test_utilities.py 3.29 KB
Newer Older
Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
1
import os
liangjing's avatar
liangjing committed
2
3
from datetime import timedelta

Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
4
import torch
liangjing's avatar
liangjing committed
5
6
7
from torch._C._distributed_c10d import PrefixStore
from torch.distributed import rendezvous

Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
8
9
import megatron.core.parallel_state as ps

liangjing's avatar
liangjing committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class TestModel(torch.nn.Module):
    def __init__(
        self,
        input_dim: int,
        output_dim: int,
        num_layers: int,
        bias: bool,
        shared_embedding: bool = False,
    ):
        super().__init__()
        self.layers = torch.nn.ModuleList(
            [torch.nn.Linear(input_dim, output_dim, bias) for _ in range(num_layers)]
        )
        if shared_embedding:
            self.layers[-1].weight.shared_embedding = True


Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
28
29
30
31
class Utils:

    world_size = torch.cuda.device_count()
    rank = int(os.environ['LOCAL_RANK'])
liangjing's avatar
liangjing committed
32
33
    inited = False
    store = None
Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
34
35
36

    @staticmethod
    def initialize_distributed():
liangjing's avatar
liangjing committed
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
        if not torch.distributed.is_initialized() and Utils.rank >= 0:
            print(
                f'Initializing torch.distributed with rank: {Utils.rank}, '
                f'world_size: {Utils.world_size}'
            )
            torch.cuda.set_device(Utils.rank % torch.cuda.device_count())
            init_method = 'tcp://'
            master_ip = os.getenv('MASTER_ADDR', 'localhost')
            master_port = os.getenv('MASTER_PORT', '6000')
            init_method += master_ip + ':' + master_port
            rendezvous_iterator = rendezvous(
                init_method, Utils.rank, Utils.world_size, timeout=timedelta(minutes=1)
            )
            store, rank, world_size = next(rendezvous_iterator)
            store.set_timeout(timedelta(minutes=1))

            # Use a PrefixStore to avoid accidental overrides of keys used by
            # different systems (e.g. RPC) in case the store is multi-tenant.
            store = PrefixStore("default_pg", store)
            Utils.store = store

            torch.distributed.init_process_group(
                backend='nccl', world_size=Utils.world_size, rank=Utils.rank, store=store
            )

            torch.distributed.barrier()
        Utils.inited = True

    @staticmethod
    def set_world_size(world_size=None, rank=None):
        Utils.world_size = torch.cuda.device_count() if world_size is None else world_size
        if (
            torch.distributed.is_initialized()
            and Utils.world_size != torch.distributed.get_world_size()
        ):
            torch.distributed.destroy_process_group()

        if rank is None:
            Utils.rank = int(os.environ['LOCAL_RANK'])
            if Utils.rank >= Utils.world_size:
                Utils.rank = -1
        else:
            Utils.rank = rank

Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
81
82
    @staticmethod
    def destroy_model_parallel():
liangjing's avatar
liangjing committed
83
84
        if not Utils.inited:
            return
Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
85
        torch.distributed.barrier()
liangjing's avatar
liangjing committed
86
87
        ps.destroy_model_parallel()
        Utils.inited = False
Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
88
89

    @staticmethod
liangjing's avatar
liangjing committed
90
91
92
93
94
95
    def initialize_model_parallel(
        tensor_model_parallel_size=1,
        pipeline_model_parallel_size=1,
        virtual_pipeline_model_parallel_size=None,
        **kwargs,
    ):
Shanmugam Ramasamy's avatar
Shanmugam Ramasamy committed
96
        ps.destroy_model_parallel()
liangjing's avatar
liangjing committed
97
98
99
100
101
102
103
104
        Utils.initialize_distributed()
        ps.initialize_model_parallel(
            tensor_model_parallel_size,
            pipeline_model_parallel_size,
            virtual_pipeline_model_parallel_size,
            **kwargs,
        )
        Utils.inited = True