test_model.py 12.1 KB
Newer Older
1
from colossalai.tensor.colo_parameter import ColoParameter
2
3
4
5
from tests.components_to_test.registry import non_distributed_component_funcs

import colossalai
import pytest
6
import torch
7
import torch.multiprocessing as mp
8
from colossalai.testing import rerun_if_address_is_in_use
9
10
from colossalai.utils.cuda import get_current_device
from colossalai.utils import free_port
11
12
from colossalai.utils.model.colo_init_context import ColoInitContext
from colossalai.tensor import distspec, TensorSpec, ComputePattern, \
13
    ComputeSpec, ColoTensor, DistSpecManager, ProcessGroup
14
from colossalai.nn.optimizer import ColoOptimizer
15
from functools import partial
16
from _utils import tensor_shard_equal, set_seed
17

18

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

25

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

32

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

39

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

46

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

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

57
58
59
60
61
62
63
64
    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)
65

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

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

109
110
111
        data = data.to(get_current_device())
        label = label.to(get_current_device())

112
113
        torch.distributed.broadcast(data, 0, group=pg.tp_process_group())
        torch.distributed.broadcast(label, 0, group=pg.tp_process_group())
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        # 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:
132
            with torch.no_grad():
ver217's avatar
ver217 committed
133
                assert torch.allclose(loss, loss_torch, rtol=1e-2)
134
135

        loss.backward()
136
        colo_optimizer.step()
137
138
139

        if rank == 0:
            loss_torch.backward()
140
141
142
143
            colo_optimizer_torch.step()

            with torch.no_grad():
                # check param
144
145
                for p, torch_p in zip(model.parameters(), model_torch.parameters()):
                    assert tensor_shard_equal(torch_p, p)
146

147
148
        if i > 5:
            break
149

150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# 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
169
    for name, colo_p in model.named_parameters():
170
171
        assert colo_p.is_model_data()

172
173
174
175
176
177
178
179
180
181
182
    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


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
209
210
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


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

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

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

225
226
227
228
    set_seed(1)
    if rank == 0:
        model_torch = model_builder(checkpoint=True)
        model_torch = model_torch.cuda()
229
    # A naive way to set spec for all weights in Linear
ver217's avatar
ver217 committed
230
    for name, p in model.named_parameters():
231
232
233
        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:
234
            init_1d_row_linear(p, pg)
235
        if 'embed' in name and 'weight' in name:
236
            init_1d_row_embedding(p, pg)
237

238
    model = model.cuda()
239
240

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

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

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

255
256
257
258
259
260
261
262
263
264
        # 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
265
            assert torch.allclose(loss, loss_torch, rtol=1e-2)
266

267
268
        loss.backward()

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


275
276
277
278
279
280
281
282
283
284
285
286
287
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
288
    c_ref = 0
289
290
    for name, param in model_pretrained.named_parameters():
        dict_pretrained[name] = param
Ziyue Jiang's avatar
Ziyue Jiang committed
291
        c_ref += 1
292
293
    c1 = 0
    c2 = 0
ver217's avatar
ver217 committed
294
    for name, param in model.named_parameters():
295
        if isinstance(param, ColoParameter):
Ziyue Jiang's avatar
Ziyue Jiang committed
296
            c1 += 1
297
        else:
298
            c2 += 1
299
        dict_col[name] = param
Ziyue Jiang's avatar
Ziyue Jiang committed
300
301
302
303
    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
304
305
306
307
308
309

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


def run_model_dist(rank, world_size, port):
310
311
    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
312
    for name in ['simple_net']:
313
        run_1d_row_tp(name)
314
    for name in ['bert', 'simple_net']:
Ziyue Jiang's avatar
Ziyue Jiang committed
315
        run_1d_hybrid_tp(name)
316

317

318
@pytest.mark.dist
Ziyue Jiang's avatar
Ziyue Jiang committed
319
@pytest.mark.parametrize('world_size', [1, 4])
320
@rerun_if_address_is_in_use()
321
def test_model(world_size):
322
323
324
325
326
327
328
329
330
331
332
333
    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.
334
@pytest.mark.skip
335
336
337
@pytest.mark.dist
@pytest.mark.parametrize('world_size', [1, 4])
@rerun_if_address_is_in_use()
338
def test_pretrain_load(world_size):
339
    run_func = partial(run_pretrain_load_dist, world_size=world_size, port=free_port())
340
341
    mp.spawn(run_func, nprocs=world_size)

342
343

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