Download tasks/moe/deepseek-node-dispatch-pack/environment/reference.py from ZMC2019/KBench: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/moe/deepseek-node-dispatch-pack/environment/reference.py
- Command line
-
hf download hf://datasets/ZMC2019/KBench/tasks/moe/deepseek-node-dispatch-pack/environment/reference.py
-
curl -L -o reference.py https://huggingface.co/datasets/ZMC2019/KBench/resolve/main/tasks/moe/deepseek-node-dispatch-pack/environment/reference.py
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 | |