rpc_test_utils.py 4.16 KB
Newer Older
1
import argparse
2
import os
3
import warnings
4
5

import torch
6
import torch.distributed as dist
7
8
import torch.distributed.rpc as rpc
import torch.multiprocessing as mp
9
from colossalai import launch
10
11
12
13
14
from colossalai.logging import disable_existing_loggers
from colossalai.pipeline.pipeline_process_group import ppg
from torch import nn
from torch._C._distributed_rpc import _is_current_rpc_agent_set
from torch.optim import SGD, Adam, Optimizer, RMSprop
15

16
17
rpc_is_initialized = _is_current_rpc_agent_set

18
19
20
21
22
23
24
25
26
27
28
29
30

def color_debug(text, prefix=' ', color='blue'):
    color = color.upper()
    print(getattr(Back, color), prefix, Style.RESET_ALL, text)


class RpcTestModel(nn.Module):

    def __init__(self, stage_id, actual_stage_num, feat_num, h) -> None:
        super().__init__()
        self.rank = stage_id
        self.is_last_rank = stage_id == actual_stage_num - 1
        self.linear_name = f'linear_{stage_id}'
31

32
        if stage_id == 0:
33
            linear = nn.Linear(feat_num, h)
34
        elif stage_id == actual_stage_num - 1:
35
            linear = nn.Linear(h, 1)
36
        else:
37
38
39
            linear = nn.Linear(h, h)

        setattr(self, self.linear_name, linear)
40
41
42
43
44
45
46
47
48
49
50
51

    def forward(self, x) -> torch.Tensor:
        linear: nn.Module = getattr(self, self.linear_name)
        out: torch.Tensor = linear(x)

        if self.is_last_rank:
            out = out.sum()
        return out


def parse_args():
    parser = argparse.ArgumentParser()
52
    parser.add_argument('--epoch', type=int, default=1)
53
    parser.add_argument('--world_size', type=int, default=2)
54
    parser.add_argument('--batch_size', type=int, default=16)
55
56
    parser.add_argument('--dp_degree', type=int, default=1)
    parser.add_argument('--tp_degree', type=int, default=1)
57
58
59
60
    parser.add_argument('--num_microbatches', type=int, default=2)
    parser.add_argument('--chunk', type=int, default=1)
    parser.add_argument('--use_checkpoint', action='store_true')
    parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'RMSprop'], default='SGD')
61
    parser.add_argument('--device', type=str, choices=['cpu', 'cuda'], default='cuda')
62
63
64
65
66
67
    parser.add_argument('--master_addr', type=str, default='localhost')
    parser.add_argument('--master_port', type=str, default='29020')
    parser.add_argument('--num_worker_threads', type=str, default=128)
    return parser.parse_args()


68
69
70
71
72
73
74
75
76
77
78
79
80
def pg_parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--world_size', type=int, default=4)
    parser.add_argument('--dp_degree', type=int, default=2)
    parser.add_argument('--tp_degree', type=int, default=1)
    parser.add_argument('--chunk', type=int, default=1)
    parser.add_argument('--num_worker_threads', type=str, default=128)
    parser.add_argument('--device', type=str, choices=['cpu', 'cuda'], default='cuda')
    parser.add_argument('--master_addr', type=str, default='localhost')
    parser.add_argument('--master_port', type=str, default='29020')
    return parser.parse_args()


81
82
83
84
def run_worker(rank, args, master_func):
    os.environ['MASTER_ADDR'] = args.master_addr
    os.environ['MASTER_PORT'] = args.master_port

85
    device = args.device
86
    world_size = args.world_size
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    dp_degree = args.dp_degree
    tp_degree = args.tp_degree
    num_worker_threads = args.num_worker_threads
    host = args.master_addr
    port = args.master_port
    backend = 'nccl' if device == 'cuda' else 'gloo'

    disable_existing_loggers()

    launch(dict(), rank, world_size, host, int(port), backend, verbose=False)
    ppg.set_global_info(rank=rank,
                        world_size=world_size,
                        dp_degree=dp_degree,
                        tp_degree=tp_degree,
                        num_worker_threads=num_worker_threads,
                        device=device)
103
104
105
106
107

    # in rpc mode, only rank 0 is needed to be coded
    if rank == 0:
        master_func(args)
    # barrier here
108
109
110
111
    if rpc_is_initialized():
        rpc.shutdown()
    else:
        warnings.warn("RPC has not been initialized")
112
113
114
115
116
117


def rpc_run(args, master_func):
    world_size = args.world_size
    assert args.num_microbatches >= args.world_size, "num_microbatches cannot be fewer than world_size!"
    mp.spawn(run_worker, args=(args, master_func), nprocs=world_size)