File size: 13,960 Bytes
4161512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""Spec for `deepseek-node-dispatch-pack` — the node-limited expert-parallel dispatch: deduplicate each
token's experts down to the set of NODES that hold them and pack the all-to-all send buffer."""
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec

SPEC = TaskSpec(
    name="deepseek-node-dispatch-pack",
    title="Write a fast node-limited MoE dispatch (dedup + all-to-all send-buffer pack) kernel",
    blurb=("DeepSeek-V3's node-limited routing exists so that a token's experts live on at most a handful "
           "of nodes — and the payoff is collected right here, in the kernel that builds the all-to-all "
           "send buffer. A token routed to four experts on the same node is sent to that node ONCE, not "
           "four times, so the dispatch has to deduplicate every token's expert set down to a node set, "
           "rank the tokens per node, and gather the hidden states into node-major order. It is the "
           "largest tensor in the layer moved once, with an index computation that is anything but a "
           "memcpy."),
    keywords=["mle", "kernel-generation", "moe", "expert-parallel", "dispatch", "all-to-all", "deepseek",
              "node-limited", "gather", "memory-bound"],
    module="dispatch_pack.py",
    func="node_dispatch_pack",
    signature="node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node)",
    returns_doc="""Node-limited MoE dispatch: dedup to node sets and pack the all-to-all send buffer.

Args:
    x:                (T, H) bfloat16 — token hidden states.
    topk_ids:         (T, K) int32    — the K expert ids chosen for each token (distinct within a row).
    num_nodes:        int             — N, the number of expert-parallel nodes.
    experts_per_node: int             — EPN; expert e lives on node e // EPN.

Returns:
    (send_buf, src_token, node_counts, node_offsets) where
      send_buf:     (T*M, H) bfloat16 — hidden states in NODE-MAJOR order, tokens ascending inside a node
      src_token:    (T*M,)   int32    — the token each packed row came from
      node_counts:  (N,)     int32    — rows destined for each node
      node_offsets: (N+1,)   int32    — node n owns rows [node_offsets[n], node_offsets[n+1])
    M is the (fixed) number of distinct nodes every token's experts span, so T*M rows are always
    produced.""",

    reference_imports="import torch",
    reference_src='''
def node_dispatch_pack(x, topk_ids, num_nodes, experts_per_node):
    """Deduplicate each token's experts to a node set, then gather node-major.

    Correct and simple — it is the exact SPECIFICATION, not a performance target. It materialises a dense
    (T, N) boolean membership matrix and lets `nonzero` do the ordering and the ranking, which is exactly
    the multi-pass shape a real kernel replaces with one privatised histogram and one gather.
    """
    T, K = topk_ids.shape
    node = topk_ids.to(torch.int64) // experts_per_node             # (T, K) node of every routed slot
    member = torch.zeros(T, num_nodes, dtype=torch.bool, device=x.device)
    member.scatter_(1, node, True)                                  # DEDUP: token -> set of nodes

    pairs = member.t().nonzero()                    # (R, 2) = [node, token], node-major, token-ascending
    src = pairs[:, 1]
    send_buf = x[src]                                               # the gather

    counts = member.sum(0).to(torch.int32)                          # rows per node
    offsets = torch.cat([torch.zeros(1, dtype=torch.int32, device=x.device),
                         torch.cumsum(counts, 0).to(torch.int32)])
    return send_buf, src.to(torch.int32), counts, offsets
''',
    make_inputs_src='''
def _mk(T, H, K, N, M, EPN, seed):
    """Hidden states plus a NODE-LIMITED routing table: every token's K experts are distinct and span
    EXACTLY M distinct nodes, which is what the node-limited router guarantees and what makes the packed
    length T*M a function of the shape alone.

    Slot j of a token goes to the (j % M)-th of its M chosen nodes, and takes the (j // M)-th entry of a
    random permutation of that node's experts — so the K experts are always distinct.
    """
    gen = torch.Generator(device="cuda").manual_seed(seed)
    x = torch.randn(T, H, device="cuda", dtype=torch.bfloat16, generator=gen)

    nodes = torch.rand(T, N, device="cuda", generator=gen).argsort(dim=-1)[:, :M]      # (T, M) distinct
    perm = torch.rand(T, M, EPN, device="cuda", generator=gen).argsort(dim=-1)         # (T, M, EPN)
    j = torch.arange(K, device="cuda")
    m, r = j % M, j // M
    sel_node = nodes[:, m]                                                             # (T, K)
    sel_off = perm[:, m, r]                                                            # (T, K)
    topk_ids = (sel_node * EPN + sel_off).to(torch.int32)
    del nodes, perm, sel_node, sel_off
    return x, topk_ids.contiguous(), N, EPN
''',
    flops_src='''
def canonical_work(T, H, K, N, M, EPN):
    """BYTES attributed to one dispatch pack, from the SHAPE ALONE.

    The unavoidable traffic: read the (T, H) bf16 hidden states once, read the (T, K) int32 routing table,
    write the (T*M, H) bf16 send buffer and the (T*M,) int32 source map. The membership bitset, the
    per-node counters and the prefix sum are tiny and never need to reach HBM. Node-limited routing fixes
    the number of copies at exactly M per token, so this is a function of the shape alone. This is a
    memory-bound kernel, so the score is achieved bandwidth against this fixed byte count.
    """
    return 2 * T * H + 4 * T * K + 2 * T * M * H + 4 * T * M + 4 * (2 * N + 1)
''',
    flops_formula=("bytes = 2*T*H  +  4*T*K  +  2*T*M*H  +  4*T*M  +  4*(2*N+1)\n"
                   "#       read x   read ids  write buf   src map   counts+offsets"),

    metric="GB/s",
    compare="tuple",
    tuple_names=("send_buf", "src_token", "node_counts", "node_offsets"),
    tol=1e-5,   # MEASURED: the payload is a pure gather, so an independent implementation differs by 0.0
    shape_names=("T", "H", "K", "N", "M", "EPN"),
    grader_shapes=[(32768, 7168, 8, 8, 4, 32), (24576, 7168, 8, 8, 4, 32),
                   (49152, 4096, 8, 8, 4, 32), (32768, 7168, 6, 8, 3, 32),
                   (32768, 5120, 8, 4, 3, 64)],
    measure_shapes=[(28672, 7168, 8, 8, 4, 32), (20480, 7168, 8, 8, 4, 32),
                    (40960, 4096, 8, 8, 4, 32), (28672, 7168, 6, 8, 3, 32),
                    (28672, 5120, 8, 4, 3, 64)],
    measure_quick_shapes=[(4096, 2048, 8, 8, 4, 32), (8192, 1024, 6, 4, 3, 16),
                          (2048, 4096, 8, 8, 2, 32)],
    correct_shapes=[(256, 512, 8, 4, 2, 16), (129, 256, 6, 4, 3, 8), (512, 1024, 8, 8, 4, 16),
                    (64, 128, 4, 4, 2, 8)],

    spec_md="""In expert-parallel serving the experts are spread over `N` nodes — expert `e` lives on node
`e // EPN` — and before the all-to-all can run, every token's hidden state has to be copied into the send
buffer of each node that owns one of its experts.

**The dedup is the point.** A token routed to four experts that happen to live on the same node is sent to
that node **once**. So the first step is to turn each token's `K` expert ids into a *set* of nodes:

```
node[t, j]  = topk_ids[t, j] // EPN
member[t,n] = True iff any j has node[t, j] == n
```

DeepSeek's node-limited routing guarantees each token's experts span exactly `M` distinct nodes, so
`member` has exactly `M` true entries per row and the packed buffer is exactly `T*M` rows long.

**The packing is node-major, token-ascending inside a node:**

```
node_counts[n]  = number of tokens with member[t, n]
node_offsets    = [0, cumsum(node_counts)]                 # (N+1,)
```

Node `n` owns rows `[node_offsets[n], node_offsets[n+1])` of `send_buf`, and those rows hold its tokens in
**increasing token index**. Formally, if `r` is the rank of token `t` among the tokens that chose node `n`
(counting in increasing `t`):

```
send_buf[node_offsets[n] + r, :] = x[t, :]
src_token[node_offsets[n] + r]   = t
```

`src_token` is what the combine step later uses to scatter the expert outputs back, so it is part of the
contract, not a debugging aid.

Note what is **not** asked for: no per-expert grouping, no weights, no padding. This is the transport
layer — one copy of each token per destination node, in the order the receiver expects.

`/app/reference.py` builds a dense `(T, N)` boolean matrix and lets `nonzero` produce the ordering. That is
the exact specification; it is deliberately simple rather than fast.""",

    contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `x` | `(T, H)` | `bfloat16` | token hidden states |
| `topk_ids` | `(T, K)` | `int32` | the `K` expert ids per token, **distinct within a row** |
| `num_nodes` | int | | `N` |
| `experts_per_node` | int | | `EPN`; expert `e` is on node `e // EPN` |

**Return a 4-tuple in exactly this order:**

| out | shape | dtype | notes |
|-----|-------|-------|-------|
| `send_buf` | `(T*M, H)` | `bfloat16` | node-major, token-ascending inside each node |
| `src_token` | `(T*M,)` | `int32` | source token of each packed row; compared **exactly** |
| `node_counts` | `(N,)` | `int32` | compared **exactly** |
| `node_offsets` | `(N+1,)` | `int32` | exclusive prefix sum, `node_offsets[N] == T*M`; compared **exactly** |

`M` — the number of distinct nodes each token's experts span — is **fixed for a given call** and is what
makes `T*M` a shape-only quantity; you can compute it, but you do not need to guess it, because
`send_buf`'s length follows from the routing table you are given.

All inputs are **read-only**; the copy is functional. `T` is **not** guaranteed to be a multiple of any
tile size — the correctness shapes include `T = 129`.""",

    regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `T`
(tokens in the micro-batch) in 24576–49152, `H` in 4096–7168, `K` in 6–8, `N` (nodes) 4 or 8, `M`
(distinct nodes per token) 3 or 4, `EPN` in 32–64. The send buffer is 3–4x the size of the input, so this
call moves more bytes than any other single op in the MoE layer.""",

    correctness_md="""Three of the four outputs are **integer** and are compared **bit-exactly** — one
wrong row index anywhere and the score is 0. `send_buf` is a pure gather, so a correct kernel reproduces it
**bit for bit**; its `1e-5` gate exists only to reject a change of dtype.

The ordering rules are an exact specification, not a convention: **node-major** blocks, **ascending token
index** inside each block. Two variants that break them were tried and both fail outright — packing
token-major (all of token 0's copies, then token 1's) and leaving the tokens unsorted inside a node. So
does skipping the dedup and emitting one row per expert slot, which produces `T*K` rows instead of `T*M`
and fails on shape.""",

    perf_md="""One read of `x`, `M` writes of each row, and an index computation in between. The floor is
`(1 + M)` passes over a `(T, H)`-sized tensor and nothing else, which is what the byte count assumes.

The index side is small but it is where the naive version dies. The reference's `(T, N)` boolean matrix,
`nonzero`, and the implied sort cost several passes over `T*N` and a device-wide scan. What it actually is:

* a **bitset per token** — `N <= 8` nodes fit in one byte, so the dedup is `mask |= 1 << (e // EPN)` over
  `K` ids, entirely in registers;
* a **histogram** of `N` counters, which wants per-block privatised counters and one atomic per block per
  node, not one atomic per token;
* a **prefix sum over `N <= 8` numbers**, which is one warp;
* a **rank within node**, which is the block's own offset plus a lane prefix — again no global sort.

Then the gather. Each destination row is a full `H`-wide bf16 copy (8–14 KB), so use vectorised 128-bit
accesses and give each row enough lanes to saturate; the read of `x[t]` serves all `M` of its destinations,
so a block that has a token's row in registers or shared memory should write **all** its copies before
moving on — reading `x` once instead of `M` times is a 25–33% bandwidth saving on its own.

The destinations of one token are `M` widely separated offsets, so the writes are scattered at row
granularity but perfectly coalesced within a row. Prefer a grid over (token tile) with the row resident,
rather than a grid over output rows that re-reads the source.""",

    precision_md="""`x` and `send_buf` are **bfloat16** and the copy is exact — no arithmetic happens to
the payload at all, so a correct kernel is bit-identical to the reference and the `1e-5` gate is
effectively an exactness check. Returning `send_buf` in fp32 would change the contract (and cost twice the
bandwidth for no benefit); returning it in fp8 would be a lossy transform of data that is supposed to be
transported unchanged.

The three integer outputs are compared **exactly**: `.float()` is lossy above 2^24 and `T*M` reaches
200000 here, so the grader never converts them.

**Where the tolerance comes from.** It is measured, and the measurement is that there is nothing to
measure: an independent implementation — the membership computed as a per-token bitmask, the ranking from
a scatter-add histogram plus a segmented rank instead of `nonzero`, and the gather written as an explicit
row copy — differs from this reference by a relative Frobenius error of exactly **0.0e+00** on `send_buf`
and reproduces all three integer outputs **bit for bit**, at every correctness shape and at a full-size
graded shape, over several seeds. The gate is set at `1e-5` rather than at zero only so that a legitimate
bf16 round-trip cannot fail on a denormal; it admits nothing except the specified bf16 payload, and in
particular an fp8 or fp16 payload would miss it by 1e-3 or more.""",
).validate()