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-07-15 09:47:12 +00:00
|
|
|
def test_lazy_init_with_meta():
|
|
|
|
ctx = LazyInitContext(to_meta=True)
|
2022-06-29 13:02:30 +00:00
|
|
|
with ctx:
|
|
|
|
model = resnet34(num_classes=10)
|
2022-07-15 09:47:12 +00:00
|
|
|
|
2022-06-29 13:02:30 +00:00
|
|
|
for param in model.parameters():
|
|
|
|
assert param.is_meta
|
|
|
|
for buffer in model.buffers():
|
|
|
|
assert buffer.is_meta
|
2022-07-15 09:47:12 +00:00
|
|
|
|
2022-06-10 02:09:48 +00:00
|
|
|
ctx.lazy_init_parameters(model)
|
2022-07-15 09:47:12 +00:00
|
|
|
|
|
|
|
for name, param in model.named_parameters():
|
|
|
|
assert not param.is_meta, name
|
|
|
|
|
|
|
|
for buffer in model.buffers():
|
|
|
|
assert not buffer.is_meta
|
|
|
|
|
|
|
|
|
|
|
|
def test_lazy_init_without_meta():
|
|
|
|
ctx = LazyInitContext(to_meta=False)
|
|
|
|
with ctx:
|
|
|
|
model = resnet34(num_classes=10)
|
|
|
|
|
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-15 09:47:12 +00:00
|
|
|
|
|
|
|
conv1_weight_before_init = model.conv1.weight.clone()
|
|
|
|
ctx.lazy_init_parameters(model)
|
|
|
|
conv1_weight_after_init = model.conv1.weight.clone()
|
|
|
|
|
|
|
|
assert not torch.allclose(conv1_weight_after_init, conv1_weight_before_init)
|
2022-06-10 02:09:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2022-07-15 09:47:12 +00:00
|
|
|
test_lazy_init_with_meta()
|
|
|
|
test_lazy_init_without_meta()
|