ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 9)
42832bf verified
Raw History Blame Contribute Delete
1.54 kB
"""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