"vscode:/vscode.git/clone" did not exist on "6cbe044aae0398cf2a27ae68b8a54390b4ad6bdd"
test_faster_shadow.py 2.54 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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 test_ddp import _ensure_initialized, _run_distributed
from test_numerical import _assert_numerical
from fmoe.fastermoe.schedule import _fmoe_general_global_forward as smart_fwd
from fmoe.layers import _fmoe_general_global_forward as naive_fwd


@pytest.mark.parametrize("n_process", [8])
@pytest.mark.parametrize("d_model", [1024])
@pytest.mark.parametrize("batch_size", [16])
@pytest.mark.parametrize("n_expert", [1])
@pytest.mark.parametrize("group_sz", [1, 2, 4])
def test_faster_shadow(n_process, d_model, batch_size, n_expert, group_sz):
    _run_distributed('_test_faster_shadow',
            n_process,
            {
                'd_model': d_model,
                'batch_size': batch_size,
                'n_expert': n_expert
            },
            script=__file__,
            env=dict(
                FMOE_FASTER_GROUP_SIZE=str(group_sz)
            )
    )


def _test_faster_shadow(d_model, batch_size, n_expert):
    _ensure_initialized()
    rank = dist.get_rank()
    world_size = dist.get_world_size()

    x1 = torch.rand(batch_size, d_model).cuda()
    x1.requires_grad = True
    x2 = x1.data.clone()
    x2.requires_grad = True
    topk_idx = torch.randint(0, world_size * n_expert, (batch_size, 2)).cuda()
    m1 = torch.nn.Linear(d_model, d_model).cuda()
    m2 = torch.nn.Linear(d_model, d_model).cuda()
    with torch.no_grad():
        m2.weight.copy_(m1.weight)
        m2.bias.copy_(m1.bias)

    def ef1(x, fec):
        y = m1(x)
        return y
    def ef2(x, fec):
        y = m2(x)
        return y

    stored_models = torch.randint(0, 2, (world_size,)).bool().cuda()
    dist.broadcast(stored_models, 0)
    stored_models = stored_models.cpu()

    ensure_comm(x1, None)
    y1 = smart_fwd(x1, topk_idx, ef1, n_expert, world_size, experts=m1, stored_models=stored_models)
    # y1.sum().backward()

    y2 = naive_fwd(x2, topk_idx, ef2, n_expert, world_size, experts=m2)
    # y2.sum().backward()
    _assert_numerical(['out'], [y1], [y2], rank)
    # _assert_numerical(['out', 'grad_in', 'grad_bias', 'grad_weight'],
    #         [y1, x1.grad, m1.bias.grad, m1.weight.grad],
    #         [y2, x2.grad, m2.bias.grad, m2.weight.grad], rank)


if __name__ == '__main__':
    if len(sys.argv) >= 3:
        args = json.loads(sys.argv[2])
        locals()[sys.argv[1]](**args)
    else:
        # test_faster_shadow(8, 16, 16, 1, 2)
        _test_faster_shadow(4, 2, 1)