File size: 3,581 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference-EQUIVALENT submission for `dist-moe-a2a-dispatch` — validation only, NOT shipped.

No torch.distributed data collective and no pre-packaged fused collective: the count matrix goes through
ctx.all_gather_object (the sanctioned metadata path) and the payload through a shared MAPPED HOST buffer
(mmap of /dev/shm + cudaHostRegister PORTABLE|MAPPED) with sequence-counter flags.  Only the block destined
for the peer is published; the rank's own tokens never touch the link.
"""
import mmap
import os

import torch

MAX_BYTES = 1 << 29
_S = {}


def _map(path, nbytes, ctx, register):
    if ctx.rank == 0:
        with open(path, "wb") as f:
            f.truncate(nbytes)
    ctx.barrier()
    f = open(path, "r+b")
    mm = mmap.mmap(f.fileno(), nbytes)
    t = torch.frombuffer(mm, dtype=torch.uint8)
    if register:
        err = torch.cuda.cudart().cudaHostRegister(t.data_ptr(), nbytes, 3)
        assert int(err) == 0, f"cudaHostRegister failed: {err}"
    ctx.barrier()
    if ctx.rank == 0:
        os.unlink(path)
    return f, mm, t


def _setup(ctx):
    if "data" in _S:
        return
    tag = os.environ.get("MASTER_PORT", "0")
    _S["data"] = _map(f"/dev/shm/a2ad_data_{tag}", ctx.world_size * MAX_BYTES, ctx, True)
    _S["flag"] = _map(f"/dev/shm/a2ad_flag_{tag}", 4096, ctx, False)
    _S["flags"] = _S["flag"][2].view(torch.int64)
    _S["flags"].zero_()
    _S["seq"] = 0
    ctx.barrier()


def _wait(flags, i, seq):
    while int(flags[i]) < seq:
        pass


def moe_a2a_dispatch(x, expert_idx, num_experts, ctx):
    _setup(ctx)
    W, r = ctx.world_size, ctx.rank
    peer = 1 - r
    E, EL = num_experts, num_experts // ctx.world_size
    T, H = x.shape
    dev = x.device
    flags = _S["flags"]
    _S["seq"] += 1
    seq = _S["seq"]

    idx = expert_idx.long()
    order = torch.argsort(idx, stable=True)
    xs = x[order].contiguous()
    cnt = torch.bincount(idx, minlength=E).to(torch.int32)

    all_cnt = ctx.all_gather_object(cnt.tolist())                    # metadata only: E ints per rank
    recv = torch.tensor([[all_cnt[s][r * EL + e] for e in range(EL)] for s in range(W)],
                        dtype=torch.int32, device=dev)
    send = [sum(all_cnt[r][d * EL:(d + 1) * EL]) for d in range(W)]  # rows I send to each destination
    start = sum(send[:peer])                                         # where the peer's block sits in xs
    n_send = send[peer]

    slot = _S["data"][2].view(torch.bfloat16).view(W, -1)
    if n_send:
        slot[r][:n_send * H].view(n_send, H).copy_(xs[start:start + n_send], non_blocking=True)
    torch.cuda.synchronize()
    flags[r] = seq
    _wait(flags, peer, seq)

    rc = recv.tolist()
    n_from_peer = sum(rc[peer])
    buf = torch.empty(n_from_peer, H, dtype=x.dtype, device=dev)
    if n_from_peer:
        buf.copy_(slot[peer][:n_from_peer * H].view(n_from_peer, H), non_blocking=True)

    R = int(recv.sum())
    y = torch.empty(R, H, dtype=x.dtype, device=dev)
    mine_off = sum(send[:r])          # my own block inside xs, already expert-sorted
    peer_off = 0
    out_off = 0
    for e in range(EL):
        for s in range(W):
            n = rc[s][e]
            if n:
                if s == r:
                    y[out_off:out_off + n] = xs[mine_off:mine_off + n]
                    mine_off += n
                else:
                    y[out_off:out_off + n] = buf[peer_off:peer_off + n]
                    peer_off += n
                out_off += n
    torch.cuda.synchronize()
    flags[W + r] = seq
    _wait(flags, W + peer, seq)
    return y, recv