test_swipe.py 2.39 KB
Newer Older
Rick Ho's avatar
Rick Ho committed
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
import pytest

import os
import sys
import json
import math

import torch
import torch.distributed as dist
import torch.nn.functional as F
from fmoe.functions import ensure_comm
from fmoe.gates.swipe_gate import SwipeGate 
from test_ddp import _ensure_initialized, _run_distributed



@pytest.mark.parametrize("d_model", [1024])
@pytest.mark.parametrize("batch_size", [16])
@pytest.mark.parametrize("n_expert", [1, 4])
@pytest.mark.parametrize("top_k", [2, 4])
@pytest.mark.parametrize("world_size", [2, 4, 8])
def test_swipe_gate(world_size, d_model, batch_size, n_expert, top_k):
    if world_size * n_expert < 2:
        pytest.skip("No enough experts")
    _run_distributed('_test_swipe_gate',
            world_size,
            {
                'd_model': d_model,
                'batch_size': batch_size,
                'n_expert': n_expert,
                'top_k': top_k
            },
            script=__file__
    )


def _test_swipe_gate(d_model, batch_size, n_expert, top_k):
    _ensure_initialized()
    gate = SwipeGate(d_model, n_expert, dist.get_world_size()).cuda()
    x = torch.rand(batch_size, d_model).cuda()
    ensure_comm(x, None)
    topk_idx, topk_val = gate(x)


@pytest.mark.parametrize("batch_size", [16])
@pytest.mark.parametrize("n_expert", [1, 4])
@pytest.mark.parametrize("world_size", [2, 4, 8])
def test_swipe_once(world_size, batch_size, n_expert):
    if world_size * n_expert < 2:
        pytest.skip("No enough experts")
    _run_distributed('_test_swipe_once',
            world_size,
            {
                'batch_size': batch_size,
                'n_expert': n_expert
            },
            script=__file__
    )


def _test_swipe_once(batch_size, n_expert):
    _ensure_initialized()
    rank = dist.get_rank()
    world_size = dist.get_world_size()
    gate = SwipeGate(4, n_expert, dist.get_world_size()).cuda()
    idx = torch.randint(0, n_expert * world_size, (batch_size,)).cuda()
Rick Ho's avatar
Rick Ho committed
67
    capacity = torch.scalar_tensor(batch_size * 2, dtype=torch.long)
Rick Ho's avatar
Rick Ho committed
68
69
    ensure_comm(idx, None)
    new_idx, new_cap = gate.swipe_once(idx, capacity, 0)
Rick Ho's avatar
Rick Ho committed
70
71
    idx = torch.randint(0, n_expert * world_size, (batch_size,)).cuda()
    new_idx, new_cap = gate.swipe_once(idx, new_cap, 0)
Rick Ho's avatar
Rick Ho committed
72
73
74
75
76
77

if __name__ == '__main__':
    if len(sys.argv) >= 3:
        args = json.loads(sys.argv[2])
        locals()[sys.argv[1]](**args)
    else:
Rick Ho's avatar
Rick Ho committed
78
79
        test_swipe_gate(8, 4, 8, 4, 2)
        # test_swipe_once(8, 800, 4)