2022-03-29 09:57:59 +00:00
|
|
|
import contextlib
|
2022-03-07 08:14:40 +00:00
|
|
|
import functools
|
2022-03-21 03:18:55 +00:00
|
|
|
from typing import Optional
|
2022-03-08 10:18:06 +00:00
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
import torch
|
2022-03-21 03:18:55 +00:00
|
|
|
from colossalai.context.parallel_mode import ParallelMode
|
|
|
|
from colossalai.core import global_context as gpc
|
2022-03-29 09:57:59 +00:00
|
|
|
from colossalai.context.singleton_meta import SingletonMeta
|
2022-03-29 01:09:04 +00:00
|
|
|
from colossalai.logging import get_dist_logger
|
2022-03-07 08:14:40 +00:00
|
|
|
from colossalai.zero.shard_utils import BaseShardStrategy
|
2022-03-25 06:54:39 +00:00
|
|
|
from colossalai.zero.sharded_model._utils import cast_tensor_to_fp16
|
2022-03-07 08:14:40 +00:00
|
|
|
from colossalai.zero.sharded_param import ShardedParamV2
|
2022-03-21 03:18:55 +00:00
|
|
|
from torch.distributed import ProcessGroup
|
2022-04-01 12:10:47 +00:00
|
|
|
from contextlib import AbstractContextManager
|
2022-03-07 08:14:40 +00:00
|
|
|
|
2022-03-14 14:05:30 +00:00
|
|
|
|
2022-03-28 09:42:18 +00:00
|
|
|
def _substitute_init_recursively(cls, func):
|
|
|
|
for subcls in cls.__subclasses__():
|
|
|
|
_substitute_init_recursively(subcls, func)
|
|
|
|
func(subcls)
|
|
|
|
|
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
class InsertPostInitMethodToModuleSubClasses(object):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
r"""
|
|
|
|
Enter the context scope.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def preprocess_after(f):
|
|
|
|
|
|
|
|
@functools.wraps(f)
|
|
|
|
def wrapper(module: torch.nn.Module, *args, **kwargs):
|
|
|
|
f(module, *args, **kwargs)
|
|
|
|
self._post_init_method(module)
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
def _enable_class(cls):
|
|
|
|
cls._old_init = cls.__init__
|
|
|
|
cls.__init__ = preprocess_after(cls.__init__)
|
|
|
|
|
|
|
|
# The function is called during init subclass.
|
|
|
|
def _init_subclass(cls, **kwargs):
|
|
|
|
cls.__init__ = preprocess_after(cls.__init__)
|
|
|
|
|
|
|
|
# Replace .__init__() for all existing subclasses of torch.nn.Module
|
|
|
|
# Excution self._post_init_method after the default init function.
|
2022-03-28 09:42:18 +00:00
|
|
|
_substitute_init_recursively(torch.nn.modules.module.Module, _enable_class)
|
2022-03-07 08:14:40 +00:00
|
|
|
|
|
|
|
# holding on to the current __init__subclass__ for exit
|
|
|
|
torch.nn.modules.module.Module._old_init_subclass = (torch.nn.modules.module.Module.__init_subclass__)
|
|
|
|
# Replace .__init__() for future subclasses of torch.nn.Module
|
|
|
|
torch.nn.modules.module.Module.__init_subclass__ = classmethod(_init_subclass)
|
|
|
|
|
|
|
|
self._pre_context_exec()
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
|
|
|
|
def _disable_class(cls):
|
|
|
|
cls.__init__ = cls._old_init
|
|
|
|
|
|
|
|
# Replace .__init__() for all existing subclasses of torch.nn.Module
|
2022-03-28 09:42:18 +00:00
|
|
|
_substitute_init_recursively(torch.nn.modules.module.Module, _disable_class)
|
2022-03-07 08:14:40 +00:00
|
|
|
|
|
|
|
# Replace .__init__() for future subclasses of torch.nn.Module
|
|
|
|
torch.nn.modules.module.Module.__init_subclass__ = (torch.nn.modules.module.Module._old_init_subclass)
|
|
|
|
|
|
|
|
self._post_context_exec()
|
|
|
|
# Now that we cleaned up the metaclass injection, raise the exception.
|
|
|
|
if exc_type is not None:
|
|
|
|
return False
|
|
|
|
|
|
|
|
# To be implemented by inheriting classes
|
|
|
|
def _post_init_method(self, module):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _pre_context_exec(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _post_context_exec(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2022-03-29 09:57:59 +00:00
|
|
|
class ZeroContextConfig(object):
|
|
|
|
"""The configuration used to control zero context initialization.
|
|
|
|
|
|
|
|
Args:
|
2022-04-01 12:10:47 +00:00
|
|
|
target_device (torch.device): The device where param data are after exiting the context.
|
2022-04-02 10:30:06 +00:00
|
|
|
replicated (bool, optional): Whether the param is replicated across data parallel group.
|
2022-03-31 10:34:11 +00:00
|
|
|
Some parameters are not replicated, e.g. parameters in MOE experts.
|
2022-03-29 09:57:59 +00:00
|
|
|
shard_param (bool, optional): Is param sharded after exiting the context. Defaults to False.
|
|
|
|
rm_torch_payload_on_the_fly (bool, optional): If set to `True`, remove tensor payload on `param.data` after module init finished.
|
|
|
|
This will reduce memory usage when initializing model.
|
|
|
|
But it's not suitable for all models, especially when there are `weight init` operations in `__init__`.
|
|
|
|
If set to `False`, remove tensor payload on param.data afther the context exist.
|
|
|
|
This is used when you add some logic to operate tensors in __init__ of module.
|
|
|
|
See torchvision resnet18. Defaults to False.
|
|
|
|
"""
|
|
|
|
|
2022-04-01 12:10:47 +00:00
|
|
|
def __init__(self,
|
|
|
|
target_device: torch.device,
|
|
|
|
replicated: bool = True,
|
|
|
|
shard_param: bool = False,
|
|
|
|
rm_torch_payload_on_the_fly: bool = False):
|
2022-03-29 09:57:59 +00:00
|
|
|
super().__init__()
|
2022-04-01 12:10:47 +00:00
|
|
|
self.target_device = target_device
|
2022-03-31 10:34:11 +00:00
|
|
|
self.is_replicated: bool = replicated
|
2022-03-29 09:57:59 +00:00
|
|
|
self.shard_param: bool = shard_param
|
|
|
|
self.rm_torch_payload_on_the_fly: bool = rm_torch_payload_on_the_fly
|
|
|
|
|
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
class ZeroInitContext(InsertPostInitMethodToModuleSubClasses):
|
2022-03-24 15:44:00 +00:00
|
|
|
"""A context to initialize model.
|
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
1. Convert the model to fp16.
|
2022-04-02 10:30:06 +00:00
|
|
|
2. The paramaters of the module are adapted to type ShardedParameter.
|
|
|
|
3. Shard the param and grad according to flags.
|
2022-03-10 06:08:58 +00:00
|
|
|
|
2022-03-24 15:44:00 +00:00
|
|
|
Args:
|
2022-04-01 12:10:47 +00:00
|
|
|
target_device (torch.device): The device where param data are after exiting the context.
|
2022-03-24 15:44:00 +00:00
|
|
|
shard_strategy (BaseShardStrategy): Shard strategy instance.
|
|
|
|
shard_param (bool, optional): Is param sharded after exiting the context. Defaults to False.
|
|
|
|
rm_torch_payload_on_the_fly (bool, optional): If set to `True`, remove tensor payload on `param.data` after module init finished.
|
|
|
|
This will reduce memory usage when initializing model.
|
|
|
|
But it's not suitable for all models, especially when there are `weight init` operations in `__init__`.
|
|
|
|
If set to `False`, remove tensor payload on param.data afther the context exist.
|
2022-03-10 03:20:04 +00:00
|
|
|
This is used when you add some logic to operate tensors in __init__ of module.
|
2022-03-24 15:44:00 +00:00
|
|
|
See torchvision resnet18. Defaults to False.
|
|
|
|
model_numel_tensor (torch.Tensor, optional): A tensor which will store the number of elements of model. Defaults to torch.zeros(1, dtype=torch.int).
|
|
|
|
dp_process_group (Optional[ProcessGroup], optional): Data parallel process group. Defaults to None.
|
2022-03-07 08:14:40 +00:00
|
|
|
"""
|
|
|
|
|
2022-03-08 06:45:01 +00:00
|
|
|
def __init__(self,
|
2022-03-10 06:08:58 +00:00
|
|
|
target_device: torch.device,
|
2022-03-08 06:45:01 +00:00
|
|
|
shard_strategy: BaseShardStrategy,
|
|
|
|
shard_param: bool = False,
|
2022-03-21 03:18:55 +00:00
|
|
|
rm_torch_payload_on_the_fly: bool = False,
|
2022-03-29 01:09:04 +00:00
|
|
|
model_numel_tensor: torch.Tensor = torch.zeros(1, dtype=torch.long),
|
2022-03-21 03:18:55 +00:00
|
|
|
dp_process_group: Optional[ProcessGroup] = None):
|
2022-03-24 15:44:00 +00:00
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
super().__init__()
|
|
|
|
self.shard_strategy = shard_strategy
|
2022-04-02 10:30:06 +00:00
|
|
|
self.initialized_param_list = []
|
2022-03-10 08:31:02 +00:00
|
|
|
self.model_numel_tensor = model_numel_tensor
|
2022-03-21 03:18:55 +00:00
|
|
|
self.dp_process_group = dp_process_group or gpc.get_group(ParallelMode.DATA)
|
2022-03-07 08:14:40 +00:00
|
|
|
|
2022-04-01 12:10:47 +00:00
|
|
|
self.config = ZeroContextConfig(target_device=target_device,
|
|
|
|
replicated=True,
|
2022-03-31 10:34:11 +00:00
|
|
|
shard_param=shard_param,
|
2022-03-29 09:57:59 +00:00
|
|
|
rm_torch_payload_on_the_fly=rm_torch_payload_on_the_fly)
|
2022-04-01 12:10:47 +00:00
|
|
|
|
2022-03-29 09:57:59 +00:00
|
|
|
ZeroContextMgr().current_context = self
|
|
|
|
|
2022-04-01 12:10:47 +00:00
|
|
|
@property
|
|
|
|
def target_device(self):
|
|
|
|
return self.config.target_device
|
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
@property
|
|
|
|
def is_replicated(self):
|
|
|
|
return self.config.is_replicated
|
|
|
|
|
2022-03-29 09:57:59 +00:00
|
|
|
@property
|
|
|
|
def shard_param(self):
|
|
|
|
return self.config.shard_param
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rm_torch_payload_on_the_fly(self):
|
|
|
|
return self.config.rm_torch_payload_on_the_fly
|
|
|
|
|
2022-03-25 03:23:35 +00:00
|
|
|
def _pre_context_exec(self):
|
|
|
|
"""
|
|
|
|
The Callback function when entering the context
|
|
|
|
"""
|
|
|
|
self.logger = get_dist_logger("ZeroInitContext")
|
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
def _post_context_exec(self):
|
2022-03-25 03:23:35 +00:00
|
|
|
"""The callback function when exiting context.
|
2022-03-07 08:14:40 +00:00
|
|
|
"""
|
2022-03-08 06:45:01 +00:00
|
|
|
if not self.rm_torch_payload_on_the_fly:
|
2022-04-02 10:30:06 +00:00
|
|
|
for param in self.initialized_param_list:
|
2022-03-31 04:25:45 +00:00
|
|
|
assert hasattr(param, 'colo_attr')
|
|
|
|
param.colo_attr.remove_torch_payload()
|
2022-03-08 06:45:01 +00:00
|
|
|
|
2022-04-02 10:30:06 +00:00
|
|
|
del self.initialized_param_list
|
2022-03-07 08:14:40 +00:00
|
|
|
|
2022-03-25 03:23:35 +00:00
|
|
|
def _post_init_method(self, module: torch.nn.Module):
|
|
|
|
"""
|
|
|
|
The function to call at the end of the constructor of each module.
|
|
|
|
NOTE() The module may be passed to this function multiple times.
|
2022-03-07 08:14:40 +00:00
|
|
|
"""
|
2022-04-02 10:30:06 +00:00
|
|
|
|
|
|
|
def half_fn(t: torch.Tensor):
|
|
|
|
return t.half() if t.is_floating_point() else t
|
|
|
|
|
2022-03-28 09:42:18 +00:00
|
|
|
for param in module.parameters(recurse=False):
|
2022-03-07 08:14:40 +00:00
|
|
|
# avoid adapting a param to ShardedParam twice
|
2022-03-31 04:25:45 +00:00
|
|
|
if hasattr(param, 'colo_attr'):
|
2022-03-07 08:14:40 +00:00
|
|
|
continue
|
|
|
|
|
2022-03-10 08:31:02 +00:00
|
|
|
self.model_numel_tensor += param.numel()
|
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
# mark whether the param is replicated
|
|
|
|
param.is_replicated = self.is_replicated
|
|
|
|
|
2022-03-29 09:57:59 +00:00
|
|
|
# convert parameters to half
|
2022-04-02 10:30:06 +00:00
|
|
|
param_half = half_fn(param)
|
2022-03-29 09:57:59 +00:00
|
|
|
param.data = param_half
|
2022-03-29 01:09:04 +00:00
|
|
|
if param.grad is not None:
|
2022-04-02 10:30:06 +00:00
|
|
|
grad_half = half_fn(param.grad)
|
2022-03-29 09:57:59 +00:00
|
|
|
param.grad.data = grad_half
|
2022-03-07 08:14:40 +00:00
|
|
|
|
2022-03-10 06:08:58 +00:00
|
|
|
# move torch parameters to the target device
|
2022-03-29 09:57:59 +00:00
|
|
|
target_device = self.target_device
|
2022-03-10 06:08:58 +00:00
|
|
|
param.data = param.data.to(target_device)
|
|
|
|
if param.grad is not None:
|
|
|
|
param.grad = param.grad.to(target_device)
|
|
|
|
|
2022-03-31 04:25:45 +00:00
|
|
|
param.colo_attr = ShardedParamV2(param, rm_torch_payload=self.rm_torch_payload_on_the_fly)
|
2022-03-08 06:45:01 +00:00
|
|
|
|
2022-03-07 08:14:40 +00:00
|
|
|
if self.shard_param:
|
2022-03-31 04:25:45 +00:00
|
|
|
self.shard_strategy.shard([param.colo_attr.sharded_data_tensor], self.dp_process_group)
|
2022-04-02 10:30:06 +00:00
|
|
|
self.initialized_param_list.append(param)
|
2022-03-25 10:03:32 +00:00
|
|
|
|
2022-03-18 07:44:47 +00:00
|
|
|
# We must cast buffers
|
|
|
|
# If we use BN, buffers may be on CPU and Float
|
|
|
|
# We must cast them
|
2022-03-28 09:42:18 +00:00
|
|
|
for buffer in module.buffers(recurse=False):
|
2022-03-18 07:44:47 +00:00
|
|
|
buffer.data = buffer.data.to(device=torch.cuda.current_device())
|
2022-03-29 01:09:04 +00:00
|
|
|
buffer.data = cast_tensor_to_fp16(buffer.data)
|
2022-03-29 09:57:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ZeroContextMgr(metaclass=SingletonMeta):
|
|
|
|
current_context: Optional[ZeroInitContext] = None
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def hijack_context_config(self, **kwargs):
|
|
|
|
if self.current_context is None:
|
|
|
|
yield
|
|
|
|
else:
|
|
|
|
old_config = self.current_context.config
|
|
|
|
self.current_context.config = ZeroContextConfig(**kwargs)
|
|
|
|
yield
|
|
|
|
self.current_context.config = old_config
|
|
|
|
|
|
|
|
|
2022-04-01 12:10:47 +00:00
|
|
|
def no_shard_zero_context(is_replicated: bool = True) -> AbstractContextManager:
|
|
|
|
return ZeroContextMgr().hijack_context_config(target_device=torch.device('cuda', torch.cuda.current_device()),
|
|
|
|
replicated=is_replicated,
|
2022-03-31 10:34:11 +00:00
|
|
|
shard_param=False,
|
|
|
|
rm_torch_payload_on_the_fly=False)
|
|
|
|
|
|
|
|
|
|
|
|
def no_shard_zero_decrator(is_replicated: bool = True):
|
2022-03-29 09:57:59 +00:00
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
def _wrapper(init_func):
|
2022-03-29 09:57:59 +00:00
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
def _no_shard(*args, **kwargs):
|
|
|
|
with no_shard_zero_context(is_replicated):
|
|
|
|
init_func(*args, **kwargs)
|
2022-03-29 09:57:59 +00:00
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
return _no_shard
|
2022-03-29 09:57:59 +00:00
|
|
|
|
2022-03-31 10:34:11 +00:00
|
|
|
return _wrapper
|