test_init_context.py 3.27 KB
Newer Older
Jiarui Fang's avatar
Jiarui Fang committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from functools import partial

import pytest
import torch
import torch.multiprocessing as mp
9
10
11
12
from common import CONFIG

import colossalai
from colossalai.gemini.memory_tracer.utils import colo_model_mem_usage
ver217's avatar
ver217 committed
13
from colossalai.logging import get_dist_logger
14
from colossalai.testing import parameterize, rerun_if_address_is_in_use
Jiarui Fang's avatar
Jiarui Fang committed
15
from colossalai.utils import free_port
ver217's avatar
ver217 committed
16
from colossalai.utils.cuda import get_current_device
17
from colossalai.utils.memory import colo_device_memory_used
ver217's avatar
ver217 committed
18
from colossalai.zero.init_ctx import ZeroInitContext
19
from colossalai.zero.shard_utils import BucketTensorShardStrategy, TensorShardStrategy
20
from tests.components_to_test.registry import non_distributed_component_funcs
ver217's avatar
ver217 committed
21

Jiarui Fang's avatar
Jiarui Fang committed
22

23
@parameterize("init_device_type", ['cpu', 'cuda'])
24
@parameterize("shard_strategy_class", [TensorShardStrategy, BucketTensorShardStrategy])
25
def run_model_test(init_device_type, shard_strategy_class):
26
27
    logger = get_dist_logger("test_zero_init")

28
29
30
31
32
33
    for name, get_components_func in non_distributed_component_funcs._registry.items():
        # because the ZeroInitContext automatically turns parameters to fp16
        # and the beit model use tensor.erfinv_() function to initialize weights
        # tensor.erfinv_() doesn't support Half in CPU, we omit the beit model
        if name == 'beit':
            continue
34
        model_builder, _, _, _, _ = get_components_func()
35
        if init_device_type == 'cuda':
36
            init_device = get_current_device()
37
38
39
40
        elif init_device_type == 'cpu':
            init_device = torch.device("cpu")
        else:
            continue
41
42

        model_numel_tensor = torch.zeros(1, dtype=torch.int)
ver217's avatar
ver217 committed
43
        with ZeroInitContext(target_device=init_device,
44
                             shard_strategy=shard_strategy_class(),
45
                             shard_param=True,
46
                             model_numel_tensor=model_numel_tensor):
47
48
            model = model_builder(checkpoint=True)

49
        for param in model.parameters():
50
51
52
            assert hasattr(param, 'colo_attr')
            assert param.colo_attr.sharded_data_tensor.dtype == torch.half
            assert param.colo_attr.sharded_data_tensor.is_sharded
53
54
            assert param.colo_attr.data_payload.device.type == init_device.type, \
                f'{param.colo_attr.data_payload.device.type} vs. {init_device.type}'
55

Jiarui Fang's avatar
Jiarui Fang committed
56
        cuda_mem_use, _ = colo_model_mem_usage(model)
57
58
        model_data_cuda_mem_MB = cuda_mem_use / 1e6
        logger.info(f"Existing ZeRO Context.\nModel Data CUDA Memory {model_data_cuda_mem_MB} MB", ranks=[0])
Jiarui Fang's avatar
Jiarui Fang committed
59
        sys_cuda_mem_MB = colo_device_memory_used(get_current_device()) / 1e6
60
61
        logger.info(f"System CUDA Memory Usage {sys_cuda_mem_MB} MB", ranks=[0])
        logger.info(f"Model Number Parameter {model_numel_tensor.numpy()[0]/1e6} M", ranks=[0])
62

Jiarui Fang's avatar
Jiarui Fang committed
63

64
65
66
67
68
def run_dist(rank, world_size, port):
    colossalai.launch(config=CONFIG, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
    run_model_test()


Jiarui Fang's avatar
Jiarui Fang committed
69
@pytest.mark.dist
70
@pytest.mark.parametrize("world_size", [1, 4])
71
@rerun_if_address_is_in_use()
72
73
def test_zero_init_context(world_size):
    run_func = partial(run_dist, world_size=world_size, port=free_port())
Jiarui Fang's avatar
Jiarui Fang committed
74
75
76
77
    mp.spawn(run_func, nprocs=world_size)


if __name__ == '__main__':
78
    test_zero_init_context(1)