File size: 1,544 Bytes
42832bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference implementation — the CORRECTNESS SPEC for `node_dispatch_pack`.

This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
bearing on your score, which is an absolute GB/s number. GENERATED by _factory/build.py.
"""
import torch


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