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

October 10, 2026 · Markdown · Whole series as Markdown

Series: Part 1 · Part 2 · Part 3 · Part 4

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:

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.

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
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
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:

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:

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:

// 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<int>(*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
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
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):

// 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 int4s) 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
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
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:

// 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
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:

// csrc/kernels/internode.cu at ebfe47e, forwarder coordinator (cut down;
// std::numeric_limits<int>::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<kLowLatencyMode>(
                             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
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
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:

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):

// 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
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
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
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:

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
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