2022-06-10 02:09:48 +00:00
|
|
|
import torch
|
|
|
|
from colossalai.utils.model.lazy_init_context import LazyInitContext
|
2022-06-29 13:02:30 +00:00
|
|
|
from torchvision.models import resnet34
|
2022-07-04 02:12:02 +00:00
|
|
|
import random
|
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
MANUAL_SEED = 0
|
|
|
|
random.seed(MANUAL_SEED)
|
|
|
|
np.random.seed(MANUAL_SEED)
|
|
|
|
torch.manual_seed(MANUAL_SEED)
|
2022-06-10 02:09:48 +00:00
|
|
|
|
|
|
|
|
2022-06-29 13:02:30 +00:00
|
|
|
def test_lazy_init():
|
2022-07-04 02:12:02 +00:00
|
|
|
cpu_rng_state = torch.get_rng_state()
|
|
|
|
origin_model = resnet34(num_classes=10)
|
|
|
|
origin_param_dict = dict(origin_model.named_parameters())
|
|
|
|
torch.set_rng_state(cpu_rng_state)
|
2022-06-29 13:02:30 +00:00
|
|
|
ctx = LazyInitContext()
|
|
|
|
with ctx:
|
|
|
|
model = resnet34(num_classes=10)
|
|
|
|
for param in model.parameters():
|
|
|
|
assert param.is_meta
|
|
|
|
for buffer in model.buffers():
|
|
|
|
assert buffer.is_meta
|
2022-06-10 02:09:48 +00:00
|
|
|
ctx.lazy_init_parameters(model)
|
2022-06-29 13:02:30 +00:00
|
|
|
for param in model.parameters():
|
|
|
|
assert not param.is_meta
|
|
|
|
for buffer in model.buffers():
|
|
|
|
assert not buffer.is_meta
|
2022-07-04 02:12:02 +00:00
|
|
|
param_dict = dict(model.named_parameters())
|
|
|
|
for key in origin_param_dict.keys():
|
|
|
|
assert origin_param_dict[key].data.equal(param_dict[key].data)
|
2022-06-10 02:09:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2022-06-29 13:02:30 +00:00
|
|
|
test_lazy_init()
|