"tests/test_autochunk/vscode:/vscode.git/clone" did not exist on "63199c668792cf86f24e8583363e8625154ed9d5"
test_model.py 12 KB
Newer Older
1
import pytest
2
3
4
from functools import partial
from _utils import tensor_shard_equal, set_seed

5
import torch
6
import torch.multiprocessing as mp
7
8
9

from colossalai.tensor.colo_parameter import ColoParameter
import colossalai
10
from colossalai.testing import rerun_if_address_is_in_use
11
12
from colossalai.utils.cuda import get_current_device
from colossalai.utils import free_port
13
14
from colossalai.utils.model.colo_init_context import ColoInitContext
from colossalai.tensor import distspec, TensorSpec, ComputePattern, \
15
    ComputeSpec, ColoTensor, DistSpecManager, ProcessGroup
16
from colossalai.nn.optimizer import ColoOptimizer
17
18

from tests.components_to_test.registry import non_distributed_component_funcs
19

20

21
def init_1d_row_linear(weight, pg: ProcessGroup):
22
    spec = TensorSpec(distspec.shard(pg, [-1], [pg.tp_world_size()]), ComputeSpec(ComputePattern.TP1D))
23
    with DistSpecManager.no_grad():
24
        weight.set_tensor_spec(spec)
25

26

27
def init_1d_col_linear(weight, pg):
28
    spec = TensorSpec(distspec.shard(pg, [0], [pg.tp_world_size()]), ComputeSpec(ComputePattern.TP1D))
29
    with DistSpecManager.no_grad():
30
        weight.set_tensor_spec(spec)
31

32

33
def init_1d_row_embedding(weight, pg):
34
    spec = TensorSpec(distspec.shard(pg, [0], [pg.tp_world_size()]), ComputeSpec(ComputePattern.TP1D))
35
    with DistSpecManager.no_grad():
36
        weight.set_tensor_spec(spec)
37

38

39
def init_1d_col_embedding(weight, pg):
40
    spec = TensorSpec(distspec.shard(pg, [-1], [pg.tp_world_size()]), ComputeSpec(ComputePattern.TP1D))
41
    with DistSpecManager.no_grad():
42
        weight.set_tensor_spec(spec)
43

44

Ziyue Jiang's avatar
Ziyue Jiang committed
45
def run_1d_hybrid_tp(model_name):
46
    # A simple net with two stacked nn.Linear
47
    get_components_func = non_distributed_component_funcs.get_callable(model_name)
48
    model_builder, train_dataloader, test_dataloader, optimizer_class, criterion = get_components_func()
49
    rank = torch.distributed.get_rank()
50
51
52
53

    set_seed(1)
    with ColoInitContext(device=get_current_device()):
        model = model_builder(checkpoint=True)
54

55
56
57
58
59
60
61
62
    if rank == 0:
        model_torch = model_builder(checkpoint=True)
        model_torch = model_torch.cuda()
        colo_optimizer_torch = ColoOptimizer(dict(model_torch.named_parameters()), torch.optim.SGD, lr=0.1)

        # Make two models have the same init params
        for p1, p2 in zip(model.parameters(), model_torch.parameters()):
            p2.data.copy_(p1.data)
63

64
65
66
    rank = torch.distributed.get_rank()
    world_size = torch.distributed.get_world_size()
    pg = ProcessGroup(tp_degree=world_size)
67
    if 'bert' == model_name:
ver217's avatar
ver217 committed
68
        for name, p in model.named_parameters():
69
70
            if not isinstance(p, ColoTensor):
                continue
71
            # print(name)
Ziyue Jiang's avatar
Ziyue Jiang committed
72
73
            # num_class = type_vocab_size = 2 | (8, 2)
            if 'classifier' in name and 'weight' in name:
74
                init_1d_row_linear(p, pg)
Ziyue Jiang's avatar
Ziyue Jiang committed
75
76
            # num_class = vocab_size = 30524 | (30524, 8)
            if 'word_embeddings' in name and 'weight' in name:
77
                init_1d_row_embedding(p, pg)
Ziyue Jiang's avatar
Ziyue Jiang committed
78
79
            # num_class = seq_len = 512 | (512, 8)
            if 'position_embeddings' in name and 'weight' in name:
80
                init_1d_row_embedding(p, pg)
Ziyue Jiang's avatar
Ziyue Jiang committed
81
82
            # num_class = type_vocab_size = 2 | (2, 8)
            if 'token_type_embeddings' in name and 'weight' in name:
83
                init_1d_col_embedding(p, pg)
84
85
    elif "simple_net" == model_name:
        # A naive way to set spec for all weights in Linear
ver217's avatar
ver217 committed
86
        for name, p in model.named_parameters():
87
88
            if not isinstance(p, ColoTensor):
                continue
89
            if 'embed' in name and 'weight' in name:
90
                init_1d_col_embedding(p, pg)
91
            if 'proj1' in name and ('weight' in name or 'bias' in name):
92
                init_1d_col_linear(p, pg)
93
            if 'proj2' in name and 'weight' in name:
94
                init_1d_row_linear(p, pg)
95
            if 'classifier' in name and ('weight' in name or 'bias' in name):
96
                init_1d_col_linear(p, pg)
97

98
    model = model.cuda()
99
    colo_optimizer = ColoOptimizer(dict(model.named_parameters()), torch.optim.SGD, lr=0.1)
100
    for i, (data, label) in enumerate(train_dataloader):
101
102
103
104
105
        model.eval()
        colo_optimizer.zero_grad()
        if rank == 0:
            model_torch.eval()
            colo_optimizer_torch.zero_grad()
106

107
108
109
        data = data.to(get_current_device())
        label = label.to(get_current_device())

110
111
        torch.distributed.broadcast(data, 0, group=pg.tp_process_group())
        torch.distributed.broadcast(label, 0, group=pg.tp_process_group())
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
        # Bcast rank0 data to all processes
        if criterion:
            output = model(data)
            loss = criterion(output, label)
        else:
            output = model(data, label)
            loss = output

        # For reference
        if rank == 0:
            if criterion:
                output_torch = model_torch(data)
                loss_torch = criterion(output_torch, label)
            else:
                output_torch = model_torch(data, label)
                loss_torch = output_torch

        if rank == 0:
130
            with torch.no_grad():
ver217's avatar
ver217 committed
131
                assert torch.allclose(loss, loss_torch, rtol=1e-2)
132
133

        loss.backward()
134
        colo_optimizer.step()
135
136
137

        if rank == 0:
            loss_torch.backward()
138
139
140
141
            colo_optimizer_torch.step()

            with torch.no_grad():
                # check param
142
                for p, torch_p in zip(model.parameters(), model_torch.parameters()):
143
                    assert tensor_shard_equal(torch_p, p, pg.tp_local_rank(), pg.tp_world_size())
144

145
146
        if i > 5:
            break
147

148

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# Test the overrided parameters() and named_parameters() member functions
def test_model_parameters():
    # build a module with 2 Linear, 4 parameters in total.
    class Net(torch.nn.Module):

        def __init__(self):
            super().__init__()
            self.fcs = torch.nn.Sequential(torch.nn.Linear(2, 3), torch.nn.Linear(3, 2))
            self.extra_param = torch.nn.Parameter(torch.randn(2))

    with ColoInitContext(device=get_current_device()):
        model = Net()

    param_cnt = 0
    for name, p in model.named_parameters():
        param_cnt += 1
    assert param_cnt == 5

ver217's avatar
ver217 committed
167
    for name, colo_p in model.named_parameters():
168
169
        assert colo_p.is_model_data()

170
171
172
173
174
175
176
177
178
179
180
    param_cnt = 0
    for name, p in model.named_parameters(recurse=False):
        param_cnt += 1
    assert param_cnt == 1

    param_cnt = 0
    for p in model.fcs[0].parameters(recurse=False):
        param_cnt += 1
    assert param_cnt == 2


181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def test_colo_optimizer():
    get_components_func = non_distributed_component_funcs.get_callable('simple_net')
    model_builder, train_dataloader, test_dataloader, optimizer_class, criterion = get_components_func()
    set_seed(1)
    with ColoInitContext(lazy_memory_allocate=False, device=get_current_device()):
        model = model_builder(checkpoint=True)

    colo_optimizer = ColoOptimizer(dict(model.named_parameters()), torch.optim.SGD, lr=0.1)
    for i, (data, label) in enumerate(train_dataloader):
        colo_optimizer.zero_grad()
        data = data.to(get_current_device())
        label = label.to(get_current_device())

        # Bcast rank0 data to all processes
        if criterion:
            output = model(data)
            loss = criterion(output, label)
        else:
            output = model(data, label)
            loss = output

        loss.backward()
        colo_optimizer.step()

        if i > 5:
            break


209
def run_1d_row_tp(model_name: str):
210
    # A simple net with two stacked nn.Linear
211
    get_components_func = non_distributed_component_funcs.get_callable(model_name)
212
    model_builder, train_dataloader, test_dataloader, optimizer_class, criterion = get_components_func()
213
    rank = torch.distributed.get_rank()
214

215
    set_seed(1)
216
    with ColoInitContext(device=get_current_device()):
217
218
        model = model_builder(checkpoint=True)

219
220
    rank = torch.distributed.get_rank()
    world_size = torch.distributed.get_world_size()
221
222
    pg = ProcessGroup(rank, list(range(world_size)), tp_degree=world_size)

223
224
225
226
    set_seed(1)
    if rank == 0:
        model_torch = model_builder(checkpoint=True)
        model_torch = model_torch.cuda()
227
    # A naive way to set spec for all weights in Linear
ver217's avatar
ver217 committed
228
    for name, p in model.named_parameters():
229
230
231
        if not isinstance(p, ColoTensor):
            continue
        if 'weight' in name and 'LayerNorm' not in name and 'ln' not in name and 'embed' not in name:
232
            init_1d_row_linear(p, pg)
233
        if 'embed' in name and 'weight' in name:
234
            init_1d_row_embedding(p, pg)
235

236
    model = model.cuda()
237
238

    for i, (data, label) in enumerate(train_dataloader):
239
240
        data = data.to(get_current_device())
        label = label.to(get_current_device())
241

242
243
        torch.distributed.broadcast(data, 0, group=pg.tp_process_group())
        torch.distributed.broadcast(label, 0, group=pg.tp_process_group())
244
245

        # Bcast rank0 data to all processes
246
        if criterion:
247
            output = model(data)
248
249
            loss = criterion(output, label)
        else:
250
            output = model(data, label)
251
252
            loss = output

253
254
255
256
257
258
259
260
261
262
        # For reference
        if rank == 0:
            if criterion:
                output_torch = model_torch(data)
                loss_torch = criterion(output_torch, label)
            else:
                output_torch = model_torch(data, label)
                loss_torch = output_torch

        if rank == 0:
ver217's avatar
ver217 committed
263
            assert torch.allclose(loss, loss_torch, rtol=1e-2)
264

265
266
        loss.backward()

267
268
        if rank == 0:
            loss_torch.backward()
269
270
271
272
        if i > 5:
            break


273
274
275
276
277
278
279
280
281
282
283
284
285
def _run_pretrain_load():
    from _utils import check_equal
    from transformers import BertForMaskedLM
    set_seed(1)
    model_pretrained = BertForMaskedLM.from_pretrained('bert-base-uncased')
    with ColoInitContext(lazy_memory_allocate=False, device=get_current_device()):
        model = BertForMaskedLM.from_pretrained('bert-base-uncased')

    model_pretrained = model_pretrained.cuda()
    model = model.cuda()

    dict_pretrained = {}
    dict_col = {}
Ziyue Jiang's avatar
Ziyue Jiang committed
286
    c_ref = 0
287
288
    for name, param in model_pretrained.named_parameters():
        dict_pretrained[name] = param
Ziyue Jiang's avatar
Ziyue Jiang committed
289
        c_ref += 1
290
291
    c1 = 0
    c2 = 0
ver217's avatar
ver217 committed
292
    for name, param in model.named_parameters():
293
        if isinstance(param, ColoParameter):
Ziyue Jiang's avatar
Ziyue Jiang committed
294
            c1 += 1
295
        else:
296
            c2 += 1
297
        dict_col[name] = param
Ziyue Jiang's avatar
Ziyue Jiang committed
298
299
300
301
    assert c_ref == c1
    assert c2 == 0
    if model_pretrained.cls.predictions.decoder.bias is model_pretrained.cls.predictions.bias:
        assert model.cls.predictions.decoder.bias is model.cls.predictions.bias
302
303
304
305
306
307

    for name, param in dict_pretrained.items():
        check_equal(param, dict_col[name])


def run_model_dist(rank, world_size, port):
308
309
    config = dict(parallel=dict(tensor=dict(mode="1d", size=world_size),))
    colossalai.launch(config=config, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
Ziyue Jiang's avatar
Ziyue Jiang committed
310
    for name in ['simple_net']:
311
        run_1d_row_tp(name)
312
    for name in ['bert', 'simple_net']:
Ziyue Jiang's avatar
Ziyue Jiang committed
313
        run_1d_hybrid_tp(name)
314

315

316
@pytest.mark.dist
Ziyue Jiang's avatar
Ziyue Jiang committed
317
@pytest.mark.parametrize('world_size', [1, 4])
318
@rerun_if_address_is_in_use()
319
def test_model(world_size):
320
321
322
323
324
325
326
327
328
329
330
331
    run_func = partial(run_model_dist, world_size=world_size, port=free_port())
    mp.spawn(run_func, nprocs=world_size)


def run_pretrain_load_dist(rank, world_size, port):
    config = dict(parallel=dict(tensor=dict(mode="1d", size=world_size),))
    colossalai.launch(config=config, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
    _run_pretrain_load()


# The test case has to download huggingface pretrained models from the internet
# So we manually trigger the test.
332
@pytest.mark.skip
333
334
335
@pytest.mark.dist
@pytest.mark.parametrize('world_size', [1, 4])
@rerun_if_address_is_in_use()
336
def test_pretrain_load(world_size):
337
    run_func = partial(run_pretrain_load_dist, world_size=world_size, port=free_port())
338
339
    mp.spawn(run_func, nprocs=world_size)

340
341

if __name__ == '__main__':
342
    # test_model_parameters()
343
    # test_colo_optimizer()
344
    # test_model(4)
345
    test_pretrain_load(4)