"""Reference implementation — the CORRECTNESS SPEC for `moe_a2a_dispatch`. 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 import torch.distributed as dist def moe_a2a_dispatch(x, expert_idx, num_experts, ctx): """Reference: sort by expert, all-gather the count matrix, one NCCL all-to-all, then a regroup loop. Correct and simple; it is the SPECIFICATION, not a performance target. There is no arithmetic here — every output row is a verbatim copy of an input row — so a correct implementation matches bitwise. """ W, r = ctx.world_size, ctx.rank E = num_experts EL = E // W T, H = x.shape dev = x.device idx = expert_idx.long() order = torch.argsort(idx, stable=True) # tokens grouped by expert, original order kept xs = x[order].contiguous() cnt = torch.bincount(idx, minlength=E).to(torch.int32) # (E,) my tokens per expert all_cnt = torch.empty(W * E, dtype=torch.int32, device=dev) dist.all_gather_into_tensor(all_cnt, cnt, group=ctx.group) all_cnt = all_cnt.view(W, E) recv = all_cnt[:, r * EL:(r + 1) * EL].contiguous() # (W, EL) what each source sends to my experts send_split = cnt.view(W, EL).sum(1).tolist() # to each destination rank recv_split = recv.sum(1).tolist() # from each source rank y_raw = torch.empty(int(sum(recv_split)), H, dtype=x.dtype, device=dev) dist.all_to_all_single(y_raw, xs, recv_split, send_split, group=ctx.group) # y_raw is grouped (source_rank, local_expert); the grouped GEMM wants (local_expert, source_rank) y = torch.empty_like(y_raw) base = torch.cat([torch.zeros(1, dtype=torch.long, device=dev), recv.sum(0).long().cumsum(0)]) cur = base[:-1].tolist() rc = recv.tolist() off = 0 for s in range(W): for e in range(EL): n = rc[s][e] if n: y[cur[e]:cur[e] + n] = y_raw[off:off + n] cur[e] += n off += n return y, recv