# DeepEP *How DeepSeek's expert-parallel communication library moves tokens between GPUs, one major release at a time, in four parts.* ## DeepEP, Part 1: The Original Release *How DeepSeek's expert-parallel communication library moved tokens between GPUs when it came out in February 2025, read from the kernels of its first commit* If you have looked at how a mixture-of-experts (MoE) model is served on more than one GPU, you have probably seen the two words dispatch and combine. The experts of each MoE layer are spread over the GPUs, so before the experts can run, every token has to be sent to the GPUs that hold the experts the router picked for it (dispatch). Afterwards, the expert outputs have to be sent back to the GPU the token came from, where they are added up (combine). DeepEP is DeepSeek's library for exactly these two operations. Its first commit is dated February 24, 2025, and DeepGEMM, the FP8 matrix multiplication library whose grouped GEMMs run the experts on what DeepEP delivers, followed a day later. Since then, DeepEP has been rewritten once from scratch (V2, April 2026) and restructured again (V2.5, September 2026), and the latest version shares almost no code with the first one. That is why it matters a lot which version a text about DeepEP describes. The performance table in the first README, for example, was measured on kernels that no longer exist. So, what did DeepEP actually do in each version, and why did it change? This series answers that question one major release at a time. In this first part, I will go through the original release, commit ebfe47e from February 24, 2025, kernel by kernel. Part 2 covers the year of changes to V1 that followed, Part 3 the V2 rewrite together with DeepGEMM's Mega MoE kernel, and Part 4 the V2.5 release. For every version, I will ask the same four questions: - What does a GPU send for each token, over which links, and how many copies? - How does the receiver know where to put a token, and when it has arrived? - In which layout do the experts get their tokens? - What does it cost: how many SMs (the GPU's streaming multiprocessors), and does the CPU have to wait? For concrete numbers, I will use the MoE layer of DeepSeek-V3 as the reference, since every number DeepEP has published uses its shape: a hidden size of 7,168, 256 routed experts, 8 experts per token, and the group-limited routing that we will get to in a moment. I also built V1 and V2 from their own commits and measured them on one machine with eight B300 GPUs. Part 4 measures V2.5 on the same machine, but with a newer CUDA and NCCL and a different timing method, so please don't divide its numbers by the ones in this part to get a speedup. That machine has no RDMA network cards, which means only the single-machine kernels could be measured, and the first release needed a few small changes to build at all, since it was written for Hopper GPUs only. I will say what I changed when we get there. The code snippets in this article assume `import torch`, and every one of them was run before publishing. ### 1. Background #### 1.1 Dispatch and Combine Let's start with what the two operations compute, written out in plain PyTorch. The snippet below simulates 8 GPUs inside one process: each "GPU" has 16 tokens, each token picks 8 of the 256 experts, and GPU r holds experts 32r to 32r + 31. ```python torch.manual_seed(0) ranks, experts, top_k, hidden = 8, 256, 8, 64 local = experts // ranks # 32 experts per GPU x = [torch.randn(16, hidden) for _ in range(ranks)] # 16 tokens per GPU scores = [torch.randn(16, experts).softmax(-1) for _ in range(ranks)] w_top, idx = zip(*[s.topk(top_k, dim=-1) for s in scores]) W = torch.randn(experts, hidden, hidden) / hidden**0.5 # one matrix/expert def dispatch(src): # what GPU `dst` receives from GPU `src` owner = idx[src] // local return {dst: (owner == dst).any(1).nonzero().flatten() for dst in range(ranks)} def expert_out(src, dst, t): # GPU dst runs its experts on token t out = torch.zeros(hidden) for e, w in zip(idx[src][t], w_top[src][t]): if e // local == dst: out += w * (x[src][t] @ W[e]) return out # one partial sum per (token, GPU) y = [torch.zeros(16, hidden) for _ in range(ranks)] for src in range(ranks): # combine: add the partial sums for dst, tokens in dispatch(src).items(): for t in tokens: y[src][t] += expert_out(src, dst, t) ``` Two details in this snippet matter for the normal kernels that we will look at first (the low-latency kernels in section 4 do both of them differently). First, `dispatch` sends a token to a GPU once, even if two of its 8 experts live on that GPU, which is why it uses `.any(1)`. With 16 tokens and 8 experts each, GPU 0 has 128 (token, expert) pairs, but it only sends 79 copies, counting the ones it sends to itself. Second, the receiving GPU already adds up the outputs of its own experts for a token, so combine sends one partial sum per (token, GPU) and not one per expert. (If you compare `y` with a dense computation that runs all 8 experts of every token in place, the two agree to within 1e-7.) That is the whole computation. Everything else in DeepEP is about doing it fast on real hardware, which brings us to the hardware. #### 1.2 Two Networks DeepSeek trained and served V3 on H800 GPUs. Inside a machine, the 8 GPUs are connected by NVLink, which both the V3 report and DeepEP's README put at about 160 GB/s per GPU for this kind of traffic. Between machines, each GPU has its own InfiniBand network card (a ConnectX-7 at 400 Gb/s, which is about 50 GB/s). In DeepEP's terms, the GPUs inside a machine form the NVLink domain, and the machines are connected through the RDMA domain, as shown in Figure 1. ![Two machines with their NVLink and RDMA networks](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig01_domains.png) *Figure 1: Two H800 machines. Inside each, the GPUs talk over NVLink; between them, each GPU uses its own RDMA network card.* RDMA stands for remote direct memory access: a network card writes into the memory of another machine without involving that machine's CPU. With GPUDirect RDMA, the card can read from and write to GPU memory directly, so the data never has to be staged in host memory. As we can see in Figure 1, the RDMA path has about one-third the bandwidth of the NVLink path (50 versus 160 GB/s), and every token whose experts are on another machine has to be sent over it. #### 1.3 Group-Limited Routing and the Two-Hop Path This is where DeepSeek-V3's routing comes in. The DeepSeek-V3 report describes a node-limited routing, which it implements by splitting the 256 experts into 8 groups, scoring each group by the sum of the two highest expert scores in it, and letting each token pick its 8 experts only from the 4 best groups. When each machine holds one group (8 machines with 8 GPUs each, so 32 experts per machine), every token goes to at most 4 machines. Why does that matter? A token that goes to three GPUs on another machine could be sent over the network three times, once per GPU. Or it could be sent once, to the GPU with the same index on that machine, and be forwarded from there to the other two over NVLink. Figure 2 shows the two options. ![One hop versus two hops](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig02_two_hop.png) *Figure 2: Sending a token from node 0 to three GPUs on node 1, directly over RDMA (left) and via one RDMA transfer followed by NVLink forwarding (right).* We can count what the second option saves with a short simulation of 64 GPUs on 8 machines, with and without the group limit: ```python torch.manual_seed(0) tokens, experts, top_k, nodes, gpus = 100_000, 256, 8, 8, 64 groups, top_groups = 8, 4 # one group of 32 experts per node def route(scores, group_limited): if group_limited: g = scores.view(tokens, groups, -1) g_score = g.topk(2, dim=-1).values.sum(-1) # V3's group score keep = g_score.topk(top_groups, dim=-1).indices mask = torch.zeros_like(g_score).scatter_(1, keep, 1) scores = (g * mask.unsqueeze(-1)).view(tokens, -1) return scores.topk(top_k, dim=-1).indices def distinct(idx, n): return torch.zeros(tokens, n).scatter_(1, idx, 1).sum(1) scores = torch.rand(tokens, experts) for limited in (False, True): idx = route(scores, limited) n_gpu = distinct(idx // (experts // gpus), gpus) n_node = distinct(idx // (experts // nodes), nodes) print(f"group-limited={limited}: {n_gpu.mean():.2f} GPUs, " f"{n_node.mean():.2f} nodes (max {n_node.max():.0f})") # group-limited=False: 7.68 GPUs, 5.30 nodes (max 8) # group-limited=True: 7.49 GPUs, 3.95 nodes (max 4) ``` With the group limit, a token reaches 7.49 distinct GPUs on average, but only 3.95 distinct machines. If each token is sent over the network once per machine instead of once per GPU, the RDMA traffic roughly halves, and RDMA is the slow link. This is the design that DeepEP's README calls "asymmetric-domain bandwidth forwarding", and it shapes the kernels for training and prefill that we will look at in section 3. (Real scores are not uniform random numbers, of course, so the exact averages depend on the model. The upper bound of 4 machines holds for any scores, but only as long as each machine holds exactly one expert group. If the experts are placed differently, or some of them are copied to several GPUs, the bound has to be worked out again for that placement.) #### 1.4 Two Workloads The last piece of background is that there are two very different workloads. During training and prefill, each GPU holds thousands of tokens per batch (DeepEP's README uses 4,096), so dispatch moves tens of megabytes per GPU and the goal is bandwidth. During decoding, each GPU holds perhaps 128 tokens, and the whole decoding step is usually recorded as a CUDA graph so that the CPU doesn't have to launch every kernel one by one. Here the goal is latency, and nothing may require the CPU to look at the data. DeepEP V1 answers this with two separate kernel families, which it calls the normal kernels and the low-latency kernels. Sections 2 and 3 cover the normal ones, first inside one machine and then across machines, and section 4 the low-latency ones. ### 2. Normal Kernels Inside One Machine #### 2.1 Counting First Before any data moves, every GPU needs to know how many tokens it will receive, because it has to allocate the output tensor and because each sender has to know where in that tensor its tokens go. So a normal dispatch starts with a small kernel, `get_dispatch_layout`, that turns the router's choices into three tables. In PyTorch terms, it computes the following: ```python def dispatch_layout(topk_idx, num_experts, ranks): tokens = topk_idx.shape[0] rank_of = topk_idx // (num_experts // ranks) in_rank = torch.zeros(tokens, ranks, dtype=torch.bool) in_rank.scatter_(1, rank_of, True) # dedup per GPU per_rank = in_rank.sum(0) per_expert = torch.bincount(topk_idx.flatten(), minlength=num_experts) return per_rank, per_expert, in_rank torch.manual_seed(0) ranks, experts = 8, 256 idx = [torch.rand(4096, experts).topk(8).indices for _ in range(ranks)] per_rank = torch.stack([dispatch_layout(t, experts, ranks)[0] for t in idx]) # rank_prefix_matrix[i][j]: tokens that GPUs 0..i send to GPU j rank_prefix_matrix = per_rank.cumsum(0) recv_on_gpu0 = rank_prefix_matrix[-1, 0] print(f"GPU 0 receives {recv_on_gpu0} tokens; GPU 3's rows start at " f"{rank_prefix_matrix[2, 0]} and end at {rank_prefix_matrix[3, 0]}") # GPU 0 receives 21667 tokens; GPU 3's rows start at 8129 and end at 10781 ``` `is_token_in_rank` (here `in_rank`) says which GPUs each token goes to, `num_tokens_per_rank` how many tokens go to each GPU, and `num_tokens_per_expert` how many (token, expert) pairs go to each expert. The cumulative sum at the end is the step that a single GPU can't do alone: the receiver needs a prefix sum over the senders, so that the tokens from GPU 3 are placed after those from GPUs 0, 1 and 2. DeepEP calls this the rank prefix matrix. #### 2.2 The CPU Has to Wait The second kernel, `notify_dispatch`, builds that matrix. Each GPU writes its row of counts into a small area of every peer's buffer, all GPUs meet at a barrier, and then each one sums the column that belongs to it. The total number of tokens a GPU will receive, and the number for each of its local experts, end up in host memory that is mapped into the GPU's address space, and the CPU spins on them: ```cpp // csrc/deep_ep.cpp at ebfe47e, Buffer::intranode_dispatch (cut down) *moe_recv_counter = -1; for (int i = 0; i < num_local_experts; ++ i) moe_recv_expert_counter[i] = -1; intranode::notify_dispatch(..., moe_recv_counter_mapped, ..., moe_recv_expert_counter_mapped, ...); // Synchronize total received tokens and tokens per expert while (true) { num_recv_tokens = static_cast(*moe_recv_counter); bool ready = (num_recv_tokens >= 0); for (int i = 0; i < num_local_experts and ready; ++i) ready &= moe_recv_expert_counter[i] >= 0; if (ready) break; // ... throw after NUM_CPU_TIMEOUT_SECS (100 s) } // Allocate new tensors auto recv_x = torch::empty({num_recv_tokens, hidden}, x.options()); ``` Only after this loop can the CPU allocate `recv_x` and launch the kernel that moves the data, as shown in Figure 3. The per-expert counts also come back to Python as a plain list, `num_recv_tokens_per_expert_list`, which tells the expert GEMMs how many rows each expert has (section 5). ![The CPU waits in the middle of a normal dispatch](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig03_notify_timeline.png) *Figure 3: A normal dispatch in V1. The CPU waits for the GPU to report the number of tokens it will receive before it can allocate the output and launch the dispatch kernel.* This has a consequence that we will see again in every later version: a call that makes the CPU wait for a value computed on the GPU can't be recorded in a CUDA graph, because a graph replays a fixed sequence of kernels with fixed tensor sizes. The README says so directly ("the CPU will wait for GPU's signal to arrive, so this is not compatible with CUDA graph"). For prefill, where a batch is large enough that the wait is small compared with the transfer itself, this was an acceptable trade. During decoding, though, the whole transfer takes on the order of a hundred microseconds, so a round trip through the CPU would be a large fraction of it, and the step could no longer be a CUDA graph. That is one reason for the second kernel family. The README's example also shows that the output can be reused. The returned `handle` holds the prefix matrices, so a second dispatch with the same routing (the backward pass of training, for example) skips the counting and the CPU wait. #### 2.3 Channels and Ring Buffers Now the data itself. Inside one machine, every GPU can map the memory of every other GPU into its own address space (with CUDA IPC handles, which DeepEP exchanges with an `all_gather_object` when the buffer is created), so a kernel on GPU 0 can simply store into GPU 3's memory over NVLink. The intranode dispatch kernel uses the SMs in pairs. Each pair is called a channel: the even SM sends and the odd SM receives, and each channel handles a contiguous slice of the tokens. With the default of 20 SMs (`Buffer.num_sms`), there are 10 channels. Inside the sending SM, there is one warp (a group of 32 threads that execute together) per destination GPU, and each of those warps owns a ring buffer that lives in the destination GPU's memory. Figure 4 shows one channel. ![One channel of the intranode dispatch](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig04_channels.png) *Figure 4: One channel of the intranode dispatch kernel. The sender's warp for GPU 3 writes tokens into a ring buffer in GPU 3's memory and moves the tail; a receiver warp on GPU 3 copies them into the output and moves the head.* The ring buffer is the classic single-producer, single-consumer queue: a fixed number of slots (256 tokens by default), a tail index that only the sender moves and a head index that only the receiver moves. Here is the core of the sender, cut down from the kernel (and with a few long lines wrapped): ```cpp // csrc/kernels/intranode.cu at ebfe47e, dispatch(), sender warp (cut down) int cached_channel_tail_idx = 0; for (int64_t token_idx = token_start_idx; token_idx < token_end_idx;) { // Check destination queue emptiness while (send_lane_id == 0) { int num_used_slots = cached_channel_tail_idx - ld_volatile_global(channel_head_idx.buffer()); if (num_recv_buffer_tokens - num_used_slots >= num_max_send_tokens) break; // ... trap() after NUM_TIMEOUT_CYCLES (about 100 s) } __syncwarp(); int chunk_token_idx = 0; while (chunk_token_idx < num_max_send_tokens and token_idx < token_end_idx) { // ... skip tokens that don't go to this rank int dst_slot_idx = (cached_channel_tail_idx ++) % num_recv_buffer_tokens; UNROLLED_WARP_COPY(5, send_lane_id, hidden_int4, channel_x_buffers.buffer() + dst_slot_idx * hidden_int4, x + token_idx * hidden_int4, __ldg, st_na_global); // ... source index, top-k indices and weights, FP8 scales chunk_token_idx ++, token_idx ++; } // Move tail index __syncwarp(); if (send_lane_id == 0) st_release_sys_global(channel_tail_idx.buffer(), cached_channel_tail_idx); } ``` Before we get to the last line, a word on the copy itself. `UNROLLED_WARP_COPY` has every lane of the warp move 16-byte `int4` values, with 5 loads in flight per lane before the matching stores, so an FP8 token of 7,168 bytes (448 `int4`s) takes each lane 14 loads and 14 stores. The `st_na_global` store skips allocating the line in L1, since the data is going to another GPU and will never be read here again. The last line is the part that makes this work across GPUs. `st_release_sys_global` is a store with release semantics at system scope (`st.release.sys.global` in PTX). Release means that every memory write this thread made before the store becomes visible before the store itself does, so any thread that reads the new tail with a matching acquire load is guaranteed to also see the token data. System scope is needed because the reader is on another GPU, and a release at GPU scope (`.gpu`) would only order the writes for threads on the same GPU. There is one subtlety: the token data was written by all 32 lanes, but only lane 0 does the release. That is what the `__syncwarp()` just before it is for, since it orders the memory accesses of all lanes before it against the accesses that follow it, so lane 0's release covers the stores of the whole warp. Figure 5 shows the two ways of publishing the tail side by side. ![A plain store versus a release store of the tail](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig05_release.png) *Figure 5: Two ways to publish the tail of a ring buffer. With a plain store (left), GPU 3 can see the new tail before all of the token data has arrived. With `__syncwarp()` and a release store at system scope (right), a reader that loads the tail with an acquire load is guaranteed to see every token in front of it.* Without the release, the 4-byte tail could become visible on GPU 3 before the last few kilobytes of the token, and the receiver would copy a token that is only half written. With it, the receiver reads the tail with `ld.acquire.sys`, copies everything between its head and the tail into `recv_x`, and then stores the new head. With the default configuration for 8 GPUs, the sender publishes a new tail every 6 tokens (`num_max_nvl_chunked_send_tokens`) and waits only when fewer than 6 of the 256 slots are free, so neither side has to look at the other's index for every token. The receiver also needs to know how many tokens to expect on its channel and where they go, and here the kernel uses a small trick that appears all over DeepEP: it sends counts as `-value - 1`. A count of 0 becomes -1 and a count of 5 becomes -6, so the receiver can poll a zero-initialized word until it becomes negative and then decode it, and "no tokens" is distinguishable from "not written yet". Notice also that the data moves twice: once over NVLink into the ring buffer, and once more inside the receiving GPU from the ring buffer into `recv_x`. The second copy is the price of having a small queue instead of a buffer big enough for every token, and part 2 will show that people later worked to remove it. Lastly, this kernel doesn't convert anything. If you want FP8 dispatch, you pass the tokens in already as FP8 together with one fp32 scale per 128 channels, and DeepEP moves both. #### 2.4 Combine Combine runs the same machinery in the other direction. The expert outputs go back over NVLink into ring buffers on the GPU each token came from, and there, receiver warps read the up to 8 partial sums of a token (one per GPU it was sent to), add them in fp32 and write the result. But how does the receiver know which slot holds the partial sum for token t from GPU 3? During dispatch, the sender wrote down the ring-buffer position that every token got for every destination, in a tensor called `send_head` (you can see it being filled in the sender code above, with -1 for GPUs the token didn't go to). Combine sends the rows back through the same channels in the same order, so each row is written to the same position it had during dispatch. The combine receiver reads `send_head[t]`, waits until the tail of each of those rings has passed the recorded position, and then reads the rows directly from the ring buffers without any searching. This is also why combine needs the `handle` from dispatch. Figure 6 follows one token through this. ![How combine uses send_head](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig06_send_head.png) *Figure 6: The `send_head` tensor that dispatch fills on GPU 0 for one channel, with the slot that each token got in each destination GPU's ring (-1 where it wasn't sent), and the rings on GPU 0 that combine fills on the way back. Token t3 got slot 2 from GPU 3 and slot 1 from GPU 5, so that is where its two partial sums arrive.* In the figure, token t3 went to GPUs 3 and 5, so the receiver on GPU 0 reads two cells of `send_head`, waits for two tails, and adds two rows. The six GPUs that t3 didn't go to cost it nothing, since their -1 entries are skipped. One detail is easy to miss: the normal combine adds the partial sums as they are, without weights. The router weights have to be applied before the data is sent back, inside the expert computation, which is also what our PyTorch snippet in section 1.1 did with `out += w * ...`. The low-latency combine in section 4 works differently, so keep this in mind. ### 3. Normal Kernels Across Machines #### 3.1 Two Hops in One Kernel The internode kernels implement the two-hop path from Figure 2. A token on GPU 2 of node 0 that needs experts on node 1 is written over RDMA to GPU 2 of node 1, the GPU with the same index. That GPU then forwards the token over NVLink to every GPU in its machine that needs it. To know where to forward, the token carries a small header. In V1.0 it is a struct called `SourceMeta`, which holds the index of the source machine and an 8-bit mask that says which of the 8 GPUs in the destination machine need the token: ```cpp // csrc/kernels/internode.cu at ebfe47e (cut down) struct SourceMeta { int src_rdma_rank, is_token_in_nvl_rank_bits; // bit i set: GPU i of the destination machine needs this token }; ``` Since a token can go to up to 8 machines, the sender has to write it into up to 8 RDMA send buffers. The kernel caps this at 8 (`get_num_topk_rdma_ranks`), which the V3 group-limited example keeps at 4 when one expert group maps to each machine. #### 3.2 Five Warp Roles All of this happens in a single kernel, with the SMs again in pairs and the warps of each pair split into five roles. Figure 7 shows them along the path of one token. ![The five warp roles of the internode dispatch](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig07_internode_roles.png) *Figure 7: The warp roles of the internode dispatch kernel in V1.0. On the sending machine, RDMA sender warps copy tokens into per-machine send buffers and a coordinator issues the transfers. On the receiving machine, forwarder warps move tokens from the RDMA receive buffer into the NVLink ring buffers of the GPUs that need them, and receiver warps copy them out.* On the odd SM of each channel there are 7 RDMA sender warps, which walk through the channel's tokens and copy each one into the send buffer of every machine it needs, together with its `SourceMeta`, scales and top-k data. They take the tokens in order, using a small lock in shared memory, so that each machine's buffer fills sequentially. One coordinator warp watches how far the senders have come and issues the RDMA write for a chunk of tokens once it is complete, then bumps a tail counter on the remote machine. The same SM also runs 8 receiver warps, one per GPU of its own machine, which copy tokens out of NVLink ring buffers into `recv_x`, as in section 2. On the even SM, 8 forwarder warps, one per destination GPU in the machine, read tokens out of the RDMA receive buffer, check the bit for their GPU in `SourceMeta`, and push the token into that GPU's NVLink ring buffer. All 8 forwarders read the same RDMA receive buffer, each at its own pace, and a slot there can only be handed back to the sending machine once every forwarder has moved past it, since any of them might still need the token. So each forwarder records how far it has come in shared memory, and a forwarder coordinator takes the minimum over the 8 and writes it to the sending machine as the new head: ```cpp // csrc/kernels/internode.cu at ebfe47e, forwarder coordinator (cut down; // std::numeric_limits::max() shortened to INT_MAX) while (true) { // Find minimum head int min_head = INT_MAX; for (int i = 0; i < NUM_MAX_NVL_PEERS; ++ i) if (not forward_channel_retired[i]) min_head = min(min_head, forward_channel_head[i][target_rdma]); if (__all_sync(0xffffffff, min_head == INT_MAX)) break; // Update remote head if (min_head != INT_MAX and min_head > last_head and lane_id < kNumRDMARanks) nvshmem_uint64_p(rdma_channel_head.buffer(rdma_rank), last_head = min_head, translate_dst_rdma_rank( lane_id, nvl_rank)); // Nanosleep and let other warps work __nanosleep(NUM_WAIT_NANOSECONDS); } ``` A forwarder that has finished all its tokens marks itself as retired, so that it no longer holds the minimum back, and the loop ends when all 8 have retired. So there are two levels of the same ring-buffer protocol: one across the network, where the head that comes back works like a credit that allows the sender to reuse that many slots, and one inside the machine. Because each role runs in its own warps, the stages overlap: while the forwarders are pushing chunk n over NVLink, the network is already carrying chunk n+1. #### 3.3 NVSHMEM and IBRC The RDMA operations in this kernel go through NVSHMEM, NVIDIA's library that gives every GPU a symmetric heap that the others can read and write. Symmetric means that every GPU allocates the same buffers at the same offsets, so a GPU can name a location on a remote GPU by its own local address plus the target's rank, and NVSHMEM translates it. In the kernel, the sender coordinator calls `nvshmemx_int8_put_nbi_warp` to write a chunk of tokens to another machine (the whole warp builds the request, and "nbi" means the call returns without waiting for the write to finish), and the forwarder coordinator above calls `nvshmem_uint64_p` to write a single word. In V1.0, the normal kernels used NVSHMEM's default InfiniBand transport, called IBRC, in which a GPU puts a request into a queue and a CPU thread (a proxy) posts it to the network card. The low-latency kernels, as we will see next, did not, and part 2 will show that the normal kernels soon followed them. ### 4. Low-Latency Kernels #### 4.1 Requirements For decoding, the low-latency kernels give up on everything that sections 2 and 3 relied on. There is no counting kernel and no CPU wait, so that a whole decoding step can be a CUDA graph. There is no NVLink forwarding, since every hop adds latency; in V1.0, every transfer, even to a GPU in the same machine, goes over RDMA (the README calls them "low-latency kernels with pure RDMA"). And there are no ring buffers, because a queue has to be managed, and managing it takes round trips. What replaces all of it is a buffer that is large enough for the worst case. #### 4.2 A Slot for Every Token The receive buffer of a low-latency dispatch has one slot for every combination of local expert, source GPU and token index that could possibly arrive. If every GPU sends at most 128 tokens, a GPU with 32 local experts in a group of 8 GPUs reserves 32 x 8 x 128 slots, as shown in Figure 8. ![The low-latency receive buffer](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig08_ll_layout.png) *Figure 8: The receive buffer of the V1.0 low-latency dispatch. Every (local expert, source GPU, token) has its own slot, so a sender can compute the address it writes to without asking anyone.* Because every slot has a fixed address, a sender can write a token straight into it without any coordination. It only needs a running count per destination expert, which it keeps with an `atomicAdd` in its own memory. When a sender is done with an expert, it writes the number of tokens it sent into a count word next to the slots, again encoded as `-n - 1`. "Done with an expert" hides a small puzzle, though. The tokens of one GPU are spread over all of its SMs, so the copies headed for expert 17 are sent by many different warps, and the warp that sends expert 17's count has to wait until all of them have been issued. It does not know how many to wait for, since nobody has counted yet. The kernel solves this with one counter per expert and a large constant, `FINISHED_SUM_TAG`. Every warp that issues a token for expert 17 adds 1 to that expert's counter. The last warp of the SM that owns expert 17 counts how many of the GPU's tokens go there, say n, and adds `FINISHED_SUM_TAG - n`. SM 0 adds another `FINISHED_SUM_TAG` once it has cleared the buffer for the next call. The counter reaches exactly `2 * FINISHED_SUM_TAG` only when all three things have happened, in whatever order, and that is the condition the count sender spins on. Figure 9 shows three of the possible orders. ![The FINISHED_SUM_TAG counter](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig09_finished_sum.png) *Figure 9: The counter of one expert, built up from three kinds of additions. The sum reaches `2 * FINISHED_SUM_TAG` in any order, but only once all of them have arrived; with one token still missing, it stops one short.* The owner's addition is the one that makes this work. It is the only one that depends on n, and it tops the token count up to exactly `FINISHED_SUM_TAG`, whatever n turned out to be. So even if the owner and SM 0 have both added their parts while one warp is still issuing its token, the counter sits at `2 * FINISHED_SUM_TAG - 1`, and the count sender keeps waiting. On the receiving GPU, each (local expert, source GPU) pair is handled by one group of 10 warps. One warp waits for the count, then reserves a range of rows in the expert's output with another `atomicAdd`, and the 10 warps copy the tokens there. So the receive buffer has holes, since most of the 128 slots from each source stay empty, but the output tensor that the experts see is packed: expert e's tokens sit in rows 0 to n - 1, with the tokens from different source GPUs one after another. The other side of this trade is memory. We can compute the size of the buffer from the layout in `csrc/config.hpp`: ```python def ll_buffer_bytes(max_tokens, hidden, ranks, experts): scales = hidden // 128 dispatch_msg = hidden + scales * 4 + 16 # FP8 + scales + index combine_msg = 16 + hidden * 2 # header + BF16 send = max(max_tokens * dispatch_msg, experts * max_tokens * combine_msg) recv = experts * max_tokens * max(dispatch_msg, combine_msg) signal = experts * 4 + (experts // ranks) * 4 return dispatch_msg, combine_msg, 2 * (send + recv + signal) for ranks in (8, 64, 256): d, c, total = ll_buffer_bytes(128, 7168, ranks, 256) print(f"EP{ranks}: {d} B and {c} B messages, " f"{total / 2**30:.2f} GiB per GPU") # EP8: 7408 B and 14352 B messages, 1.75 GiB per GPU # EP64: 7408 B and 14352 B messages, 1.75 GiB per GPU # EP256: 7408 B and 14352 B messages, 1.75 GiB per GPU ``` (The result agrees with `Buffer.get_low_latency_rdma_size_hint` from the V1.0 build to within its 128-byte alignment.) A dispatch message is the FP8 token (7,168 bytes), its 56 scales (224 bytes) and a 16-byte header with the token's index on the source GPU, 7,408 bytes in total. A combine message is the BF16 output with a 16-byte header, 14,352 bytes. The buffer comes out at 1.75 GiB per GPU for 128 tokens, and interestingly, it doesn't depend on the number of GPUs: the receive buffer has a slot for every (expert, token) pair of the whole group, which is 256 x 128 regardless of how the 256 experts are spread. Notice the `max` in both lines. Dispatch and combine never run at the same time on one buffer, so they share the same memory, and its size is set by combine, whose messages are twice as large. The factor of 2 at the end is there because the buffer is double buffered: consecutive calls alternate between two halves. The token slots never need to be cleared, since a slot is only read up to the count that arrived with it. What does need clearing are the count words, which a receiver polls until they become non-zero, and each call zeroes the count words of the other half for the next call, so no call has to wait for a clean-up. #### 4.3 The GPU Talks to the Network Card The next problem is that an RDMA write normally starts on the CPU. With IBRC, the GPU hands every request to a proxy thread, which adds a trip through the CPU to every message. The low-latency kernels instead use IBGDA (InfiniBand GPUDirect Async), in which GPU threads write the network card's work requests themselves. A network card is driven through queue pairs (QPs). To send, software writes a work queue entry (WQE) into the send queue (the entry describes "write these bytes from this local address to that remote address with that key"), then writes the new queue index into a doorbell register on the card. With IBGDA, the queues and the doorbell are mapped into GPU memory, so a warp can do it. Here is the WQE that a warp builds for an RDMA write, from DeepEP's own IBGDA code (the casts around the three stores are removed): ```cpp // csrc/kernels/ibgda_device.cuh at ebfe47e, ibgda_write_rdma_write_wqe raddr_seg.raddr = HtoBE64(raddr); raddr_seg.rkey = rkey; raddr_seg.reserved = 0; data_seg.byte_count = HtoBE32(bytes); data_seg.lkey = lkey; data_seg.addr = HtoBE64(laddr); ctrl_seg = {0}; ctrl_seg.qpn_ds = HtoBE32((qp->qpn << 8) | 3); ctrl_seg.fm_ce_se = MLX5_WQE_CTRL_CQ_UPDATE; ctrl_seg.opmod_idx_opcode = HtoBE32((wqe_idx << 8) | MLX5_OPCODE_RDMA_WRITE); // Three 16-byte stores into the send queue, which lives in GPU memory st_na_relaxed(ctrl_seg_ptr, ctrl_seg); st_na_relaxed(raddr_seg_ptr, raddr_seg); st_na_relaxed(data_seg_ptr, data_seg); ``` These are the actual bytes of a Mellanox mlx5 work request, assembled by GPU threads and converted to big-endian, since that is the byte order the card reads. The control segment names the queue pair, the WQE's position in the queue and the opcode, and the `| 3` says that the WQE is three 16-byte segments long: the control segment, the remote address with its key, and the local address with its key and length. Writing the WQE is only half of it, because the card doesn't know yet that a new entry exists. Many warps post to the same queue at once, so the posting follows a small protocol, which lives in the same file. A warp first reserves its slots with an `atomicAdd` on the queue's reservation counter, writes its WQE, and issues a `__threadfence()` so that the WQE is visible in memory before anything else happens. Then it waits until all warps that reserved earlier slots have finished theirs (a compare-and-swap loop on a `ready_head` counter), because the card processes the queue strictly in order and must not be told about slot 10 while slot 9 is still half written. Finally, it writes the new producer index into the queue's doorbell record in memory and rings the doorbell with an 8-byte store to the card's doorbell register (mlx5 calls it the BlueFlame register). Both are release stores, so the card cannot see the doorbell before the WQE. Figure 10 shows a moment in this protocol with three warps. ![Posting a work request with IBGDA](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig10_ibgda_post.png) *Figure 10: Three warps posting RDMA writes to one queue pair. Each warp reserves a slot, writes its WQE, waits until `ready_head` reaches its slot, and then writes the doorbell record and rings the doorbell register on the network card.* In the figure, warp C has finished slot 11, but it is stuck in the compare-and-swap loop, since `ready_head` is still 10 and warp B is still writing slot 10. Once warp B is done, it moves `ready_head` to 11 and rings the doorbell for its own entry, and only then can warp C move it to 12 and ring the doorbell with the new index 12. DeepEP uses one queue pair per local expert (the kernel checks that the number of queue pairs per peer equals the number of local experts), so that the warps sending to different experts never contend for the same queue. How does the receiver find out that a count has arrived? In V1.0, the count is written with an RDMA write with immediate data, which consumes a receive request that the receiver has posted in advance and produces a completion entry on the receiver's completion queue. The receiving warp polls that completion queue (`nvshmemi_ibgda_poll_recv`), and because RDMA writes on one queue pair are delivered in order, once the count has arrived, so have all the tokens before it. Stock NVSHMEM had no receive queue for IBGDA, which is why V1.0 required a patched NVSHMEM that DeepSeek shipped with the repository (`third-party/nvshmem.patch`). We will see in part 2 that this mechanism lasted less than three weeks. #### 4.4 FP8 Inside the Kernel Unlike the normal kernels, the low-latency dispatch takes BF16 tokens and converts them to FP8 itself, while it copies them into the send buffer. Each thread reads 8 BF16 values (16 bytes), and a half-warp of 16 threads covers 128 channels, so one shuffle-based reduction over the half-warp gives the maximum absolute value of those 128 channels. The scale is 448 (the largest FP8 E4M3 value) divided by that maximum, and its inverse is stored in the message for the receiver, which is exactly the per-token, per-128-channel scaling that DeepSeek-V3 used and DeepGEMM expects. (The maximum starts at 1e-4 instead of 0, so that a block of zeros doesn't produce a division by zero.) The receiver also writes the scales out transposed: the scale tensor it returns has the token index as its fastest dimension, `[local experts, 56, GPUs x 128]` in memory, because that is the layout in which DeepGEMM's FP8 GEMM loads the scales of a whole block of rows at once. #### 4.5 Combine Applies the Weights The low-latency combine runs on the GPU that holds the experts. For each of its local experts and each source GPU, it sends the BF16 outputs back, and the address is again fixed in advance: the receive buffer is indexed by the global expert index and the token's original position, both of which the receiver already knows. (The token's original position is the index that dispatch sent in the 16-byte header of each message.) Each (expert, GPU) pair then writes a flag. Once a GPU has seen all of its flags, the kernel runs a grid-wide barrier, `cg::this_grid().sync()`, which is why the combine kernel is launched as a cooperative kernel whose blocks must all be resident at once. After the barrier, every SM walks over its share of the tokens, reads the 8 rows that belong to each token's top-8 experts, multiplies each by its router weight, and adds them up in fp32. So in contrast to the normal combine, the low-latency combine applies the router weights itself, and it receives one message per (token, expert) pair and not one per (token, GPU). For 128 tokens with 8 experts each, that is 1,024 messages of 14 KB per GPU, compared with about 678 on average if they were deduplicated per GPU on 8 GPUs (128 tokens times the 5.29 distinct GPUs that a token reaches on average with uniform routing). In exchange, there is no reduction on the sending side and nothing to coordinate. #### 4.6 The Hook The last idea in the low-latency kernels is the one that the README calls "hook-based communication-computation overlapping", which "does not occupy any SM resource". The dispatch and combine kernels are split into a send phase and a receive phase (`LOW_LATENCY_SEND_PHASE` and `LOW_LATENCY_RECV_PHASE` in the code). With `return_recv_hook=True`, the call only runs the send phase, which writes the work requests and returns. The network card then moves the data on its own, and the caller gets back a function, the hook, that runs the receive phase when it is called. This pays off when the framework has independent work to schedule before calling the hook. The V3 report uses two micro-batches for prefill and discusses exploring the same overlap for decode. Figure 11 sketches such a schedule: while the network carries micro-batch 0's tokens, the SMs run micro-batch 1's attention. ![Overlapping two micro-batches with the hook](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig11_hook.png) *Figure 11: Two micro-batches with the receive hook. The send phase of dispatch and combine only posts the transfers, so the SMs are free to work on the other micro-batch until the hook collects the data.* The send and receive phases themselves do occupy SMs while they run. The low-latency kernels launch one SM per three experts, with 30 warps per SM in three groups of 10, so 86 SMs for 256 experts. In the send phase of dispatch, each SM takes whole tokens in turn: 29 warps convert the token to FP8 together, and then warp i sends the copy for the token's i-th expert, while the 30th warp counts tokens per expert for the count messages. In the receive phase, each group of 10 warps takes one (local expert, source GPU) pair, as described above. These phases run briefly, though, and with the hook, no SM is kept busy while the data is in flight, which is what the README means by "without any SM occupation". ### 5. The Other Half: DeepGEMM's Two Layouts Getting the tokens to the right GPU is only half the job, since the experts then have to run a matrix multiplication on them, and the GEMM cares a lot about how the rows are laid out in memory. The two dispatch families hand over very different layouts, and DeepGEMM's first commit provides a grouped GEMM for each of them. Both are "grouped" along the token dimension only: every expert has the same weight shape, and only the number of tokens per expert differs. For prefill, the normal dispatch returns one row per received token, grouped by source rank rather than by expert. The framework has to copy a token once for every local expert it selected and reorder the rows into DeepGEMM's contiguous layout, which expects rows sorted by expert, with each expert's segment padded to a multiple of the GEMM's block size (`get_m_alignment_for_contiguous_layout()`, 128 rows) and a tensor `m_indices` that says which expert each row belongs to. The padding is there because each thread block of the GEMM computes a tile of 128 rows and loads the weights of exactly one expert for it, so a tile must never contain rows of two experts. Rows marked -1 in `m_indices` are padding, and the kernel skips their tiles. DeepEP's `expert_alignment` argument exists so that the per-expert counts it reports can be rounded up to this alignment. For decoding, the low-latency dispatch returns a fixed-size tensor of shape [local experts, GPUs x max tokens, hidden], together with the number of valid rows per expert. That is DeepGEMM's masked layout, `m_grouped_gemm_fp8_fp8_bf16_nt_masked`, which takes the count tensor `masked_m` on the GPU and simply skips the rows beyond it, so the shapes never change and the GEMM can be part of the CUDA graph. (DeepGEMM's README even names the use case: "An example usage is to use the output of low-latency kernels from DeepEP as input.") Figure 12 shows both. ![Contiguous and masked layouts](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig12_gemm_layouts.png) *Figure 12: The contiguous layout (left) used after a normal dispatch, and the masked layout (right) used after a low-latency dispatch, for four local experts that received 300, 0, 45 and 129 tokens.* Here is how the two are built, with a plain matrix multiplication standing in for the FP8 GEMM: ```python torch.manual_seed(0) local, hidden, n, align = 4, 64, 32, 128 counts = torch.tensor([300, 0, 45, 129]) # tokens received per expert xs = [torch.randn(c, hidden) for c in counts] W = torch.randn(local, n, hidden) # NT: weights are [N, K] # Contiguous layout (prefill): one tensor, each expert padded to `align` padded = (counts + align - 1) // align * align m_indices = torch.repeat_interleave(torch.arange(local), padded) lhs = torch.zeros(int(padded.sum()), hidden) starts = torch.cumsum(padded, 0) - padded for e in range(local): lhs[starts[e]:starts[e] + counts[e]] = xs[e] m_indices[starts[e] + counts[e]:starts[e] + padded[e]] = -1 out_contig = torch.einsum('mk,mnk->mn', lhs, W[m_indices.clamp(min=0)]) # Masked layout (decode): a fixed [experts, max_m, K] slab plus counts max_m = 512 lhs_masked = torch.zeros(local, max_m, hidden) for e in range(local): lhs_masked[e, :counts[e]] = xs[e] out_masked = torch.bmm(lhs_masked, W.transpose(1, 2)) # rows >= count unused ``` The contiguous layout needs 768 rows for 474 tokens here, because of the padding, but its size depends on the actual counts, so the CPU has to know them, which the normal dispatch's CPU wait provides. The masked layout needs 4 x 512 rows no matter what, but its shape is fixed. The same trade between memory and knowing the counts on the CPU runs through every DeepEP version, and V2 ends up offering both from one function. ### 6. An Instruction That Isn't in the Manual One more detail of V1.0 is worth knowing about, because the README is unusually frank about it. To read data that another GPU is writing, the kernels need loads that bypass any stale cached copy. The obvious choice is a volatile load, but DeepSeek found a faster one: `ld.global.nc.L1::no_allocate.L2::256B`, a load through the read-only (non-coherent) path that doesn't allocate in L1 and prefetches 256 bytes into L2. Reading memory that changes through a non-coherent load is undefined behavior according to the PTX documentation. The README says the result was tested to be correct on Hopper with `.L1::no_allocate` and offers `DISABLE_AGGRESSIVE_PTX_INSTRS=1` for other GPUs. (A later version of the README adds a guess for why it works: on Hopper, the non-coherent cache and L1 are the same hardware, so not allocating in L1 means there is no stale copy to read.) The comment next to the instruction in `utils.cuh` explains the other half: the load compiles to `LDG.E.NA.CONSTANT` in SASS, which has no coherence control, "so we have to control them by queue semantics". In other words, the kernels only ever use this load on buffer slots after an acquire load of a tail or a count has shown that the slot was written, and the tails and counts themselves are always read with proper acquire or volatile loads. The fast load never decides by itself whether data is there. When I built V1.0 for B300, I turned the aggressive PTX off, and later versions do this automatically for anything other than Hopper. ### 7. How V1.0 Runs Today DeepEP's README for V1.0 reports, on H800 with 4,096 tokens per GPU, FP8 dispatch and BF16 combine, 153 GB/s for dispatch and 158 GB/s for combine inside one machine, which it labels as the NVLink bottleneck. For the low-latency kernels with 128 tokens on 8 GPUs, it reports 163 us for dispatch and 318 us for combine, over RDMA. On the B300 machine, V1.0 needed three changes to build: the GPU architecture had to come from the environment instead of being fixed to Hopper, it had to link the NVSHMEM from PyPI instead of the patched static library, and the three functions that use the patched receive queue (section 4.3) had to be stubbed out, since stock NVSHMEM doesn't have it. That last change only affects the low-latency kernels, which can't run on this machine anyway, since it has no RDMA network cards and V1.0's low-latency kernels use RDMA even inside one machine. With those changes, V1.0's own intranode test passes all 24 correctness cases. Figure 13 shows the bandwidth of the normal intranode kernels for 4,096 tokens per GPU on 8 GPUs, as a function of the number of SMs they get. ![V1.0 normal kernels on B300](https://sleepy-capybara.vercel.app/deepep/1-original-release/figures/fig13_v1_0_sms.png) *Figure 13: Bandwidth of V1.0's intranode dispatch (FP8) and combine (BF16) on eight B300 GPUs, 4,096 tokens per GPU, as a function of the SMs they use. The time is the sum of the kernel durations, including the layout and notify kernels.* With the 24 SMs from the README example, the summed dispatch kernel durations are 873 us, which is 183 GB/s of received data, and combine takes 733 us (424 GB/s). (Since dispatch moves FP8 and combine BF16, combine carries twice the bytes in less time.) Of the 873 us, the layout kernel takes 46 us and the notify kernel 28 us, so almost all of it is the dispatch kernel itself, which runs only 8 warps per SM, one for each destination GPU. The combine kernel runs 24. As shown in Figure 13, both keep improving all the way to 64 SMs, where dispatch reaches 310 GB/s and combine 609 GB/s. On H800, the README calls 153 GB/s an NVLink bottleneck, which makes sense next to the roughly 160 GB/s it quotes for the link. On B300, whose NVLink is several times faster, my reading of Figure 13 is that V1.0's kernels run out of SMs long before they run out of link, because every byte passes through SM registers twice, once into the ring buffer and once out of it. That is the problem that most of the next two versions work on. Two caveats about these numbers. First, the time is the sum of the GPU kernel durations from a profiler, not the time a Python call takes, so it leaves out the CPU wait from section 2.2. Second, the bytes in the numerator include the copies that each GPU sends to itself, which never touch NVLink. So the numbers say how fast V1.0's kernels move data inside one B300 machine, and nothing about InfiniBand or about how long a full V3 serving step takes. #### 7.1 How DeepSeek Actually Deployed It There is one more thing to keep in mind before we move on. The toy snippets in this article give GPU r the experts 32r to 32r + 31, with `experts // ranks`, and the 64-GPU example uses one expert group per machine, which matches how V3 was trained. The serving setup that the V3 report describes in its deployment section looks different. Prefill ran as EP32 on four machines, and decode ran as EP320 on forty machines, with one expert per GPU. 320 is more than 256, and the difference comes from the shared expert, which decode treats as a routed expert that every token selects, and from redundant copies of the most heavily used experts. So in a real deployment, the router picks a logical expert, a placement policy then picks one of its physical copies, and only that copy determines the destination GPU. The dispatch kernels themselves don't care, since they only see destination ranks, but every count in this article that was derived from `experts // ranks` would come out differently. This is also why I would not read the README's 128-token, 8-GPU low-latency example as a deployment recommendation. The fixed-size buffers are meant for large decode groups like EP320, where each expert only gets a small batch. ### 8. Summary To summarize, the original DeepEP answered the four questions like this: 1. **What is sent.** Normal kernels send each token once per destination GPU inside a machine, and once per destination machine across machines, forwarding over NVLink on the far side. Low-latency kernels send it once per destination expert, always over RDMA. 2. **How the receiver knows.** Normal kernels count first, exchange prefix sums, and stream tokens through ring buffers with release/acquire head and tail indices. Low-latency kernels give every possible token a fixed slot and signal counts as `-n - 1`, with arrival detected through RDMA completions. 3. **The layout.** Normal dispatch produces a tensor grouped by source GPU, which the caller expands and reorders for DeepGEMM's contiguous grouped GEMM; low-latency dispatch produces a fixed [experts, tokens, hidden] slab for the masked one. 4. **The cost.** A normal dispatch with new routing makes the CPU wait for the counts, so it can't be part of a CUDA graph (a dispatch that reuses the routing from a `handle` skips the wait), and its data passes through the SMs twice, on a configurable number of SMs (20 by default). Low-latency kernels need no CPU and can hand the waiting to the network card with the hook, but they reserve 1.75 GiB per GPU and send up to 8 copies of each token. In part 2, we will follow V1 through the following year, in which almost every one of these answers changed: the low-latency kernels learned to use NVLink, the network transport moved from a CPU proxy to the GPU and the patched NVSHMEM disappeared, TMA replaced most of the copy loops, and the normal kernels learned to run without the CPU wait. ### Sources - [DeepEP at the first commit (ebfe47e)](https://github.com/deepseek-ai/DeepEP/tree/ebfe47e46fa86a5b41be96c326a92f62ed6721da) - [DeepGEMM at the first commit (a6d97a1)](https://github.com/deepseek-ai/DeepGEMM/tree/a6d97a1c1b48a7a9d7994d0e155ee6f11d0a3f07) - [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) - [NVIDIA: Improving Network Performance of HPC Systems Using NVIDIA Magnum IO NVSHMEM and GPUDirect Async](https://developer.nvidia.com/blog/improving-network-performance-of-hpc-systems-using-nvidia-magnum-io-nvshmem-and-gpudirect-async/) - [PTX ISA: memory consistency model and ld instruction](https://docs.nvidia.com/cuda/parallel-thread-execution/) ## DeepEP, Part 2: A Year of V1 *What changed in DeepEP between its release in February 2025 and the V2 rewrite, from adaptive routing and NVLink for decoding to TMA copies and 10-bit combines, measured on the same machine* In part 1, we went through the first commit of DeepEP, DeepSeek's library for the two all-to-all steps of an MoE layer: dispatch, which sends every token to the GPUs that hold its experts, and combine, which brings the expert outputs back and adds them up. That release had two kernel families. The normal kernels, for training and prefill, count the tokens first, make the CPU wait for the counts, and then stream the data through ring buffers, forwarding it over NVLink after it has arrived over the network. The low-latency kernels, for decoding, reserve a fixed slot for every token that could possibly arrive and write into it with RDMA, which the GPU drives directly. DeepEP V1 then stayed in use for more than a year, until the V2 rewrite in April 2026, and it changed a lot in that time. The repository got 208 commits (not counting merges) between the first release and the last V1 commit on February 3, 2026, and many of them came from outside DeepSeek, from teams at Tencent, Baidu, NVIDIA, Alibaba and others. Almost every answer that part 1 gave to its four questions (what is sent, how the receiver knows, which layout the experts get, and what it costs) changed along the way, some of them more than once. In this part, I will go through these changes by topic rather than by date, since most topics span several commits. For each one, I will look at what the code did before and after, and why. Along the way, I will compare three builds on the same machine with eight B300 GPUs that I used in part 1: the first release (V1.0), the `v1.2.1` tag from September 15, 2025, which is the only release tag V1 ever got, and the last V1 commit from February 2026. As in part 1, the machine has no RDMA network cards, so only the kernels that run inside one machine could be measured, and the code snippets assume `import torch`. ### 1. The Year in Commits Before going into the details, Figure 1 puts the changes on a timeline, together with what happened in DeepGEMM, the GEMM library that consumes DeepEP's output. ![Timeline of DeepEP V1 and DeepGEMM in 2025](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig01_timeline.png) *Figure 1: The main changes to DeepEP V1 (top) and DeepGEMM (bottom) between February 2025 and February 2026.* As we can see in Figure 1, the changes come in three waves. In March 2025, right after the release, came DeepSeek's own fixes, mainly around adaptive routing. Between April and July, most of the performance work landed: NVLink for the low-latency kernels, GPU-driven RDMA for the normal kernels, TMA copies, and the end of the patched NVSHMEM. From August on, the changes were mostly about formats, operations and new GPUs, and the bigger ideas moved into separate branches, several of which look a lot like what V2 later did. ### 2. Adaptive Routing and Atomics #### 2.1 What Adaptive Routing Breaks The first change after the release was about the network itself. An InfiniBand switch normally sends all packets from one port to another along the same path, which keeps them in order but lets two busy flows collide on one link while another link sits idle. Adaptive routing (AR) lets the switch pick a less loaded path for each packet. The README of the first release said that the low-latency kernels supported it, but that "enabling adaptive routing for normal internode kernels may lead to deadlocks or data corruption issues", and the Python code reminded users that AR "must be off". Why would a routing feature corrupt data? Remember from part 1 that the internode kernels use two ring buffers across the network: the sender advances a tail on the receiving machine, and the receiving machine sends the head back as a credit, so that the sender knows which slots it can reuse. In the first release, the forwarders sent their head back as a plain RDMA write of the new value (`nvshmem_uint64_p`). If the switch sends two of those writes along different paths, the older value can arrive after the newer one, and the head moves backwards, as shown in Figure 2. ![Plain writes versus atomic adds under adaptive routing](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig02_ar.png) *Figure 2: Two credit updates take different paths through the network and arrive in reverse order. A plain write leaves the older value behind (left); atomic adds of the differences give the right result in any order (right).* We can see how often that goes wrong with a tiny simulation. The forwarders report six heads in a row, and the network delivers the six messages in a random order: ```python torch.manual_seed(0) heads = [3, 7, 12, 20, 26, 31] # the forwarders' progress # Before: write the new head (a plain RDMA write, last one wins) # After: add the difference to the old head (an RDMA atomic) deltas = [h - p for h, p in zip(heads, [0] + heads[:-1])] regressions = 0 for trial in range(1000): order = torch.randperm(len(heads)).tolist() # adaptive routing reorders written = 0 added = 0 for i in order: written = heads[i] added += deltas[i] regressions += written != heads[-1] assert added == heads[-1] print(f"plain writes ended on a stale head in {regressions} of 1000 runs; " f"atomic adds never did") # plain writes ended on a stale head in 831 of 1000 runs; atomic adds never did ``` A stale head means the sender thinks slots are still in use when they are free, and since the next update may never come, the sender can wait forever, which is the deadlock the README warned about. #### 2.2 The Fix The fix, which landed on March 5, 2025 (commit 458cdcb), is the second half of the snippet: instead of writing the new head, the forwarder coordinator adds the difference between the new head and the last one it reported, using an atomic add (`nvshmemx_signal_op` with `NVSHMEM_SIGNAL_ADD`). Additions commute, so the order of arrival no longer matters: ```cpp // csrc/kernels/internode.cu, forwarder coordinator, after 458cdcb (cut down) if (min_head != INT_MAX and min_head > last_head and lane_id < kNumRDMARanks) { nvshmemx_signal_op(rdma_channel_head.buffer(rdma_rank), min_head - last_head, NVSHMEM_SIGNAL_ADD, translate_dst_rdma_rank( lane_id, nvl_rank)); last_head = min_head; } ``` The tail already worked this way, so after this commit, the README's warning was gone and its recommendation became the same for both kernel families: enable adaptive routing when the network is heavily loaded, and use static routing when it is lightly loaded. Nine days later, the low-latency kernels got the same treatment (commit 2d0cf41, "Low latency kernels use rdma atomic to support AR"). In part 1, we saw that V1.0 signalled the arrival of a count with an RDMA write with immediate data, which the receiver detected by polling its completion queue for the matching receive. That relied on the receive queue that DeepSeek's NVSHMEM patch added, and on the order of messages within a queue pair. The new code sends the count as an atomic add into a zero-initialized word, and the receiver simply spins on that word: ```cpp // csrc/kernels/internode_ll.cu after 2d0cf41, receiving side (cut down) while ((num_recv_tokens = ld_acquire_global( rdma_recv_count + local_expert_idx * num_ranks + src_rank)) == 0); num_recv_tokens = -num_recv_tokens - 1; ``` The `-n - 1` encoding from part 1 does the rest: a zero means "not arrived yet", and any arriving count is negative. ### 3. Decoding Learns to Use NVLink #### 3.1 RDMA Between Neighbors The low-latency kernels of the first release used RDMA for every destination, including the GPUs in the same machine. A token going from GPU 0 to GPU 3 of the same machine went down to GPU 0's network card, out to the switch, back into GPU 3's network card, and up into GPU 3's memory, even though the two GPUs were connected by NVLink. The reason was simplicity: with one transport, every destination looks the same to the kernel. On a small expert-parallel group, though, most destinations are neighbors. With 8 GPUs, every destination is in the same machine, and with 16 GPUs on two machines, half of them are. In May 2025, a contribution from Baidu (commit 68ae8b3, "LL nvlink p2p") added a check to every send: if NVSHMEM can map the destination's buffer into this GPU's address space, write to it directly over NVLink; otherwise, post an RDMA write as before. Figure 3 shows the two paths. ![The low-latency path to a neighbor, before and after](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig03_ll_nvlink.png) *Figure 3: A low-latency dispatch from GPU 0 to GPU 3 of the same machine in the first release (left), which goes through both network cards, and after May 2025 (right), which uses NVLink.* The change itself is short. When NVSHMEM sets up its symmetric heap, it maps the heaps of all GPUs that are reachable over NVLink into each GPU's address space, much like the CUDA IPC handles that the normal kernels exchange. It keeps, for every peer, the base address at which the peer's symmetric heap is mapped into the local address space (`peer_heap_base_p2p`), or zero if the peer can't be reached that way. The kernel translates the remote address by the offset between the two heaps and copies the token with an ordinary warp copy: ```cpp // csrc/kernels/internode_ll.cu after 68ae8b3, dispatch send (cut down) void *peer_base = (void *)__ldg((const long long unsigned *) nvshmemi_device_state_d.peer_heap_base_p2p + dst_rank); if (peer_base) { // reachable over NVLink: store directly char *dst = (char *)peer_base + ((char *)dst_ptr - (char *)nvshmemi_device_state_d.heap_base); UNROLLED_WARP_COPY(8, lane_id, num_int4_per_msg, (int4 *)dst, (const int4 *)src_ptr, ld_nc_global, st_na_global); } else { // another machine: post an RDMA write nvshmemi_ibgda_put_nbi_warp(dst_ptr, src_ptr, num_bytes_per_msg, dst_rank, dst_expert_local_idx, lane_id, slot_idx); } ``` The count and the combine's finishing flag got the same branch, with a release store instead of an RDMA atomic. #### 3.2 What It Bought According to the README, which DeepSeek updated with the new numbers in June, the low-latency dispatch on 8 GPUs went from 163 us to 77 us, and the combine from 318 us to 114 us (for 128 tokens on H800). On 16 GPUs, where half of the destinations are inside the machine, dispatch went from 173 us to 118 us. On 64 GPUs, where almost all traffic leaves the machine, dispatch only went from 186 us to 173 us, as we would expect. On the B300 machine, the low-latency kernels of `v1.2.1` take 31.4 us for a dispatch of 128 tokens per GPU and 42.6 us for the combine (the sum of all kernels of each call; DeepEP's own test, which times them slightly differently, reports 30.0 us and 39.5 us). That is much less than the README's 77 and 114 us, but the GPUs, the CUDA version and the timing method are all different, so I wouldn't read the ratio as the speedup of anything in particular. There is an interesting consequence: on one machine, the low-latency kernels are now faster than the normal ones even for batches of several hundred tokens. We can see this in Figure 4, which compares the two on the B300 machine for batches of up to 512 tokens per GPU. ![Low-latency and normal kernels on one machine](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig04_ll_vs_normal.png) *Figure 4: Summed device-kernel durations for the low-latency and normal kernels of DeepEP v1.2.1 on eight B300 GPUs, by tokens per GPU. FP8 dispatch and BF16 combine; CPU waits and inter-kernel gaps are excluded.* As shown in Figure 4, a normal dispatch of 128 tokens takes 63 us, twice as long as the low-latency one, partly because it includes the layout and notify kernels. And that is before the CPU wait for the counts, which the plotted kernel sum leaves out and which would make the gap larger. The low-latency kernels pay for their speed with memory, though: at 512 tokens per GPU, the buffer from part 1's formula grows to 7 GiB per GPU, which is one reason they stayed a decoding tool. ### 4. The GPU Drives the Network Card #### 4.1 Proxy and IBGDA The normal internode kernels of the first release used NVSHMEM's default InfiniBand transport, IBRC. In IBRC, a GPU thread that wants to send something writes a request into a queue in host memory, and a CPU thread, called the proxy, picks it up and posts it to the network card. The low-latency kernels, in contrast, used IBGDA, where the GPU writes the network card's work request and rings its doorbell itself. Figure 5 shows the two. ![IBRC with a CPU proxy versus IBGDA](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig05_proxy_vs_ibgda.png) *Figure 5: With IBRC (left), every GPU-initiated transfer goes through a CPU proxy thread. With IBGDA (right), GPU threads write the work request into the send queue and ring the doorbell directly.* The proxy has two costs. Every message waits for the CPU thread to notice it, and one proxy thread with one queue pair per peer limits how many transfers can be in flight. In April 2025, Tencent's network team contributed a change (commit 5ab80c2, merged as PR #130) that moved the normal kernels to IBGDA as well and gave every channel its own queue pair. In their words: "a single QP is used for data transfer between two GPUs, which limits kernel performance in network card dual-port and RoCE network scenarios." The reason is that both the card and the network spread traffic per queue pair, not per message: a dual-port card puts each queue pair on one of its ports, and a RoCE network picks one path per queue pair by hashing its packet headers. With one queue pair between two GPUs, all their traffic ends up on one port and one path. The README got a news entry ("performance was enhanced by up to 30%"), and its internode numbers changed from 44 to 58 GB/s on 32 GPUs and from 46 to 51 GB/s on 64. A month later, commit 9fe9021 ("Use IBGDA only") replaced the remaining NVSHMEM puts in the counting kernels with DeepEP's own IBGDA code, including a simplified completion-queue poll, and turned the barriers between machines into lighter `nvshmem_sync` calls. From then on, the data transfers and signals of both kernel families were work requests written by GPU threads. #### 4.2 Smaller Fixes Along the Same Line A few more changes in this area are worth knowing about, because they show what kind of problems a GPU-driven network stack runs into: - **Incast.** If every GPU starts sending to rank 0, then rank 1, and so on, all of them hit the same receiver at the same time. Commit 63c29d0 makes each rank and channel start at a different destination. - **One queue pair per SM.** Commit 05df555 gave every SM its own queue pair, so that warps of different SMs never contend for a queue. - **Atomics on PCIe.** RDMA atomics, which the AR fix relies on, are executed by the network card on GPU memory across PCIe, and V2's README later recommends setting the card's `PCI_ATOMIC_MODE` to make them faster. #### 4.3 Out-of-Order Senders One more change in this area is a nice piece of engineering. In part 1, the 7 RDMA sender warps of a channel took tokens strictly in order, using a lock in shared memory, so that a token's slot in a machine's send buffer was only marked as filled after all earlier slots were. A slow warp held up all the others. In June 2025, commit bc118b2 removed the waiting in two steps. The first step is about handing out the slots. Instead of taking turns, every sender warp now walks over all of the channel's tokens and reads each token's destination mask, but copies only every 7th token, its own. Since every warp sees the same sequence of masks, every warp can count for itself how many earlier tokens went to machine m, and that count is the slot of the current token in machine m's buffer. No warp has to ask any other, and reading a mask is cheap compared with copying a 7 KB token. Figure 6 shows this for one channel. ![Slot assignment without a lock](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig06_slot_count.png) *Figure 6: The tokens of one channel, the machines each one goes to, and the warp that copies it. Every warp reads all of the masks, so warp 3 can work out by itself that six earlier tokens go to machine 1 and that t10 takes slot 6 there.* In the figure, warp 3 copies tokens t3 and t10. To find t10's slot in machine 1's buffer, it doesn't need to know where warps 0 to 2 are; it counts the tokens to the left of t10 that go to machine 1, six of them, and writes t10 into slot 6. Every other warp computes the same counts for its own tokens, so no two warps can pick the same slot. The second step is about reporting the slots as filled. The coordinator may only send slots up to the first one that is still being written, so the warps need to agree on a tail. For this, the commit adds what the code calls a transaction window: for every destination machine, a 32-bit mask of the slots that have been filled but are not yet covered by the tail. A warp that finishes a slot sets its bit, and if it was the oldest slot, it advances the tail over the whole run of finished slots in front of it. In Python, the release step looks like this: ```python def release(window, tail, slot): """A sender warp finished `slot`; move the tail if it can.""" offset = slot - tail assert 0 <= offset < 32 # at most 32 slots in flight window |= 1 << offset if offset == 0: # the oldest slot just finished run = (window ^ (window + 1)).bit_length() - 1 # trailing ones tail += run window >>= run return window, tail window, tail = 0, 0 for slot in [2, 0, 1, 4, 3, 5]: # warps finish out of order window, tail = release(window, tail, slot) print(f"slot {slot} done -> tail {tail}") # slot 2 done -> tail 0 # slot 0 done -> tail 1 # slot 1 done -> tail 3 # slot 4 done -> tail 3 # slot 3 done -> tail 5 # slot 5 done -> tail 6 ``` If you have seen how an out-of-order CPU retires instructions, this is the same idea: work finishes in any order, but becomes visible in order. The kernel does the trailing-ones count with `__ffs(~window) - 1` and keeps the window in shared memory behind a small lock that is only held for these few instructions. #### 4.4 Goodbye to the Patched NVSHMEM The first release needed DeepSeek's own patch to NVSHMEM 3.1.7: it added a receive queue to IBGDA (used by the write-with-immediate signalling from section 2), changed how queue pairs were created and how completions were tracked. After the AR fix, the receive queue was no longer needed, and in July 2025, NVIDIA engineers contributed a series of commits (starting with 441833d) that moved DeepEP onto stock NVSHMEM 3.3.9. They also documented how to use NVSHMEM's CPU-assisted IBGDA, a mode in which the CPU rings the doorbell on the GPU's behalf, for machines where the driver settings that IBGDA needs can't be changed. From then on, `pip install nvidia-nvshmem-cu12` was enough. (This is also why I could build the first release on the B300 machine at all: NVSHMEM 3.4.5 has the queue fields that V1.0's IBGDA code expects, except for the receive queue.) ### 5. TMA and More Warps #### 5.1 Two Changes to the Intranode Kernels In part 1, the intranode dispatch of the first release reached 183 GB/s on the B300 machine with 24 SMs, and the measurement suggested that it was limited by its SMs rather than by NVLink. Two changes in 2025 addressed exactly that. The first, in March 2025 (commit 1553fc4, "Improve EP2/4 performance"), gave every destination GPU several warps instead of one. The first release's dispatch kernel ran 8 warps per SM, one per destination; the new one ran 16 (512 threads), so that each destination got two warps and more memory requests were in flight at once. The TMA change below raised it again, to 24 warps. The second, in June 2025 (commit c8dceba, "Use TMA instead of LD/ST for intra-node normal kernels"), replaced the receivers' copy loops with the Tensor Memory Accelerator, and the commit message lists "Enable more warps" among its steps. TMA is a copy unit in every SM of Hopper and newer GPUs. One thread hands it a source, a destination and a size, and the unit moves the bytes on its own, without the data passing through the registers of 32 threads. A copy goes global memory to shared memory (a TMA load) and shared memory to global memory (a TMA store), and an mbarrier in shared memory tells the thread when the load has landed. Figure 7 shows the difference. ![A warp copy versus a TMA copy](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig07_tma.png) *Figure 7: Copying one 14 KB token with ordinary loads and stores (left), where every byte passes through the registers of a warp, and with TMA (right), where one thread issues a load into shared memory and a store out of it.* Here is the receiver's copy after the change. Each warp gets 8 KB of shared memory, so a BF16 token of 14 KB is moved in two halves: ```cpp // csrc/kernels/intranode.cu after c8dceba, dispatch receiver (cut down) for (int i = 0; i < 2; ++ i) if (lane_id == 0) { tma_store_wait(); // previous store left smem tma_load_1d(tma_buffer, shifted_buffer_x_int4 + i * half_hidden_int4, tma_mbarrier, half_hidden_bytes); mbarrier_arrive_and_expect_tx(tma_mbarrier, half_hidden_bytes); mbarrier_wait(tma_mbarrier, tma_phase); tma_store_1d(tma_buffer, shifted_recv_x_int4 + i * half_hidden_int4, half_hidden_bytes, false); } __syncwarp(); ``` Only lane 0 issues the TMA operations here, and the token no longer passes through anyone's registers. The other 31 lanes are still there, though. They belong to the same warp and wait at the `__syncwarp()`, so TMA doesn't hand any threads back to other kernels; what it saves is the register traffic and the instructions of the copy loop. The `tma_store_wait()` at the top of the loop is needed because both halves use the same shared-memory buffer, so the second load must not start before the first store has finished reading from it. The commit message also records a decision: "Do not use TMA for senders". The senders still copy with loads and stores into the other GPU's memory, and V1's intranode kernels use TMA only for copies whose destination is in the local GPU's memory. (We will see in part 3 that V2 uses TMA stores straight into the peer's memory.) In July, the same idea moved into the internode kernels (commits a2fa3b7 and 06f417d) and into the send phase of the low-latency combine (commit c874cb7). #### 5.2 What It Bought Figure 8 compares the first release with `v1.2.1` on the B300 machine, for 4,096 tokens per GPU and a range of SM counts. ![V1.0 and v1.2.1 on B300 by number of SMs](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig08_v1_versions_sms.png) *Figure 8: Bandwidth of the intranode dispatch (left) and combine (right) of DeepEP V1.0 and v1.2.1 on eight B300 GPUs, 4,096 tokens per GPU. The time is the sum of the kernel durations, without CPU time or gaps between kernels.* As we can see in Figure 8, dispatch improved across the SM sweep: with 24 SMs, a dispatch now takes 459 us instead of 873 us (349 GB/s instead of 183 GB/s), and with 64 SMs it reaches 496 GB/s instead of about 310 GB/s. That is about 1.9 times the first release's rate at 24 SMs and 1.6 times at 64. Combine, on the other hand, didn't move at all; it was already running 24 warps per SM in the first release, and on this machine it ends up at 407 GB/s with 24 SMs and 602 GB/s with 64, within a few percent of the first release. The last V1 commit from February 2026 is within 1% of `v1.2.1` on every point I measured, so for intranode traffic, V1 was essentially finished by the summer of 2025 (I can't say the same for the internode kernels, which I couldn't measure). ### 6. Getting Rid of the CPU Wait #### 6.1 The Worst Case Instead of the Exact Count The normal dispatch's CPU wait from part 1 had the consequence that the normal kernels couldn't be captured in a CUDA graph. In June 2025, commit a8299ca added a way around it for the intranode case, `num_worst_tokens`. If the caller passes it, DeepEP skips the CPU wait and allocates the output for the worst case instead: ```cpp // csrc/deep_ep.cpp after a8299ca, intranode_dispatch (cut down) if (num_worst_tokens > 0) { // No CPU sync, just allocate the worst case num_recv_tokens = num_worst_tokens; // Must be forward with top-k stuffs EP_HOST_ASSERT(topk_idx.has_value()); EP_HOST_ASSERT(topk_weights.has_value()); } else { // Synchronize total received tokens and tokens per expert // ... the spin loop from part 1 } ``` The worst case is that every token of every GPU comes to this GPU, so for 4,096 tokens per GPU on 8 GPUs, the output has 32,768 rows, of which about 21,600 are used with uniform routing. In exchange, the call has fixed sizes and can be in a graph. At the end of the kernel, the top-k indices of all unused rows are set to -1, so the GEMM that follows can tell the real tokens from the padding, and the per-expert counts are no longer returned to Python (the docstring says the list is then empty). That is the same trade as the masked layout from part 1, applied to the normal kernels. In November 2025, the internode dispatch got the same option (commit 92fe2de, PR #438). #### 6.2 Fewer Barriers The first release synchronized the GPUs of a machine with a FIFO of barrier slots in each GPU's buffer (the `task_fifo_ptrs` in part 1's code). In June 2025, commit 8da2d7b ("Fully remove barrier FIFO designs") replaced it with a simpler barrier on signal words. ### 7. Smaller Data Formats #### 7.1 UE8M0 Scales The FP8 tokens that DeepEP sends carry one fp32 scale per 128 channels, which is 224 bytes per token. Blackwell GPUs changed what the GEMM wants: DeepGEMM's SM100 kernels, which became public in July 2025, expect the scales in UE8M0, an 8-bit format that stores only an exponent, so that every scale is a power of two. Four of them are packed into one 32-bit integer. DeepEP added the matching scale option in June 2025 (commit 21efbe9, "Support UE8M0 data format"). With `round_scale=True`, the low-latency dispatch rounds each scale up to the next power of two, and with `use_ue8m0=True`, it sends only the exponent byte. We can see what that costs in accuracy: ```python torch.manual_seed(0) x = torch.randn(4, 7168) * torch.rand(4, 1) * 10 # 4 tokens blocks = x.view(4, -1, 128) amax = blocks.abs().amax(-1, keepdim=True).clamp(min=1e-4) exact_inv = amax / 448 # fp32 scale exp = torch.ceil(torch.log2(exact_inv)) # round up ue8m0_inv = torch.exp2(exp) # a power of two ue8m0 = (ue8m0_inv.view(torch.int32) >> 23).to(torch.uint8) # exponent byte def roundtrip(inv): q = (blocks / inv).to(torch.float8_e4m3fn) return q.float() * inv for name, inv in (("fp32 scales", exact_inv), ("UE8M0 scales", ue8m0_inv)): err = (roundtrip(inv) - blocks).norm() / blocks.norm() print(f"{name}: relative error {err:.4f}") byte = ue8m0[0, 0, 0].item() print(f"one scale is the byte {byte}, which means 2^{byte - 127}") # fp32 scales: relative error 0.0257 # UE8M0 scales: relative error 0.0264 # one scale is the byte 124, which means 2^-3 ``` Rounding the scale up means the largest value of a block no longer maps to 448 but to somewhere between 224 and 448, which costs a little precision (here, 2.64% relative error instead of 2.57%). The scale shrinks from 4 bytes to 1, and the exponent byte is literally bits 23 to 30 of the fp32 scale, which is what DeepEP's `extract_required_scale_format` does with one shift. Figure 9 shows the bits of the scale from the snippet. ![An fp32 scale and its UE8M0 byte](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig09_ue8m0.png) *Figure 9: The fp32 scale 2^-3 and the byte that UE8M0 keeps of it. A power of two has an all-zero mantissa, so the 8 exponent bits carry the whole value, and four such bytes fit into one 32-bit integer.* Since the mantissa of a power of two is zero, dropping the other three bytes loses nothing that rounding hadn't already removed. The byte 124 stands for 2 to the power 124 - 127 = -3, with the same bias of 127 that fp32 uses, so converting it back is a shift in the other direction. #### 7.2 LogFMT for the Combine The combine was the bigger target, since it sends BF16, twice the bytes of an FP8 dispatch, and it is the slower half of a low-latency round trip. In July and August 2025 (commits 1cf85fb and c5facf5), DeepEP added `use_logfmt=True` to the low-latency combine, which sends the expert outputs in a 10-bit logarithmic format that the docstring calls "LogFMT with dynamic per-64-channel cast". The idea is to spend the bits on the exponent rather than on the mantissa. For every group of values, the kernel computes the logarithms of the largest and smallest magnitudes, divides the range between them into 510 equal steps on the log scale, and sends each value as a sign bit and a 9-bit step index (index 0 means zero). If a group doesn't fit the scheme (its largest magnitude is 1 or more, or all its nonzero magnitudes are equal), the group is sent in BF16 instead. Figure 10 compares the resulting grid of values with FP8's. ![FP8 and LogFMT-10 grids](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/figures/fig10_logfmt.png) *Figure 10: The values that FP8 E4M3 (left) and LogFMT-10 (right) can represent within one octave. FP8 always has 8; LogFMT spreads 510 steps over the range of each group.* As we can see in Figure 10, FP8 has the same 8 values in every octave, while the density of LogFMT-10 depends on how wide a group's range is: a group that spans 10 octaves gets 51 values per octave, and even the widest range the kernel allows, 32 octaves, still gets about 16. Here is the encoding and decoding in PyTorch, following the kernel's arithmetic: ```python def logfmt10(x): # x: [..., 128], one group per 128 values a = x.abs() log_amax = torch.log2(a.amax(-1, keepdim=True)) log_amin = torch.log2(a.clamp(min=1e-30).amin(-1, keepdim=True)) log_amin = torch.maximum(log_amin, log_amax - 32) use = (log_amax < 0) & (log_amin < log_amax) # else: send BF16 step = (log_amax - log_amin) / 510 # 9 bits: codes 0..511 rounding = 2 - torch.log2((1 + torch.exp2(step)) / 2) / step code = torch.floor(torch.log2(a) / step + rounding - log_amin / step) code = code.clamp(min=0) # code 0 means zero value = torch.exp2((code - 1) * step + log_amin) * x.sign() decoded = torch.where(code == 0, torch.zeros_like(x), value) return torch.where(use, decoded, x), code torch.manual_seed(0) y = torch.randn(1024, 128) * 0.05 # expert outputs y_log, code = logfmt10(y) y_fp8 = (y / (y.abs().amax(-1, keepdim=True) / 448)).to(torch.float8_e4m3fn) y_fp8 = y_fp8.float() * (y.abs().amax(-1, keepdim=True) / 448) for name, z in (("BF16", y.bfloat16().float()), ("LogFMT-10", y_log), ("FP8 E4M3", y_fp8)): print(f"{name:>9}: relative error {(z - y).norm() / y.norm():.4f}") # BF16: relative error 0.0017 # LogFMT-10: relative error 0.0035 # FP8 E4M3: relative error 0.0257 ``` (I wrote the group as 128 values because the kernel's amax reduction runs over the lanes that together hold 128 BF16 values, `128 * sizeof(nv_bfloat16)` bytes; the docstring says 64.) The `rounding` term is the subtle part: it moves the rounding boundary between two steps from the midpoint in log space to the midpoint in linear space, so that a value is rounded to whichever neighbor is closer in absolute terms. As we can see from the output, in this synthetic sample, LogFMT-10's relative norm error is more than seven times smaller than FP8's and about twice BF16's, while sending 10/16 of BF16's bytes (plus two BF16 values per group for the range). The kernel packs 16 codes into five 32-bit words (`logfmt_encode` in `internode_ll.cu`), and the receiver decodes and accumulates in the same step, multiplying each decoded value by its router weight. ### 8. Running It in Production Some changes in 2025 were not about speed at all but about running DeepEP in a service: - **Statistics.** Since June 2025, the low-latency dispatch can add the number of tokens each local expert received into a cumulative tensor (`cumulative_local_expert_recv_stats`, commit 5a2e37f), which is what an expert-placement balancer needs to decide which experts to replicate. - **Slow ranks.** A diagnosis mode (commit 4b67064, "Add diagnosis module for efficient and precise location of slow rank") records how long each rank waits for each other rank, so that a straggler can be found, and the README links to AntGroup's DeepXTrace, an analyzer for this kind of data. - **Fault tolerance.** In September 2025, an Alibaba team contributed "elasticity support" (commit c475ec6): with `enable_shrink=True`, the low-latency buffer gets a mask, and `low_latency_update_mask_buffer(rank, True)` makes the surviving ranks stop sending to and waiting for a failed rank. The mask only keeps the communication from hanging, though. The experts that lived on the failed GPU are still gone, so the framework has to route their tokens to replicas on other GPUs, or the outputs will be wrong. - **Bias in combine.** The normal combine learned to add up to two extra tensors to its output (commit bd429ff), for example the shared expert's output, which saves a separate addition kernel. - **Zero-copy combine.** Already in March 2025 (commit dcaf73e), `get_next_low_latency_combine_buffer` lets the expert GEMM write its output directly into the RDMA send buffer of the next combine, which skips one copy. There were also many small extensions of what V1 accepts: more hidden sizes (2,048 up to 8,192), top-10 routing, expert-parallel groups of 24, 48, 96, 144 and 160 GPUs, Ampere GPUs for the intranode kernels (commit b8d90fb), and turning off NVSHMEM's multi-node NVLink (MNNVL) support by default, which also reduced NVSHMEM's memory use (commit df4debe). ### 9. What Others Built on Top By February 2026, the README listed five experimental branches and four community forks. Here are the ones that matter for where DeepEP went next: - **Zero-copy** (PR #453, Tencent) removes the copy between PyTorch tensors and the communication buffers in the normal kernels, "which reduces the SM usages significantly". - **Eager** (PR #437) replaces the RDMA atomic that signals arrival with a protocol that doesn't need the extra round trip of an atomic. - **Hybrid-EP** (a branch from NVIDIA, September 2025) is a new backend that uses TMA "for minimal SM usage", supports larger NVLink domains (its README has numbers for up to 36 GPUs in one GB200 NVLink domain), has a PCIe mode and NVFP4 support. Its README reports, on 8 B200 GPUs with 16 SMs, 410 GB/s for an FP8 dispatch compared with 246 GB/s for DeepEP V1. - **AntGroup-Opt** has three optimizations, one of which (Normal-SMFree, PR #347) is described as "eliminating SM from RDMA path by decoupling comm-kernel execution from NIC token transfer, freeing SMs for compute". - **Mori-EP** and **UCCL-EP** bring the same API to AMD GPUs and to other network cards. The README also gained a short section called "Easier potential overall design", which I think is the most interesting paragraph DeepSeek wrote about V1: "The current DeepEP implementation uses queues for communication buffers which save memory but introduce complexity and potential deadlocks. If you're implementing your own version based on DeepEP, consider using fixed-size buffers allocated to maximum capacity for simplicity and better performance." In other words, the authors themselves point at the ring buffers of the normal kernels, with their heads, tails, credits and timeouts, as the source of V1's complexity. That paragraph reads like a design note for V2, and in part 3, we will see that V2 is built exactly that way. ### 10. DeepGEMM in 2025 DeepGEMM, which turns DeepEP's output into expert computations, changed in the same year in ways that DeepEP had to follow: - In April 2025, its FP8 GEMM reached up to 1,550 TFLOPS on H800. - In May 2025, it added the weight-gradient GEMMs for training, including a version for MoE layers that is grouped over the K dimension (today called `k_grouped_fp8_gemm_tn_contiguous`), which is what the backward pass of a contiguous-layout MoE needs. - In July 2025, it was refactored to support both SM90 and SM100, with the packed UE8M0 scales from section 7.1 on SM100. - In September 2025, it added the scoring kernels for the "lightning indexer" of DeepSeek-V3.2, which are unrelated to MoE but show where DeepGEMM was going: from one GEMM kernel to a library of the kernels DeepSeek's models need. The UE8M0 change also shows up in DeepSeek's models. DeepSeek-V3.1, released on August 21, 2025 with the same architecture as V3, says in its [model card](https://huggingface.co/deepseek-ai/DeepSeek-V3.1/blob/c0781d039fb7a1ba2abc4add0bdc293e92d2b8db/README.md) that it was trained with the UE8M0 FP8 scale format for both weights and activations, and points to DeepGEMM. So by then, the format that DeepEP added in June and DeepGEMM's SM100 kernels used from July was also the format of the model itself. (The model card doesn't say anything about which GPUs DeepSeek ran it on, so I wouldn't read it as a hint about their hardware.) V3.2-Exp, the first model with the lightning indexer, followed on September 29, and the final V3.2 on December 1. One thing to keep in mind about all the accuracy numbers in this part: the snippets in section 7 measure how much error one cast adds to a random tensor. That tells us how the formats compare with each other, but not what they do to a trained model's outputs. Before switching a deployment to UE8M0 scales or a LogFMT combine, I would compare the outputs of a whole MoE layer, or better, the model's evaluation scores, against the BF16 path. Similarly, all B300 numbers in this part are sums of kernel durations with uniform random routing, taken inside one machine. Part 4 measures V2.5 with a different method (cold L2 cache, CUPTI timing), so its numbers are not one more point on the curves of Figure 8. ### 11. Summary To summarize, here is how the answers to part 1's four questions changed during the year of V1: 1. **What is sent.** The low-latency kernels now write directly over NVLink to every GPU whose memory NVSHMEM can map, and use RDMA only for the rest. Scales can be one byte instead of four, and the low-latency combine can send 10-bit values instead of BF16. 2. **How the receiver knows.** The normal kernels still use ring buffers with heads, tails and credits, but the heads sent back over the network are now RDMA atomic adds of differences, which adaptive routing can reorder without harm. The low-latency counts arrive as atomic adds that the receiver spins on, instead of writes with immediate data that it found by polling a completion queue, so the receive queue and the patched NVSHMEM are gone. 3. **The layout.** Unchanged in principle, but the normal dispatch can now produce a worst-case-sized output without the CPU, which makes it usable in a CUDA graph. 4. **The cost.** All RDMA is driven by GPU threads, more warps and TMA improved intranode dispatch across the measured SM budgets, and on the B300 machine, a dispatch of 4,096 tokens per GPU takes 459 us with 24 SMs instead of 873 us. The normal kernels still need many SMs to saturate a modern NVLink, though: 64 SMs reach about 500 GB/s for dispatch and 600 GB/s for combine. What didn't change is the basic structure: two kernel families with two APIs, ring buffers for the normal kernels, and buffers that grow with the number of experts for the low-latency ones. In part 3, we will see how V2 replaced all of it with one buffer, one dispatch function and NCCL instead of NVSHMEM, and how DeepGEMM's Mega MoE kernel took a different path at the same time. ### Sources - [DeepEP v1.2.1](https://github.com/deepseek-ai/DeepEP/tree/9af0e0d0e74f3577af1979c9b9e1ac2cad0104ee) and [the last V1 commit](https://github.com/deepseek-ai/DeepEP/tree/567632dd59810d77b3cc05553df953cc0f779799) - [DeepEP PR #130: multiple QPs and IBGDA for the internode normal kernels](https://github.com/deepseek-ai/DeepEP/pull/130) - [DeepEP PR #173: NVLink for the low-latency kernels](https://github.com/deepseek-ai/DeepEP/pull/173) - [DeepEP PR #191: TMA for the intranode normal kernels](https://github.com/deepseek-ai/DeepEP/pull/191) - [DeepEP Hybrid-EP branch](https://github.com/deepseek-ai/DeepEP/tree/hybrid-ep) - [DeepEP issue #39: fixed-size buffers](https://github.com/deepseek-ai/DeepEP/issues/39) - [DeepGEMM](https://github.com/deepseek-ai/DeepGEMM) - [V3.1 model card](https://huggingface.co/deepseek-ai/DeepSeek-V3.1/blob/c0781d039fb7a1ba2abc4add0bdc293e92d2b8db/README.md) - [V3.2-Exp announcement](https://api-docs.deepseek.com/news/news250929/) and [final V3.2 announcement](https://api-docs.deepseek.com/news/news251201/) - [NVIDIA: Enhancing Application Portability and Compatibility across New Platforms Using NVIDIA Magnum IO NVSHMEM 3.0 (CPU-assisted IBGDA)](https://developer.nvidia.com/blog/enhancing-application-portability-and-compatibility-across-new-platforms-using-nvidia-magnum-io-nvshmem-3-0/) ## 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* 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) ## DeepEP, Part 4: V2.5 and the Model Around It *What the September 2026 release changes in expert layouts, scheduling and memory, measured with CUDA 13.4, and how it fits alongside DeepSeek's models and DeepGEMM* At the end of part 3, DeepEP had a new transport. V2 gave every token a fixed slot on each destination GPU, talked to the network through NCCL's device API instead of NVSHMEM, and folded the two kernel families of V1 into one `ElasticBuffer` with one `dispatch` and one `combine`. V2.5, released on September 29, 2026, keeps all of that. The kernels that move a token from one GPU to another are recognizably the ones from part 3. What V2.5 changes is everything around those kernels. The EP interface becomes `EPBuffer`, and Engram lookups, pipeline transfers and collectives each get a buffer class of their own. A caller can now postpone the second half of a dispatch until it actually needs the result, reuse an expanded expert layout from an earlier call, and copy the weights of redundant experts between GPUs. And V1, together with its NVSHMEM dependency, is finally gone from the repository. So if the transport stayed the same, how much do the answers to our four questions change? Quite a bit, as it turns out, because two of the questions (which layout the experts get, and what it costs) depend as much on the interface as on the kernels. I will go through the release with the same four questions as before: what is sent, how the receiver knows that data has arrived, which layout reaches the experts, and what it costs in memory, SMs and CPU time. After that, we will place V2.5 next to the DeepSeek models and DeepGEMM releases of the same period, and finish with my measurements on the B300 machine. The source is DeepEP at `93eb6eb`, the README update right after the V2.5 release commit `def86514`, and DeepGEMM at `057ca59` from September 30. V2.5 needs a newer CUDA than the earlier parts used, so I measured it in a separate container with CUDA 13.4, on the same machine with eight B300 GPUs and still without RDMA network cards. As in part 3, everything I measured runs inside one NVLink domain, and the multi-machine parts of this article come from reading the source. ### 1. From One Buffer to Four #### 1.1 Why Split the Buffer In V2, one `ElasticBuffer` served four quite different kinds of transfer. Expert dispatch needs routing metadata and per-expert counts. An Engram lookup needs rows of a table at known addresses. A pipeline stage sends one activation tensor to its neighbor, and an all-gather needs every rank's shard of a result. Each of these has its own layout and its own notion of "done", and keeping them under one name made it hard to see which rules applied to which call. V2.5 gives them separate classes: `EPBuffer`, `EngramBuffer`, `PPBuffer` and `BucketBuffer`. They share the allocation and lifecycle code in a small base class, `BufferBase`, but each operation keeps its own layout and completion rules. For example, an EP handle records where every expert output has to go back to during combine, while an Engram fetch returns one hook per layer that waits for that layer's rows. Figure 1 follows each kind of data to the computation that consumes it. ![Four buffers and the computations that consume their data](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig01_buffers.png) *Figure 1: EP delivers routed activations, Engram delivers table rows, PP delivers a stage's activations, and Bucket delivers collective results. They share allocation and lifecycle code, while each operation keeps its own layout and completion rules.* #### 1.2 Planning Symmetric Memory Remember from part 3 that DeepEP's buffers are NCCL windows: symmetric memory, registered once, in which an offset means the same thing on every GPU. That works for DeepEP's own buffers, but V2.5 adds operations whose inputs live in the caller's tensors, such as the weights of a redundant expert or the shards of a collective. Those tensors have to be inside a registered window too, at the same offset on every rank. The new `BufferAllocator` solves this by planning first and allocating later. Each `allocate` call returns a placeholder tensor on PyTorch's `meta` device, which has a shape and a dtype but no storage, and records an aligned offset for it. When the buffer is constructed, it allocates and registers one block of memory and calls `materialize`, which swaps every placeholder for a view into that block with `torch.utils.swap_tensors`. So the caller's variables turn into views of registered memory without being reassigned: ```python # BufferAllocator usage, from the README at 93eb6eb # (excerpt, not a standalone program) plan = BufferAllocator() x = plan.allocate((group.size(), 1024), torch.float32) # a meta tensor buffer = BucketBuffer(group, plan) # allocates, registers, materializes x[group.rank()].fill_(group.rank()) # x is now a view into the window gathered_x = buffer.all_gather(x[group.rank()]).wait() ``` Since the offsets come from the order of the `allocate` calls, every rank has to make the same calls in the same order, which the README spells out as a requirement. Figure 2 shows the three steps. ![Planning symmetric memory with BufferAllocator](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig02_allocator.png) *Figure 2: `allocate` hands out meta tensors and records offsets, constructing the buffer allocates and registers one window per GPU with the same layout everywhere, and `materialize` turns the caller's tensors into views of that window.* The last step is the clever one. `torch.utils.swap_tensors` exchanges everything about two tensor objects, including their storage, so every reference to the placeholder `x`, in the caller's code or anywhere else, now sees the view into the window. The alternative, returning new tensors and asking the caller to rebind every name that pointed to the old ones, would be easy to get wrong. #### 1.3 New Build Requirements The requirements went up as well. V2.5 needs Hopper or newer, CUDA 13.1 or newer, NCCL 2.32.3 or newer, PyTorch 2.10 or newer, and a C++20 compiler whose standard library has `std::format`. The kernels are now compiled at run time by DeepJIT, a JIT module that DeepSeek split out into its own repository, which means the CUDA toolkit and the host compiler have to stay installed next to the wheel. This is also why the CUDA 13.0 environment from parts 1 to 3 couldn't run V2.5 at all. ### 2. The Topology Comes From Memory Access #### 2.1 NVLink Domains Instead of Machines In part 1, V1's normal kernels hard-coded the topology: 8 GPUs per machine, an 8-bit mask in `SourceMeta`, and RDMA always to the GPU with the same local index. V2 replaced this with NCCL's teams, and V2.5 makes the consequence explicit. Here is how it computes the sizes of the two levels: ```cpp // csrc/kernels/comm/context.cpp at 93eb6eb (one line broken in two) const int num_ranks = ncclTeamWorld(comm).nRanks, num_nvl_ranks = ncclTeamLsa(comm).nRanks; EP_HOST_ASSERT(num_ranks % num_nvl_ranks == 0); return {num_ranks / num_nvl_ranks, num_nvl_ranks}; ``` The first number is the number of NVLink domains, and the second the number of GPUs in one domain. Notice that neither of them counts GPUs per machine. The LSA team ("load/store accessible") from part 3 contains the GPUs that can reach each other's memory with ordinary loads and stores, and on a rack-scale system like GB200 NVL72, that is up to 72 GPUs spread over 18 machines. So an EP64 group could be eight domains of eight GPUs each, as on our B300 machines, or a single domain of 64 GPUs in one rack, and these are two quite different transport problems. Figure 3 shows the difference. ![Equal expert-parallel sizes with different NVLink domains](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig03_domains.png) *Figure 3: In one load/store accessible domain, every payload can be stored through an NVLink pointer. Across domains, the hybrid path sends once to each destination domain over RDMA and forwards over NVLink there. Machine boundaries alone don't choose the path.* #### 2.2 Direct and Hybrid On top of the physical domains, `EPBuffer` has two logical modes, which part 3 mentioned briefly. With `allow_hybrid_mode=True` (the default), the logical levels follow the physical domains: a token is sent once to each destination domain, to the GPU on the same rail, and forwarded over NVLink to the expert owners there. With `allow_hybrid_mode=False`, all ranks form one flat group, and every expert owner is a direct destination. Direct mode still works across domains, since the transport picks an NVLink pointer for each destination that has one and a GIN put for the rest. So "direct" describes where the token is sent, not how many machines there are. Which one is better depends on how many expert owners of a token share a remote domain. Let's take two experts of the same token. If they are on the same remote GPU, both modes send the token once, since dispatch deduplicates destination GPUs. If they are on two different GPUs of the same remote domain, direct mode sends two copies over RDMA, while hybrid mode sends one over RDMA and forwards it twice over NVLink on the far side. And if they are in two different domains, hybrid saves nothing and still pays for the forwarding step. Figure 4 shows the three cases. ![Direct and hybrid mode for two experts of one token](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig04_direct_hybrid.png) *Figure 4: The transfers that direct and hybrid mode make for a token with two experts on remote GPUs. Hybrid mode sends once to the GPU on the source's rail in each destination domain and forwards from there over NVLink.* Reading the figure row by row, hybrid mode never sends more over RDMA than direct mode, since a token can't reach more domains than GPUs, but it always pays for the NVLink forwarding. So it wins only in the middle row, and only when the network is the slower of the two links. Section 5 puts numbers on how often the middle row happens with uniform routing. The two modes also use the network differently. For direct mode, `get_theoretical_num_qps` uses at most 9 queue pairs, with a comment saying that fewer queue pairs mean less doorbell ringing. For hybrid mode, it gives every channel its own queue pair, 16 per SM plus one for the notify warps, since each channel is a warp that sends its own stream of tokens and tails, and part 3 explained why a signal must be sent through the same GIN context as the data it refers to. The README also changed its advice on adaptive routing. In part 2, we saw V1's README recommend it only for heavily loaded networks. V2.5's README now recommends turning it on "under all network load conditions", even though it adds some latency. My reading is that this follows from part 3: V2's progress signals across the network are atomic adds of differences, which give the same result in any order, and no credit is sent back. On the B300 machine, I set `EP_DISABLE_GIN=1`, which skips the RDMA initialization entirely, since there are no network cards to initialize. All eight GPUs are in one LSA team, so every destination is reached through a pointer anyway. ### 3. Arrival, Expansion and the Expert GEMM #### 3.1 One Received Token, Several Expert Rows The dispatch kernel itself works as in part 3. Notify warps count tokens per destination GPU and per local expert, dispatch warps load each token and its metadata into shared memory and store it into a fixed slot on every destination GPU, and a copy epilogue turns the slots into the output tensors. In hybrid mode, forward warps pass the tokens on inside the destination domain. To send the outputs back later, the handle keeps the source indices, the slots and the forwarding links. The output layout is where we need to be careful with counting. A token that selects three experts on GPU 5 arrives at GPU 5 once, but a grouped expert GEMM needs it three times, once in each expert's segment. Dispatch sends the single copy, and the copy epilogue makes the other two locally. So there are three different counts in play: the rows that were received, the expert rows that the GEMM computes, and the rows that are allocated. With `do_expand=False`, the output has one row per received token, together with its local expert indices and router weights, and the caller arranges the rows for its expert kernel itself. With `do_expand=True`, the epilogue builds the expert segments directly, each aligned to `expert_alignment` rows, and records in the handle where each token's copies went, so that combine can find them again. Let's take a small example. If three local experts receive 3, 0 and 5 tokens and the GEMM needs segments aligned to 4 rows, the segments take 4, 0 and 8 rows, which makes 8 useful rows out of 12. But neither number says how many tokens were sent over NVLink, since two of the 8 rows might be copies of the same received token. Figure 5 shows the three counts side by side. ![One received token, several expert rows and alignment padding](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig05_expand.png) *Figure 5: The received-token layout has one row per token and destination GPU. Expansion copies a token once per local expert, and alignment adds unused rows. The metadata links the expanded rows back to their source token.* #### 3.2 When the Counts Stay on the GPU As in V2, `do_cpu_sync=True` makes the CPU wait for the exact counts, so that the outputs can be allocated with exactly the right size, which is what prefill and training usually want. With `do_cpu_sync=False`, the outputs are allocated for the worst case, and the real counts stay on the GPU, in `handle.psum_num_recv_tokens_per_expert`. That is what a CUDA graph needs, but it also means that the next kernel must read the expert ranges from that tensor instead of treating every allocated row as a token. The worst case for the expanded layout is large. The source sizes it as every rank sending its maximum number of tokens, each with `min(top-k, local experts)` copies, plus room for the alignment of every expert. For the V3 shape on 8 GPUs with 4,096 tokens per rank, that is 8 x 4,096 x 8 = 262,144 rows, or 1.75 GiB for the FP8 values alone. With 128 tokens per rank, it is 8,192 rows and 56 MiB. So the no-sync mode is meant for decoding, where the maximum batch is small, and prefill keeps paying for the CPU wait in exchange for exactly sized outputs. Two kinds of empty rows are easy to mix up here. Alignment gaps sit between the segments of populated experts, and unused capacity is the large tail of a worst-case allocation. V2.5's new `do_zero_padding=True` fills the alignment gaps with zeros. A forward GEMM doesn't care what is in a padding row, since each output row depends only on its own input row, but a kernel that sums over the rows does, such as the weight-gradient GEMM in training, which would add whatever garbage a gap contains into the gradient. That is presumably why the README's example, which covers training as well as inference, turns it on. It doesn't touch the unused capacity, and the README says explicitly that zeroing does not make that capacity valid data. Figure 6 shows both in the worst-case allocation from above. ![Alignment gaps and unused capacity](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig06_empty_rows.png) *Figure 6: The expanded output of a dispatch with `do_cpu_sync=False`, sized for the worst case. Alignment gaps sit between the expert segments and are zeroed by `do_zero_padding=True`; the unused capacity after the last segment is never valid data.* With uniform routing, a GPU receives about 32,768 expert rows on average (8 GPUs x 4,096 tokens x 8 experts, spread over 8 GPUs), so about seven eighths of the worst-case allocation is unused capacity, and only the counts on the GPU tell the next kernel where it begins. The expanded tensor is also still the flat, contiguous layout, with all segments one after another. DeepGEMM's masked GEMM from part 1 wants a three-dimensional `[experts, max rows, hidden]` slab instead, so a framework that uses it has to copy the segments over, as SGLang does with its `expand_to_masked_slab` kernel (part 3, section 8). And a dispatch that can be captured in a graph doesn't make the whole MoE layer capturable: every kernel after it has to work with fixed allocations and device-side counts as well. Notice that these choices are independent of direct versus hybrid. Either mode can expand or not, and either can keep the counts on the GPU. In V1, the choice of kernel family decided both the transport and the layout; in V2.5, they are separate arguments. #### 3.3 Reusing a Layout A cached handle lets dispatch skip the work whose answer is already known: the counting, the slot assignment and the prefix sums. V2.0 already had this for the plain layout, and V2.5 extends it to the expanded one, which is what a training backward pass needs, since it sends gradients along exactly the routes of the forward pass. It is not a cache for consecutive decoding steps, though, because a new batch of tokens comes with new router choices and needs a new dispatch. The handle keeps a reference to `topk_idx`, and here V2.5 does something nice: it checks that nobody has changed that tensor in the meantime, using the version counter that PyTorch increments on every in-place write: ```python # deep_ep/buffers/ep.py at 93eb6eb, EPHandle # (cut down; excerpt, not a standalone program) self._topk_idx = topk_idx self._topk_idx_version = (None if topk_idx.is_inference() else topk_idx._version) @property def topk_idx(self) -> torch.Tensor: assert (self._topk_idx_version is None or self._topk_idx._version == self._topk_idx_version), \ '`topk_idx` must not be modified while the EP handle is in use' return self._topk_idx ``` (Some lines are wrapped.) Inference tensors have no version counter, so the check is skipped for them, and a CUDA graph that writes the next batch's routing into the same tensor with a kernel would not be caught either. So the rule from the docstring still holds: don't modify `topk_idx` until every use of the handle has finished. One more detail of the plain layout caught a bug in my own measurement harness. A row in the non-expanded output keeps all top-k router weights of its token, including the weights of experts that live on other GPUs, whose local indices are marked as -1. My first identity-expert reference summed all weights on every receiver, so it counted each weight once per destination GPU and made combine look wrong. The fix is to mask the weights wherever the local expert index is negative, which is what a real expert computation does anyway. ### 4. Waiting for an Epilogue #### 4.1 What the Deferred Epilogue Defers V2 could already run dispatch asynchronously and hand back an event. V2.5 adds `defer_epilogue=True`, which only works together with `async_with_compute_stream=True`. To see what it does, we need to look at what a dispatch call consists of on the C++ side. The second half of the call is written as a closure, so that it can either run right away or be handed to the caller: ```cpp // csrc/buffers/ep.hpp at 93eb6eb, EPBuffer::dispatch (cut down) launch_dispatch(..., num_sms, ..., comm_stream); // the protocol kernel auto epilogue = [=, this](const at::cuda::CUDAStream& stream, ...) { if (do_cpu_sync) { pybind11::gil_scoped_release release; // ... spin on the host-mapped counts, as in part 1 } else { // ... sizes for the worst case } auto recv_x = torch::empty({num_allocated_tokens, hidden}, ...); // ... allocate the other outputs launch_dispatch_copy_epilogue(..., jit->device.get_num_sms(), ..., stream); // all SMs return result; }; if (defer_epilogue) // hand the closure to Python, run it at the wait return pybind11::make_tuple(pybind11::none(), event, epilogue_hook); auto result = epilogue(comm_stream, ...); // run it now ``` So the epilogue contains three things: the CPU wait for the counts (if requested), the allocation of the outputs, and the copy-epilogue kernel, which runs on all of the GPU's SMs and not on the communication budget. Without deferral, all three happen inside the `dispatch` call, on the communication stream. With deferral, `dispatch` returns as soon as the protocol kernel is launched, and the closure runs when the caller waits on the event, on whatever stream is current at that moment. That helps in two ways. First, the CPU is free to enqueue other work before it blocks on the counts, which matters most with `do_cpu_sync=True`, where an immediate epilogue would stall the Python thread right after the launch. (The wait also releases Python's GIL, so that other threads, for example one that transfers KV cache, can keep running.) Second, the all-SM copy kernel no longer runs between the dispatch kernel and the independent work, where it would compete with that work for SMs. On the Python side, it looks like this: ```python # DeepEP V2.5 interface example; excerpt, not a standalone program. event = buffer.dispatch( x, topk_idx=topk_idx, topk_weights=topk_weights, num_experts=num_experts, do_expand=True, do_cpu_sync=False, async_with_compute_stream=True, defer_epilogue=True, ) # The framework can schedule independent work here. recv_x, recv_idx, recv_weights, handle = event.current_stream_wait() ``` `current_stream_wait()` makes the current stream wait for the communication event, then calls the registered hook, which runs the epilogue and returns the outputs. For combine, the same option defers the reduce epilogue that adds the partial sums and writes the final output, so attention or another micro-batch can run before it. The hook runs only once. `EventOverlap` sets `hook_after_wait` back to `None` after calling it, so a second wait returns `None` instead of running the epilogue again. A framework has to keep the result of the first wait. Figure 7 compares this with V1's receive hook from part 1. ![V1 network waiting and V2.5 deferred epilogues](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig07_deferred.png) *Figure 7: V1's receive hook leaves the RDMA transfer to the network card between two short kernels. V2.5's protocol kernel occupies its SMs until the data has arrived, and what moves to the consumer is the epilogue that produces the result.* #### 4.2 What Overlap Still Needs As we can see in Figure 7, the two hooks are not the same thing. V1's low-latency kernels could post their RDMA writes and leave, so the network card moved the data while the SMs did something else. V2.5's dispatch and combine kernels hold their SMs until the protocol has finished, and the README says plainly that "zero-SM RDMA EP is not supported". Deferring the epilogue moves the wait and the copy to the point where the result is consumed, but it can't create SMs for the overlapping work. If the communication kernel and the GEMM together need more SMs than the GPU has, or if the next kernel needs the received tokens right away, the deferral buys nothing. So whether a framework gains from it can only be measured as a whole schedule: two micro-batches with and without deferred epilogues, with the same GEMMs, the same routing and the same graph setup. My measurements in section 9 time the communication alone, so they say how long the operations take, but not how much of that time a schedule can hide. ### 5. An SM Budget From Routing #### 5.1 Counting Destinations Before Counting Bytes V2.5 keeps V2's idea of computing the number of SMs from a model of the traffic instead of a tuning table, so let's first recall how many destinations a token has. If the router picks k distinct experts uniformly from E experts, spread evenly over P ranks, then each rank owns E/P experts, and the chance that a token misses a given rank entirely is the number of ways to pick all k experts from the other ranks' experts, divided by the number of ways to pick them from all experts. One minus that, times P, is the expected number of destination ranks. Here it is with exact combinations, which is the same formula as V2's `get_expected_topk` from part 3: ```python from math import comb def expected_destinations(experts, topk, groups): assert experts % groups == 0 other = experts - experts // groups misses = comb(other, topk) / comb(experts, topk) return groups * (1 - misses) for ranks in (8, 32, 64): print(ranks, round(expected_destinations(256, 8, ranks), 3)) # 8: 5.295; 32: 7.267; 64: 7.676 ``` For EP64 as eight domains of eight GPUs, the same formula with 8 groups gives 5.295 destination domains, against 7.676 destination GPUs. So with uniform routing, hybrid mode cuts the copies that a token's GPU sends from about 7.7 (one per destination GPU) to about 5.3 (one per destination domain), before we subtract the local ones, and then forwards them to the individual GPUs inside each domain. That is a smaller saving than V1's one-group-per-machine example in part 1, where the group limit kept every token on at most 4 machines. Part of each count is local, too. A token that selects experts on its own GPU sends nothing over NVLink for them, so with symmetric routing, only a fraction (P - 1)/P of the destination ranks are remote, and the same goes for domains. If you forget this correction and divide all delivered bytes by the time, you can end up with a "bandwidth" higher than the link can carry. Figure 8 shows both counts as the group grows. ![Expected rank and domain destinations for uniform routing](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig08_destinations.png) *Figure 8: Expected destinations for V3's 256 experts and top-8 selection, with eight ranks per domain. The rank count approaches eight as the group grows, while the domain count grows more slowly. The calculation assumes even expert placement and uniform routing, not V3's group-limited router.* The source of `get_theoretical_num_sms` warns that its model doesn't apply to V3's group-limited routing, and redundant experts change the picture again, since they change which GPU owns which expert copy. As we saw at the end of part 1, EP320 can't be treated as 256 experts spread evenly over 320 GPUs. A real deployment has to run this kind of calculation with its own placement and its own router. #### 5.2 What the Budget Includes V2's estimate in part 3 only looked at dispatch. V2.5's version adds two terms for combine, uses slightly lower per-SM bandwidths (180 GB/s for reads and 45 GB/s for writes, both marked in the source as defaults to be replaced by per-architecture values), adds a 30% margin instead of 25%, and rounds up to a multiple of 4. For a single NVLink domain, the whole model fits in a few lines: ```python from math import comb, ceil def v25_num_sms(ranks, nvlink_gbs, experts=256, top_k=8, sm_read=180, sm_write=45): """V2.5's SM estimate for one NVLink domain (no RDMA).""" other = experts - experts // ranks k = ranks * (1 - comb(other, top_k) / comb(experts, top_k)) read, write = 1 / k, 1.0 # SM bytes per received byte nvl = 1 - 1 / ranks # NVLink bytes per received byte scale = nvlink_gbs / nvl need = max(scale * read / sm_read, # dispatch scale * write / sm_write, scale * (write - nvl) / sm_read, # combine scale * (read + nvl) / sm_write) n = max(4, ceil(need * 1.3)) return (n + 3) // 4 * 4 b300 = 18 * 53.125 * 0.9 # 18 links, 90% of their sum for ranks in (4, 8): print(f"EP{ranks}: {v25_num_sms(ranks, b300)} SMs") # EP4: 36 SMs # EP8: 32 SMs ``` These are exactly the automatic budgets that V2.5 chose on the B300 machine for EP4 and EP8. The `scale` is the rate at which received data arrives when NVLink is fully busy, and each term asks how many SMs it takes to read or write the corresponding bytes at that rate. In dispatch, an SM reads each token once (`1 / k` per received copy) and writes every copy. In combine, the roles swap: the expert side stores the partial sums back over NVLink and writes the final outputs, so the NVLink bytes now count as writes. On this machine, that last term is the largest one for both group sizes (23.3 SMs before the margin for EP8), which means the combine sets the budget. The real function also caps the result at the number of SMs on the device. Figure 9 shows all four terms for both group sizes. ![The four terms of the SM model](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig09_sm_terms.png) *Figure 9: The number of SMs that each term of V2.5's model needs to keep up with NVLink on the B300 machine, before the 30% margin. The combine's write term is the largest for both EP4 and EP8.* The two write terms are more than ten times as large as the read terms. One reason is that the model gives an SM only a quarter of the bandwidth for writes that it gives for reads (45 against 180 GB/s). The other is that every received byte has to be written, while a token is read only once for all of its copies. The combine's write term is a little larger than the dispatch's, because the model counts both the final outputs (`1 / k` per received byte) and the partial sums stored over NVLink (`nvl`) as writes, which adds up to 1.06 for EP8 against 1.0. The margin and the rounding then turn 26.2 and 23.3 SMs into 36 and 32. With `prefer_overlap_with_compute=False`, the function returns at least 64 SMs, since then there is no GEMM that needs the rest. Which setting is right can't be answered by timing the communication alone: an isolated dispatch may finish sooner with 64 SMs, while the layer as a whole may finish sooner with 32, because the expert GEMM running next to it keeps more SMs. The model also has some blind spots that are worth knowing about. It doesn't look at the current batch size or at launch latency, so it recommends the same 32 SMs for 16 and for 4,096 tokens per rank, and the source lists expansion and the multiple-reduction option as TODOs. For a decoding batch, where launch overhead dominates, I would measure a few budgets at the real batch size instead of trusting the formula. #### 5.3 Reduction Order and Determinism As in V2, combine can add up a token's expert outputs inside a domain before sending one partial sum back, which saves network traffic when several of its experts share a domain. `allow_multiple_reduction=True` allows this. Since the partial sums are stored in BF16 before they are sent, a token's output is rounded once per level, so changing the reduction tree can change the result slightly even when every transfer is correct. A numerical reference for testing has to round at the same points, which is separate from the error of the FP8 input or the FP4 weights. V2.5 also changed how `deterministic=True` works. In V2.0 (part 3), a prologue kernel assigned every token its slot from prefix sums in token order before the dispatch kernel ran. In V2.5, the dispatch runs with the usual `atomicAdd` slots, and afterwards `EPHandle.deterministic_sort` sorts the received rows by their source token's global index with a few PyTorch operations (`torch.sort` and a permutation), so the output order no longer depends on which warp won which atomic. In expanded mode, it sorts within each expert's segment and updates the handle's slot pointers to match. That makes the dispatch output reproducible for a given batch, but the GEMMs and reductions downstream can still depend on the batch shape, so it doesn't make a model's outputs batch-invariant by itself. ### 6. Redundant Experts Need More Than a Router Map An expert that receives twice as many tokens as its neighbors can hold up the whole layer, since every GPU waits for the slowest one. A common fix is to place a second copy of that expert on a less busy GPU and send some of its tokens there. The model still has the same logical experts, but the runtime now has more physical expert slots than experts, as we saw with V3's EP320 in part 1. The README credits two projects that explore this, Moonshot's MoonEP and UltraEP. V2.5 adds the data movement for those slots. `lb_prefetch_weights` copies expert weights from their owner GPUs into redundant slots on other GPUs before the expert computation runs, and `lb_reduce_grads` does the reverse in the backward pass. Both work only within one NVLink domain, and every rank of the domain has to call them, even a rank without redundant slots, since they start and end with a barrier. The plan is a `redundancy_mapping` tensor of shape `[GPUs in the domain, redundant slots per GPU]`, identical on every rank. Entry `[r, c]` names the expert that goes into slot c on GPU r, as `owner_rank * local_experts + local_index`, or -1 for an empty slot, and a GPU may not hold a replica of its own expert. The redundant slots have to live in a separate registered region (planned with a `BufferAllocator`), while the original weights can stay in ordinary CUDA tensors. The prefetch kernel moves each expert in chunks: a warp loads a chunk of the owner's weights into shared memory with TMA and stores it into the peer's redundant slot with a TMA store over NVLink. The API takes a list of tensors, so the packed FP8 or FP4 weights and their scale tensors can be copied in one call, and that matters, since a replica with new weights and old scales would compute garbage. Each pair of tensors needs the same number of bytes per expert, a multiple of 32. The gradient reduction is the more interesting kernel. Each redundant copy accumulates gradients from the tokens that were routed to it, and those have to be added into the owner's gradients before the optimizer step. The owner loads a chunk of a replica's gradients from the peer into shared memory and then writes it into its own gradient tensor with `tma_store_reduce_add_f32`, a TMA store that adds to the destination instead of overwriting it. The addition happens in the memory system, not in the SM's registers, and the API takes FP32 gradients only. The owner's own contribution must already be in its gradient tensor (or zeros, if it had none), since the reduction adds to it. Figure 10 puts the two kernels side by side. ![Prefetching weights and reducing gradients](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig10_redundant.png) *Figure 10: The two load-balancing kernels for one redundant copy. In the forward pass, the owner's warps push the weights through shared memory into the peer's slot. In the backward pass, the owner pulls the replica's gradients and adds them into its own tensor with a TMA reduce-add.* Notice that the owner does the work in both directions: it pushes the weights out, and it pulls the gradients in. So the additions happen in the owner's own memory, which is where the optimizer step reads the result. What these functions don't do is decide anything. They don't detect which expert is hot, choose a placement, rewrite the router's owner map, or decide when it is safe to switch. The framework has to pick a boundary between batches, copy a consistent version of the weights, switch the routing only after the copy has finished, and, in training, reduce the replica gradients before the optimizer touches the weights. It also has to decide whether a placement is worth it: copying an expert's weights costs something once, and it only pays off if the imbalance it removes lasts for enough later batches. My benchmark only covers dispatch and combine, so I can't say where that break-even point is. ### 7. The Model and Kernel Timeline Parts 2 and 3 already placed several DeepSeek models next to the library releases. In this section, I want to put all of them on one timeline, from V3 to V4.1, and say for each one what the connection to DeepEP and DeepGEMM actually is. Sometimes a paper names a kernel, sometimes a model card names a format, and sometimes the only connection is that two things happened in the same month, which tells us much less. #### 7.1 V3 and the Original Split The [DeepSeek-V3 report](https://arxiv.org/html/2412.19437v2) describes H800 machines with eight GPUs connected by NVLink and InfiniBand between machines. Training ran as EP64 across eight machines. Prefill ran as EP32 on four machines, with redundant experts to spread the heavy ones, and decode as EP320 on forty machines, with the shared expert treated as a routed expert that every token selects. These two deployments explain V1's two kernel families from part 1 quite directly: prefill has large batches that can afford a count exchange and benefit from NVLink forwarding, while decode needs small fixed allocations and low latency, and the two GEMM layouts follow from the same split. The 2025 updates of the model family kept this MoE shape. For example, the [R1-0528 configuration](https://huggingface.co/deepseek-ai/DeepSeek-R1-0528/blob/4236a6af538feda4548eca9ab308586007567f52/config.json) still has hidden size 7,168, 256 routed experts, top-8 selection and an expert intermediate size of 2,048. A new reasoning model on the same shape doesn't need a new communication library, and nothing in the configuration says which one DeepSeek used to serve it. #### 7.2 Blackwell Changes the Scale Format Before V2 The first DeepGEMM release supported only Hopper (SM90), with FP32 scale factors. On July 20, 2025, DeepGEMM added Blackwell (SM100) kernels, and its README now describes two formats at the dispatch/GEMM boundary: FP32 scales on SM90 and packed UE8M0 scales on SM100, four exponent-only bytes per 32-bit integer, both in a transposed, TMA-aligned layout. Part 2 showed that DeepEP added UE8M0 handling to V1 in June 2025, and that V3.1's model card in August named UE8M0 scales for weights and activations and pointed to DeepGEMM. So the scale format changed during V1, long before the V2 rewrite. This matters because moving FP8 values quickly is not enough if the scales that come with them need a transpose, a padding copy or a conversion before the tensor cores can use them. It also means that Blackwell support did not start with V2 in April 2026. V1 compiled and ran on Blackwell long before that, but, as part 1 showed, its register copies and ring buffers were designed for H800's much slower NVLink, so running on Blackwell and making good use of it are different things. A note on names: our B300 GPUs report compute capability 10.3. They are Blackwell GPUs, and DeepGEMM's SM100 kernels run on them, but "measured on SM100" would hide which GPU the numbers come from, so I always say B300. The numbers in this series don't transfer to H800, B200 or a rack-scale NVLink system. #### 7.3 V3.2 Adds an Attention Consumer On September 28, 2025, DeepGEMM added the scoring kernels for the lightning indexer, and [V3.2-Exp launched the next day](https://api-docs.deepseek.com/news/news250929/) with DeepSeek Sparse Attention, on top of V3.1-Terminus. The [final V3.2](https://api-docs.deepseek.com/news/news251201/) followed on December 1, and its [technical report](https://arxiv.org/html/2512.02556v1) explains how the indexer scores earlier token positions so that attention only has to look at the selected ones. The indexer and the MoE router both pick a top-k, but of different things: the indexer picks token positions and the router picks experts. So the index count in a V3.2 checkpoint is not the `num_topk` of an EP buffer, which stays at 8 for this shape. V3.2 gave DeepGEMM a new consumer of low-precision matrix products, but the expert-parallel library at the time was still V1. #### 7.4 V4 and the Fused MoE DeepGEMM's April 2026 update added FP8-by-FP4 GEMMs and Mega MoE (announced in the README on April 16, merged on April 17), V4 Preview launched on April 24, and DeepEP V2 followed on April 30. The [V4 report](https://arxiv.org/html/2606.19348v1) names Mega MoE, DeepGEMM PR 304, as its fused MoE implementation, and describes FP4 quantization-aware training for the expert weights and for the QK path of the indexer: FP32 master weights during training, with the FP4 quantization simulated in the forward pass, and native FP4 expert weights for inference and rollouts. That is a direct connection between the model and DeepGEMM. Between Mega MoE and V2, the only connection I can see is the timing, so I wouldn't say that one caused the other. The V4 configurations also show that one model family can have quite different communication shapes. [V4-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/config.json) has hidden size 4,096, 256 routed experts, top-6 selection and intermediate size 2,048, while [V4-Pro](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/b5968e9190ef611bbf34a7229255be88a0e937c1/config.json) has hidden size 7,168, 384 routed experts, top-6 selection and intermediate size 3,072. Both store their experts in FP4, with FP8 quantization settings and UE8M0 scales. FP4 weights don't make the communication cheaper, though, since what dispatch and combine send are activations, not weights. Let's compare the activation bytes with the arithmetic of one expert. Ignoring the nonlinearity, the three projections of an expert with hidden size H and intermediate size I cost about `6 * H * I` FLOPs per (token, expert) pair (2 FLOPs per multiply-add, three H-by-I matrices). An FP8 token on the way in and a BF16 output on the way back are `3 * H` bytes, before metadata and deduplication, so the ratio is about `2 * I` FLOPs per byte: ```python hidden, intermediate = 7168, 2048 # V3 expert shape expert_flops = 6 * hidden * intermediate activation_bytes = hidden + 2 * hidden print(expert_flops // activation_bytes) # 4096 FLOPs/byte # V4.1's intermediate size 2304 gives 4608 FLOPs/byte. ``` Notice that the hidden size cancels out, so only the expert's intermediate size matters, and it barely changed between V3 and V4.1. This is an idealized ratio per copy. A GPU that owns several of a token's experts receives one copy and returns one partial sum for all of them, which raises the ratio, while small expert batches leave the GEMM underutilized, which effectively lowers it. That is why the batch sizes and the expert placement belong in a benchmark description, next to the precision. #### 7.5 V4.1 Expands the Boundary Again V4.1-Flash launched on September 10, 2026, the same day as a DeepGEMM update with Mega Gate, Mega mHC, a sparse indexer and DeepJIT, and DeepEP V2.5 followed on September 29. The [V4.1 report](https://arxiv.org/html/2609.19969v1) names DeepGEMM's fused kernels in its inference system, and it also describes a causal encoder-decoder architecture, attention reuse across layers, and Engram tables whose addresses are known in advance, so that their rows can be prefetched from host memory over RDMA in the background. That is several kinds of communication in one model: routed expert activations need EP, table rows need a lookup from storage, and pipeline stages pass activations along. V2.5's separate buffer classes line up with those quite well. The report doesn't say which implementation runs in DeepSeek's deployment, though, so I read this as a match in structure, not as evidence that `EngramBuffer` is what serves V4.1. The [V4.1-Flash configuration](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/2cba9e42aa026125f3ed06c6d98c1db82f7ca027/config.json) gives us the second MoE shape for the measurements: hidden size 5,120, 384 routed experts, top-6 selection and intermediate size 2,304, with FP4 experts, FP8 quantization and UE8M0 scales. Each of those settings describes a different tensor. The KV cache in the report uses yet another 4-bit format, and none of these decide what format the activations have when they enter `EPBuffer.dispatch`. My benchmark uses BF16 inputs or FP8 inputs with FP32 scales per 128 channels at this shape. It doesn't convert to packed UE8M0, and it leaves out the router, the expert GEMMs, Engram and attention, so it measures the communication at V4.1's shape and nothing more. Figure 11 puts the model launches and the library releases on separate tracks. ![Model releases alongside DeepEP and DeepGEMM updates](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig11_timeline.png) *Figure 11: Blackwell scale and layout support arrives during V1, before V2's transport rewrite. V4 and V4.1 name DeepGEMM kernels in their reports, while DeepEP's release dates sit near the model launches without a stated connection.* As we can see in Figure 11, the scale format went through three steps in 2025: DeepEP's UE8M0 handling in June, DeepGEMM's SM100 kernels in July, and V3.1's model card in August. The V4 connection is a different kind, since the report names a specific fused kernel. And DeepEP's own releases have no stated connection to any model, which is why I keep the tracks apart. ### 8. What the Other Buffers Add The three other buffer classes get one section here, since my measurements don't cover them. `EngramBuffer` fetches rows of lookup tables that can live in GPU or CPU memory on other machines. `fetch(indices)` takes the row indices of several layers at once, as a `[layers, tokens, entries per token]` tensor, issues all the RDMA reads, and returns one hook per layer, so each layer waits only for its own rows. This works because an Engram row's address depends only on the token IDs, which are known before the first transformer layer runs. An expert activation can't be sent that early, since its destination depends on the router's output in the same layer. The README notes that Engram needs an NCCL build with `ncclGinOptFlagsWarpGet`, and since the reads go over RDMA, I couldn't run it on this machine. `PPBuffer` sends and receives activation tensors between neighboring pipeline stages, in a group that has to be RDMA-only. Its `send` and `recv` take their own `num_sms`, and if you leave it at `None`, they use all SMs. So configuring `EPBuffer` to leave SMs free says nothing about what a pipeline transfer will take. `BucketBuffer` offers batched all-gather, reduce-scatter and all-reduce, which V2.0 only had in part (part 3 found only the all-gather). The all-gather runs on the copy engines without SMs, while reduce-scatter and all-reduce need SMs for the additions and, inside an NVLink domain, NCCL's multimem support. A `session()` lets you pass ordinary tensors by staging them into the bucket's storage and copying the results back, and those copies cost time too. At this commit, the constructor also asserts that both an NVLink and an RDMA bandwidth can be detected, even for a group that only uses one of them, so I couldn't construct a `BucketBuffer` on this machine at all. ### 9. Measurements in the CUDA 13.4 Container #### 9.1 What Was Timed The container has CUDA toolkit 13.4.92, PyTorch 2.14.1+cu130 and NCCL 2.32.3. (The `+cu130` suffix describes how PyTorch was built; DeepJIT compiles the kernels with the 13.4 toolkit.) The installed `deep_ep` reports version 2.5.0, and the benchmark calls the upstream `EPBuffer` directly, from the source pinned at `93eb6eb`. I measured EP4 and EP8, always inside the one NVLink domain of the machine. EP4 covers 128 and 4,096 tokens per rank, and EP8 adds 16 and 512. Each runs the V3 and V4.1 shapes, with BF16 or FP8 dispatch and with expanded or plain outputs. The router picks distinct experts uniformly at random with equal weights, which gives the right dimensions with a controlled workload; a real router produces a different distribution. Before any timing, each configuration checks the received rows against the original inputs, using the source-token metadata and routing counts gathered independently. Then an identity expert applies the local router weights, and combine is checked against the input. For FP8, the reference is the quantized and dequantized input, so that the quantization error isn't blamed on combine. Across the 96 configurations of the EP4 and EP8 runs, dispatch matches its reference exactly, and the largest absolute difference after combine is 0.015625, within BF16 rounding. A fresh dispatch after the graph replays checks that the buffer can be reused. An identity expert keeps the round trip easy to check, but it can't catch a mix-up between two experts that get the same input. So a separate EP8 test uses non-uniform router weights and a different diagonal transform for every expert, and its sixteen configurations pass against the independent reference (`data/weighted.log` and `methodology.md` have the details). Another small two-GPU BF16 test exercises the new interfaces from sections 3 and 4: deferred dispatch and combine, the one-time hook, cached expanded dispatch, and zeroed alignment gaps, each in deterministic and non-deterministic mode. All checks pass (`data/contracts.log`). None of this tests RDMA, expert migration or gradients. For timing, I used FlashInfer's `bench_gpu_time_with_cupti`, with CUDA graphs and a cold L2 cache on every rank. After the utility's own warm-up, each operation gets five dry runs and then thirty measured runs for each of two routing seeds. The timer spans from the start of the first kernel to the end of the last one, so it includes the protocol kernel and its epilogue. For each run I take the slowest rank, compute the median per seed, and report the median of the two seed medians. The cold L2 cache matters, because the graph replays the same inputs over and over, and without flushing, the tokens would still be in L2 from the previous run. The first sample of a record is always much slower: in 272 of the 288 records it is more than ten times the median. I kept those samples in the data and in the medians. My guess is that the profiler's start-up and launch skew between the ranks cause it, since the harness doesn't synchronize the ranks again after CUPTI starts, but I didn't verify that. With only two seeds, the percentile bands in the charts describe these replays, not the tail latency of a server. Input generation, FP8 casting, the reference checks, JIT compilation and everything on the CPU happen outside the timed region. So these are GPU operation times, which are not the same as end-to-end serving latency, and also not the same as the summed kernel durations in parts 1 to 3, which leave out the gaps between kernels and used a different software stack and no cache flushing. I kept the older numbers in their parts, but I don't compute speedups across the two methods. #### 9.2 Payload Size and Expansion At EP8 with 4,096 tokens per rank and the automatic 32 SMs, the V3 shape takes 526.4 us for a plain BF16 dispatch and 280.1 us for FP8. Combine sends BF16 in both cases and takes about 499 to 500 us. So FP8 almost halves the dispatch, but since the combine format doesn't change, the round trip only gets about a quarter faster, from about 1,026 to 779 us. The V4.1 shape has a smaller hidden size (5,120 instead of 7,168) and selects 6 experts instead of 8, so it moves less data per token. With the same setup, its FP8 dispatch takes 172.3 us and its combine 308.9 us. That says nothing about which model is faster overall, since the two differ in their layers, attention, memory lookups and compute. Expansion adds local copies after the data has arrived, and on the way back, combine has to find and add up each token's expert rows. For the large V3 FP8 case, the expanded dispatch takes 301.4 us and combine 540.6 us, and for V4.1, 185.9 and 322.8 us. Figure 12 shows all batch sizes, including the small ones, where fixed overheads dominate. ![Operation latency across batch sizes and output layouts](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig12_latencies.png) *Figure 12: EP8 at the automatic 32-SM budget, FP8 dispatch with FP32 scales per 128 channels and BF16 combine, expert alignment 1. Lines are the median of two per-seed medians, and the shaded bands span the per-seed 10th to 90th percentiles. Each point uses thirty cold-L2 CUDA-graph samples per seed, timed with CUPTI on the slowest rank. Commands and raw samples are in `data/commands.txt`, `ep8.jsonl` and `methodology.md`.* As shown in Figure 12, the small batches behave differently. At 16 tokens per rank, V3's FP8 dispatch takes about 27.6 us, against 23.7 us for BF16, so sending half the bytes made it slower. I suspect the extra work for the scales costs more than the bytes it saves at that size, but I didn't isolate the cause, and two seeds are not enough for a confidence interval. Either way, it is a good reason to measure the real decoding batch instead of extrapolating the large-batch ratio. EP4 is a different workload, even at the same number of tokens per rank. Each GPU holds twice as many experts, so more of a token's experts share a destination, and the whole group has half as many tokens. At 4,096 tokens per rank, V3's plain FP8 dispatch takes 176.2 us and combine 309.9 us, and V4.1 takes 120.1 and 209.3 us. The automatic budget is also 36 SMs here instead of 32, so comparing EP4 with EP8 mixes the group size, the payload and the deduplication, and doesn't tell us how well the library scales. The raw records also contain a payload rate: the average number of distinct rows received per rank, times the bytes per row, divided by the slowest rank's time. For an FP8 dispatch of the V3 shape, a row is 7,168 bytes of values plus 224 bytes of scales, and for the BF16 combine it is 14,336 bytes. This rate counts the rows that a GPU sends to itself and leaves out metadata, signals, padding and the epilogue's copies, so it is a measure of useful payload per second, not of NVLink bandwidth. The registered EP buffer at 4,096 tokens per rank takes 450 MiB per rank for the FP8 V3 case and 242 MiB for FP8 V4.1 (452 and 324 MiB with BF16 dispatch). The reported `buffer.num_bytes` leaves out the separate GPU and host workspaces, the output tensors (which, as section 3.2 showed, can be much larger in the no-sync expanded mode), the cached JIT kernels, and of course the model's weights and KV cache. #### 9.3 How Many SMs to Give Communication For the SM sweep, I used FP8 dispatch and BF16 combine with budgets of 8, 24 and 64 SMs, at 128 and 4,096 tokens per rank. For the large V3 case with plain outputs, dispatch goes from 409.0 us with 8 SMs to 312.2 us with 24 and 283.2 us with 64, and combine from 851.4 us to 540.0 and 495.7 us. The automatic 32 SMs give 280.1 and 498.6 us, which is as fast as 64 SMs. The few microseconds between the two come from separate runs, so I wouldn't call either one faster. ![Operation time as the communication SM budget changes](https://sleepy-capybara.vercel.app/deepep/4-v2-5/figures/fig13_sms.png) *Figure 13: EP8, 4,096 tokens per rank, plain outputs. Each point is the median of two per-seed medians of thirty cold-L2 CUDA-graph samples, timed with CUPTI on the slowest rank. `data/commands.txt` has the full invocation and `sms.jsonl` every sample.* As shown in Figure 13, the V4.1 shape behaves the same way: its large dispatch goes from 251.5 us with 8 SMs to 190.0 and 174.0 us with 24 and 64, and its combine from 523.8 to 335.0 and 303.6 us. At 128 tokens, though, dispatch takes 27.4 us with 24 SMs and 29.4 us with 64, so more SMs didn't help at all. That fits the model's blind spot from section 5.2: at small batches, the time goes into fixed costs that more SMs can't shorten. No GEMM runs next to these operations, so the sweep only shows what the communication costs by itself. An expert kernel next to a 64-SM dispatch has 32 fewer SMs than one next to a 32-SM dispatch, and only a measurement of the whole layer, with two micro-batches or a pipeline schedule, can say which budget makes the layer faster. ### 10. Using V2.5 in a Serving Framework To close, here is what I would check when moving a framework to V2.5, in the order I would check it. First, the interface. V2's `ElasticBuffer` and V2.5's `EPBuffer` are different classes, and with deferred epilogues, `dispatch` returns either a tuple or an `EventOverlap`, depending on an argument. A framework written for V2 needs an adapter that understands the new handles, outputs and completion rules, and having a V2.5 wheel installed doesn't mean that adapter exists. That is also why my benchmark calls `deep_ep.EPBuffer` directly: the container has a development `sgl-deep-ep` wrapper for SGLang, but nothing in this article tests SGLang's integration, its correctness or its throughput. Second, the topology and the owner map. How many GPUs share one LSA domain, which remote GPUs are reachable over a rail, and how many destination GPUs and domains does the real router produce per token, with the replicas included? Only with those numbers can we decide between direct and hybrid mode, and estimate whether deduplication saves enough RDMA traffic to be worth the forwarding. Third, the layout through the whole layer. Keep the received rows, the expanded rows and the allocated capacity apart, check the GEMM's alignment and scale format, and find every transpose, padding copy or FP8 cast between dispatch and the tensor cores. Those can be fused into other kernels, but they don't disappear when we compare buffer interfaces. Finally, place each wait where its data is first used, and measure what overlaps with it. A deferred epilogue only helps if there is independent work to run before the result is needed, and enough SMs for that work. For a small decoding batch, launch and synchronization costs matter more than the bytes, while for a large prefill batch, the buffer sizes and the SM budget are what show up in the total. ### 11. Summary To summarize, V2.5 keeps V2's transport and changes how the caller controls it: 1. **What is sent.** As in V2, each token is sent once per destination GPU, or in hybrid mode once per destination domain and then forwarded over NVLink. The activation format (BF16 or FP8 with FP32 or UE8M0 scales) is independent of how the expert weights or the KV cache are stored. 2. **How the receiver knows.** NCCL's teams decide which destinations get an NVLink store and which a GIN put, so the topology comes from memory access instead of a fixed machine size. A deferred event lets the caller place the count wait and the epilogue at the point where the result is used. 3. **The layout.** The caller chooses between one row per received token and aligned expert segments, and between counts on the CPU and counts on the GPU, independently of the transport mode. Expanded layouts can now be cached for the backward pass, and alignment gaps can be zeroed. 4. **The cost.** The SM model now covers combine as well and picks 32 SMs for EP8 on B300, which is as fast as 64 in isolation. The protocol kernels still occupy their SMs, the worst-case outputs of the no-sync mode can be large, and the copy epilogue runs on all SMs wherever it is placed. Around these four answers, V2.5 adds what a deployment of a model like V4.1 needs besides expert parallelism: weight and gradient transfers for redundant experts, table lookups for Engram, pipeline transfers and collectives, each with its own buffer. Which of them pay off depends on the placement, the routing and the workload of a real deployment, which my measurements here don't cover. The [measurement bundle](https://sleepy-capybara.vercel.app/deepep/4-v2-5/artifacts.zip) contains the harnesses, raw samples, commands, verification logs and review notes. ### Sources - [DeepEP source at 93eb6eb](https://github.com/deepseek-ai/DeepEP/tree/93eb6eb238127e96c6d7a4a625a6dad158348509) - [DeepGEMM source at 057ca59](https://github.com/deepseek-ai/DeepGEMM/tree/057ca5964aae0879ff2e0eb71ee05a3cb0ba3df7) - [DeepSeek-V3 technical report](https://arxiv.org/html/2412.19437v2) - [DeepSeek-V3.1 model card](https://huggingface.co/deepseek-ai/DeepSeek-V3.1/blob/c0781d039fb7a1ba2abc4add0bdc293e92d2b8db/README.md) - [V3.2-Exp announcement](https://api-docs.deepseek.com/news/news250929/) and [final V3.2 announcement](https://api-docs.deepseek.com/news/news251201/) - [DeepSeek-V3.2 technical report](https://arxiv.org/html/2512.02556v1) - [DeepSeek-V4 technical report](https://arxiv.org/html/2606.19348v1) - [DeepSeek-V4.1-Flash technical report](https://arxiv.org/html/2609.19969v1) - [DeepSeek-V4.1-Flash checkpoint configuration](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/2cba9e42aa026125f3ed06c6d98c1db82f7ca027/config.json) - [V4 launch announcement](https://deepseek.com/en/news/v4-preview/) and [V4.1 launch announcement](https://deepseek.com/en/news/deepseek-v4-1-flash/)