2021-10-28 16:21:23 +00:00
|
|
|
import math
|
2022-04-01 08:52:47 +00:00
|
|
|
from collections import OrderedDict
|
2021-12-27 07:04:32 +00:00
|
|
|
from typing import Callable
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
2021-12-27 07:04:32 +00:00
|
|
|
import torch.nn.functional as F
|
2022-11-14 09:34:03 +00:00
|
|
|
from torch import Tensor
|
|
|
|
from torch.nn import Parameter
|
|
|
|
|
2023-09-11 08:24:28 +00:00
|
|
|
from colossalai.legacy.communication import all_reduce, broadcast
|
2023-09-18 08:31:06 +00:00
|
|
|
from colossalai.legacy.constants import (
|
|
|
|
INPUT_GROUP_3D,
|
|
|
|
INPUT_X_WEIGHT_3D,
|
|
|
|
OUTPUT_GROUP_3D,
|
|
|
|
OUTPUT_X_WEIGHT_3D,
|
|
|
|
WEIGHT_GROUP_3D,
|
|
|
|
)
|
|
|
|
from colossalai.legacy.context import ParallelMode, seed
|
|
|
|
from colossalai.legacy.core import global_context as gpc
|
|
|
|
from colossalai.legacy.global_variables import tensor_parallel_env as env
|
2023-09-11 08:24:28 +00:00
|
|
|
from colossalai.legacy.nn.layer.base_layer import ParallelLayer
|
2023-09-04 11:56:42 +00:00
|
|
|
from colossalai.legacy.registry import LAYERS
|
2023-09-18 08:31:06 +00:00
|
|
|
from colossalai.legacy.utils.checkpointing import (
|
2022-11-14 09:34:03 +00:00
|
|
|
broadcast_state_dict,
|
|
|
|
gather_tensor_parallel_state_dict,
|
|
|
|
partition_tensor_parallel_state_dict,
|
|
|
|
)
|
2023-09-18 08:31:06 +00:00
|
|
|
from colossalai.nn import init as init
|
2023-11-20 08:12:41 +00:00
|
|
|
from colossalai.utils.device import get_current_device
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2021-12-29 15:32:10 +00:00
|
|
|
from ..utils import divide, set_tensor_parallel_attribute_by_partition, to_2tuple
|
2022-11-14 09:34:03 +00:00
|
|
|
from ._operation import (
|
|
|
|
all_gather_tensor_3d,
|
|
|
|
classifier_3d,
|
|
|
|
layernorm_3d,
|
|
|
|
linear_3d,
|
|
|
|
reduce_scatter_tensor_3d,
|
|
|
|
split_batch_3d,
|
|
|
|
split_tensor_3d,
|
|
|
|
vocab_parallel_classifier_3d,
|
|
|
|
)
|
|
|
|
from ._utils import get_depth_from_env, get_parallel_mode_from_env, register_async_grad_hook, swap_in_out_group
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
2021-12-27 07:04:32 +00:00
|
|
|
class LayerNorm3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Layer Normalization for 3D parallelism.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
normalized_shape (int): input shape from an expected input of size.
|
|
|
|
:math:`[* \times \text{normalized_shape}[0] \times \text{normalized_shape}[1]
|
|
|
|
\times \ldots \times \text{normalized_shape}[-1]]`
|
|
|
|
If a single integer is used, it is treated as a singleton list, and this module will
|
|
|
|
normalize over the last dimension which is expected to be of that specific size.
|
|
|
|
eps (float, optional): a value added to the denominator for numerical stability, defaults to 1e-12.
|
2022-04-14 03:43:56 +00:00
|
|
|
bias (bool, optional): Whether to add a bias, defaults to ``True``.
|
2022-03-25 05:02:39 +00:00
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2022-04-14 03:43:56 +00:00
|
|
|
def __init__(self, normalized_shape: int, eps: float = 1e-12, bias=True, dtype=None):
|
2021-10-28 16:21:23 +00:00
|
|
|
super().__init__()
|
Develop/experiments (#59)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
* Split conv2d, class token, positional embedding in 2d, Fix random number in ddp
Fix convergence in cifar10, Imagenet1000
* Integrate 1d tensor parallel in Colossal-AI (#39)
* fixed 1D and 2D convergence (#38)
* optimized 2D operations
* fixed 1D ViT convergence problem
* Feature/ddp (#49)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* support torch ddp
* fix loss accumulation
* add log for ddp
* change seed
* modify timing hook
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* Feature/pipeline (#40)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* optimize communication of pipeline parallel
* fix grad clip for pipeline
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* optimized 3d layer to fix slow computation ; tested imagenet performance with 3d; reworked lr_scheduler config definition; fixed launch args; fixed some printing issues; simplified apis of 3d layers (#51)
* Update 2.5d layer code to get a similar accuracy on imagenet-1k dataset
* update api for better usability (#58)
update api for better usability
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
Co-authored-by: puck_WCR <46049915+WANG-CR@users.noreply.github.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
Co-authored-by: アマデウス <kurisusnowdeng@users.noreply.github.com>
Co-authored-by: BoxiangW <45734921+BoxiangW@users.noreply.github.com>
2021-12-09 07:08:29 +00:00
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
|
|
|
self.input_x_weight_parallel_mode = get_parallel_mode_from_env(INPUT_X_WEIGHT_3D)
|
2021-10-28 16:21:23 +00:00
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.normalized_shape = normalized_shape
|
Develop/experiments (#59)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
* Split conv2d, class token, positional embedding in 2d, Fix random number in ddp
Fix convergence in cifar10, Imagenet1000
* Integrate 1d tensor parallel in Colossal-AI (#39)
* fixed 1D and 2D convergence (#38)
* optimized 2D operations
* fixed 1D ViT convergence problem
* Feature/ddp (#49)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* support torch ddp
* fix loss accumulation
* add log for ddp
* change seed
* modify timing hook
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* Feature/pipeline (#40)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* optimize communication of pipeline parallel
* fix grad clip for pipeline
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* optimized 3d layer to fix slow computation ; tested imagenet performance with 3d; reworked lr_scheduler config definition; fixed launch args; fixed some printing issues; simplified apis of 3d layers (#51)
* Update 2.5d layer code to get a similar accuracy on imagenet-1k dataset
* update api for better usability (#58)
update api for better usability
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
Co-authored-by: puck_WCR <46049915+WANG-CR@users.noreply.github.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
Co-authored-by: アマデウス <kurisusnowdeng@users.noreply.github.com>
Co-authored-by: BoxiangW <45734921+BoxiangW@users.noreply.github.com>
2021-12-09 07:08:29 +00:00
|
|
|
self.normalized_shape_per_partition = divide(normalized_shape, self.depth)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
self.weight = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.ones(self.normalized_shape_per_partition, device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2022-04-14 03:43:56 +00:00
|
|
|
if bias:
|
2022-05-16 02:18:49 +00:00
|
|
|
self.bias = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros(self.normalized_shape_per_partition, device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2022-04-14 03:43:56 +00:00
|
|
|
else:
|
|
|
|
self.bias = None
|
2021-10-28 16:21:23 +00:00
|
|
|
self.variance_epsilon = eps
|
2022-10-26 12:54:39 +00:00
|
|
|
self.reset_parameters()
|
2021-10-28 16:21:23 +00:00
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth)
|
2022-04-14 03:43:56 +00:00
|
|
|
if self.bias is not None:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.bias, self.depth)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def reset_parameters(self) -> None:
|
|
|
|
init.ones_()(self.weight)
|
2022-10-26 12:54:39 +00:00
|
|
|
register_async_grad_hook(self.weight)
|
2022-04-14 03:43:56 +00:00
|
|
|
if self.bias is not None:
|
|
|
|
init.zeros_()(self.bias)
|
2022-10-26 12:54:39 +00:00
|
|
|
register_async_grad_hook(self.bias)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight.transpose(0, 1)
|
|
|
|
# bias
|
|
|
|
bias = state_dict.pop(bias_key, None)
|
|
|
|
if bias is not None:
|
|
|
|
local_state[bias_key] = bias
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
2022-04-01 08:52:47 +00:00
|
|
|
partition_states={
|
|
|
|
weight_key: True,
|
|
|
|
bias_key: True,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
# broadcast in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = broadcast_state_dict(local_state, self.input_parallel_mode)
|
|
|
|
# broadcast in weight groups
|
|
|
|
local_state = broadcast_state_dict(local_state, self.weight_parallel_mode)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-14 03:43:56 +00:00
|
|
|
local_state = OrderedDict({weight_key: self.weight})
|
|
|
|
if self.bias is not None:
|
|
|
|
local_state[bias_key] = self.bias
|
2022-04-01 08:52:47 +00:00
|
|
|
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2021-10-28 16:21:23 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2022-10-26 12:54:39 +00:00
|
|
|
return layernorm_3d(
|
|
|
|
input_,
|
|
|
|
self.weight,
|
|
|
|
self.bias,
|
|
|
|
self.normalized_shape,
|
|
|
|
self.variance_epsilon,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
self.input_x_weight_parallel_mode,
|
|
|
|
)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
2021-12-27 07:04:32 +00:00
|
|
|
class Linear3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Linear layer for 3D parallelism.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
in_features (int): size of each input sample.
|
|
|
|
out_features (int): size of each output sample.
|
|
|
|
bias (bool, optional): If set to ``False``, the layer will not learn an additive bias, defaults to ``True``.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of weight, defaults to kaiming uniform initializer.
|
|
|
|
bias_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of bias, defaults to xavier uniform initializer.
|
|
|
|
|
|
|
|
More details about ``initializer`` please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_.
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
in_features: int,
|
|
|
|
out_features: int,
|
|
|
|
bias: bool = True,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
skip_bias_add: bool = False,
|
|
|
|
weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)),
|
|
|
|
bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1),
|
|
|
|
):
|
2021-10-28 16:21:23 +00:00
|
|
|
super().__init__()
|
|
|
|
self.in_features = in_features
|
|
|
|
self.out_features = out_features
|
Develop/experiments (#59)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
* Split conv2d, class token, positional embedding in 2d, Fix random number in ddp
Fix convergence in cifar10, Imagenet1000
* Integrate 1d tensor parallel in Colossal-AI (#39)
* fixed 1D and 2D convergence (#38)
* optimized 2D operations
* fixed 1D ViT convergence problem
* Feature/ddp (#49)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* support torch ddp
* fix loss accumulation
* add log for ddp
* change seed
* modify timing hook
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* Feature/pipeline (#40)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* optimize communication of pipeline parallel
* fix grad clip for pipeline
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* optimized 3d layer to fix slow computation ; tested imagenet performance with 3d; reworked lr_scheduler config definition; fixed launch args; fixed some printing issues; simplified apis of 3d layers (#51)
* Update 2.5d layer code to get a similar accuracy on imagenet-1k dataset
* update api for better usability (#58)
update api for better usability
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
Co-authored-by: puck_WCR <46049915+WANG-CR@users.noreply.github.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
Co-authored-by: アマデウス <kurisusnowdeng@users.noreply.github.com>
Co-authored-by: BoxiangW <45734921+BoxiangW@users.noreply.github.com>
2021-12-09 07:08:29 +00:00
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
|
|
|
self.output_x_weight_parallel_mode = get_parallel_mode_from_env(OUTPUT_X_WEIGHT_3D)
|
2021-10-28 16:21:23 +00:00
|
|
|
self.depth = get_depth_from_env()
|
2022-10-26 12:54:39 +00:00
|
|
|
self.skip_bias_add = skip_bias_add
|
2023-01-03 07:26:47 +00:00
|
|
|
self.in_features_per_partition = divide(in_features, self.depth**2)
|
|
|
|
self.out_features_per_partition = divide(out_features, self.depth)
|
2022-02-17 14:03:39 +00:00
|
|
|
self.bias_features_per_partition = divide(out_features, self.depth)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
self.weight = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty(
|
|
|
|
self.in_features_per_partition,
|
|
|
|
self.out_features_per_partition,
|
|
|
|
device=get_current_device(),
|
|
|
|
dtype=dtype,
|
|
|
|
)
|
|
|
|
)
|
2021-10-28 16:21:23 +00:00
|
|
|
if bias:
|
2022-02-17 14:03:39 +00:00
|
|
|
self.bias = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros(self.bias_features_per_partition, device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2021-10-28 16:21:23 +00:00
|
|
|
else:
|
2021-12-27 07:04:32 +00:00
|
|
|
self.bias = None
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
self.reset_parameters(weight_initializer, bias_initializer)
|
2021-10-28 16:21:23 +00:00
|
|
|
self._set_tensor_parallel_attributes()
|
Develop/experiments (#59)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
* Split conv2d, class token, positional embedding in 2d, Fix random number in ddp
Fix convergence in cifar10, Imagenet1000
* Integrate 1d tensor parallel in Colossal-AI (#39)
* fixed 1D and 2D convergence (#38)
* optimized 2D operations
* fixed 1D ViT convergence problem
* Feature/ddp (#49)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* support torch ddp
* fix loss accumulation
* add log for ddp
* change seed
* modify timing hook
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* Feature/pipeline (#40)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* optimize communication of pipeline parallel
* fix grad clip for pipeline
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* optimized 3d layer to fix slow computation ; tested imagenet performance with 3d; reworked lr_scheduler config definition; fixed launch args; fixed some printing issues; simplified apis of 3d layers (#51)
* Update 2.5d layer code to get a similar accuracy on imagenet-1k dataset
* update api for better usability (#58)
update api for better usability
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
Co-authored-by: puck_WCR <46049915+WANG-CR@users.noreply.github.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
Co-authored-by: アマデウス <kurisusnowdeng@users.noreply.github.com>
Co-authored-by: BoxiangW <45734921+BoxiangW@users.noreply.github.com>
2021-12-09 07:08:29 +00:00
|
|
|
swap_in_out_group()
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
2022-02-17 14:03:39 +00:00
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3)
|
2021-10-28 16:21:23 +00:00
|
|
|
if self.bias is not None:
|
2021-12-27 07:04:32 +00:00
|
|
|
set_tensor_parallel_attribute_by_partition(self.bias, self.depth)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2022-10-26 12:54:39 +00:00
|
|
|
def _sync_grad_hook(self, grad) -> Tensor:
|
|
|
|
grad = all_reduce(grad.clone(), self.output_x_weight_parallel_mode)
|
|
|
|
return grad
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def reset_parameters(self, weight_initializer, bias_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, fan_out = self.in_features, self.out_features
|
|
|
|
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
2022-10-26 12:54:39 +00:00
|
|
|
register_async_grad_hook(self.weight)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
if self.bias is not None:
|
|
|
|
bias_initializer(self.bias, fan_in=fan_in)
|
2023-09-19 06:20:26 +00:00
|
|
|
broadcast(
|
|
|
|
self.bias,
|
|
|
|
gpc.get_ranks_in_group(self.output_x_weight_parallel_mode)[0],
|
|
|
|
self.output_x_weight_parallel_mode,
|
|
|
|
)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.bias.register_hook(self._sync_grad_hook)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight.transpose(0, 1)
|
|
|
|
# bias
|
|
|
|
if self.bias is not None:
|
|
|
|
bias = state_dict.pop(bias_key, None)
|
|
|
|
if bias is not None:
|
|
|
|
local_state[bias_key] = bias
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# partition in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# partition in weight groups
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict({weight_key: self.weight})
|
|
|
|
if self.bias is not None:
|
|
|
|
local_state[bias_key] = self.bias
|
|
|
|
|
|
|
|
# gather in weight groups
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
local_state[weight_key] = local_state[weight_key].transpose(0, 1)
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2021-10-28 16:21:23 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2022-10-26 12:54:39 +00:00
|
|
|
output = linear_3d(
|
|
|
|
input_,
|
|
|
|
self.weight,
|
|
|
|
self.input_parallel_mode,
|
|
|
|
self.weight_parallel_mode,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
)
|
|
|
|
|
|
|
|
if not self.skip_bias_add:
|
|
|
|
if self.bias is not None:
|
|
|
|
output = output + self.bias
|
|
|
|
return output
|
|
|
|
else:
|
|
|
|
return output, self.bias
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
@LAYERS.register_module
|
|
|
|
class Classifier3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Classifier for 3D parallelism.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
in_features (int): size of each input sample.
|
|
|
|
num_classes (int): number of classes.
|
|
|
|
weight (:class:`torch.nn.Parameter`, optional): weight of the classifier, defaults to None.
|
|
|
|
bias (bool, optional): If set to ``False``, the layer will not learn an additive bias, defaults to ``True``.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of weight, defaults to kaiming uniform initializer.
|
|
|
|
bias_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of bias, defaults to xavier uniform initializer.
|
|
|
|
|
|
|
|
More details about ``initializer`` please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_.
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
in_features: int,
|
|
|
|
num_classes: int,
|
|
|
|
weight: Parameter = None,
|
|
|
|
bias: bool = True,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)),
|
|
|
|
bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1),
|
|
|
|
):
|
2021-12-27 07:04:32 +00:00
|
|
|
super().__init__()
|
|
|
|
self.in_features = in_features
|
|
|
|
self.num_classes = num_classes
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
2021-12-27 07:04:32 +00:00
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.in_features_per_partition = divide(in_features, self.depth)
|
|
|
|
|
|
|
|
if weight is not None:
|
|
|
|
self.weight = weight
|
|
|
|
self.has_weight = False
|
|
|
|
else:
|
|
|
|
self.weight = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty(self.num_classes, self.in_features_per_partition, device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
self.has_weight = True
|
|
|
|
if bias:
|
|
|
|
self.bias = Parameter(torch.zeros(self.num_classes, device=get_current_device(), dtype=dtype))
|
|
|
|
else:
|
|
|
|
self.bias = None
|
|
|
|
|
|
|
|
self.reset_parameters(weight_initializer, bias_initializer)
|
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
|
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
|
|
|
if self.has_weight:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth)
|
|
|
|
|
|
|
|
def reset_parameters(self, weight_initializer, bias_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, fan_out = self.in_features, self.num_classes
|
|
|
|
|
|
|
|
if self.has_weight:
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
2022-10-26 12:54:39 +00:00
|
|
|
broadcast(self.weight, gpc.get_ranks_in_group(self.weight_parallel_mode)[0], self.weight_parallel_mode)
|
|
|
|
|
|
|
|
register_async_grad_hook(self.weight)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
if self.bias is not None:
|
|
|
|
bias_initializer(self.bias, fan_in=fan_in)
|
2022-10-26 12:54:39 +00:00
|
|
|
broadcast(self.bias, gpc.get_ranks_in_group(ParallelMode.TENSOR)[0], ParallelMode.TENSOR)
|
|
|
|
register_async_grad_hook(self.bias)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
if self.has_weight:
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight
|
|
|
|
# bias
|
|
|
|
if self.bias is not None:
|
|
|
|
bias = state_dict.pop(bias_key, None)
|
|
|
|
if bias is not None:
|
|
|
|
local_state[bias_key] = bias
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# broadcast in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = broadcast_state_dict(local_state, self.input_parallel_mode)
|
|
|
|
# broadcast in weight groups
|
|
|
|
local_state = broadcast_state_dict(local_state, self.weight_parallel_mode)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
|
|
|
if self.has_weight:
|
|
|
|
local_state[weight_key] = self.weight
|
|
|
|
if self.bias is not None:
|
|
|
|
local_state[bias_key] = self.bias
|
|
|
|
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2022-10-26 12:54:39 +00:00
|
|
|
return classifier_3d(
|
|
|
|
input_,
|
|
|
|
self.weight,
|
|
|
|
self.bias,
|
|
|
|
self.input_parallel_mode,
|
|
|
|
self.weight_parallel_mode,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
|
|
|
class VocabParallelClassifier3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Vocab parallel classifier layer for 3D parallelism.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
in_features (int): size of each input sample.
|
|
|
|
num_classes (int): number of classes.
|
|
|
|
weight (:class:`torch.nn.Parameter`, optional): weight of the classifier, defaults to None.
|
|
|
|
bias (bool, optional): If set to ``False``, the layer will not learn an additive bias, defaults to ``True``.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of weight, defaults to kaiming uniform initializer.
|
|
|
|
bias_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of bias, defaults to xavier uniform initializer.
|
|
|
|
|
|
|
|
More details about ``initializer`` please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_.
|
2022-02-14 03:15:02 +00:00
|
|
|
"""
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
in_features: int,
|
|
|
|
num_classes: int,
|
|
|
|
weight: Parameter = None,
|
|
|
|
bias: bool = True,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)),
|
|
|
|
bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1),
|
|
|
|
):
|
2022-02-14 03:15:02 +00:00
|
|
|
super().__init__()
|
|
|
|
self.in_features = in_features
|
|
|
|
self.num_classes = num_classes
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
|
|
|
self.output_x_weight_parallel_mode = get_parallel_mode_from_env(OUTPUT_X_WEIGHT_3D)
|
2022-02-14 03:15:02 +00:00
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.in_features_per_partition = divide(in_features, self.depth)
|
2022-02-17 14:03:39 +00:00
|
|
|
self.out_features_per_partition = divide(num_classes, self.depth**2)
|
|
|
|
self.bias_features_per_partition = divide(num_classes, self.depth)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
if weight is not None:
|
|
|
|
self.weight = weight
|
|
|
|
self.has_weight = False
|
|
|
|
else:
|
|
|
|
self.weight = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty(
|
|
|
|
self.out_features_per_partition,
|
|
|
|
self.in_features_per_partition,
|
|
|
|
device=get_current_device(),
|
|
|
|
dtype=dtype,
|
|
|
|
)
|
|
|
|
)
|
2022-02-14 03:15:02 +00:00
|
|
|
self.has_weight = True
|
|
|
|
if bias:
|
2022-02-17 14:03:39 +00:00
|
|
|
self.bias = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros(self.bias_features_per_partition, device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2022-02-14 03:15:02 +00:00
|
|
|
else:
|
|
|
|
self.bias = None
|
|
|
|
|
|
|
|
self.reset_parameters(weight_initializer, bias_initializer)
|
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
swap_in_out_group()
|
|
|
|
env.vocab_parallel = True
|
|
|
|
|
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
|
|
|
if self.has_weight:
|
2022-04-11 02:17:55 +00:00
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3)
|
2022-02-14 03:15:02 +00:00
|
|
|
if self.bias is not None:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.bias, self.depth)
|
|
|
|
|
|
|
|
def reset_parameters(self, weight_initializer, bias_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, fan_out = self.in_features, self.num_classes
|
|
|
|
|
|
|
|
if self.has_weight:
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
|
|
|
|
2022-10-26 12:54:39 +00:00
|
|
|
register_async_grad_hook(self.weight)
|
|
|
|
|
2022-02-14 03:15:02 +00:00
|
|
|
if self.bias is not None:
|
|
|
|
bias_initializer(self.bias, fan_in=fan_in)
|
2023-09-19 06:20:26 +00:00
|
|
|
broadcast(
|
|
|
|
self.bias,
|
|
|
|
gpc.get_ranks_in_group(self.output_x_weight_parallel_mode)[0],
|
|
|
|
self.output_x_weight_parallel_mode,
|
|
|
|
)
|
2022-10-26 12:54:39 +00:00
|
|
|
register_async_grad_hook(self.bias)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
if self.has_weight:
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight
|
|
|
|
# bias
|
|
|
|
if self.bias is not None:
|
|
|
|
bias = state_dict.pop(bias_key, None)
|
|
|
|
if bias is not None:
|
|
|
|
local_state[bias_key] = bias
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# partition in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# partition in weight groups
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict({weight_key: self.weight})
|
|
|
|
if self.bias is not None:
|
|
|
|
local_state[bias_key] = self.bias
|
|
|
|
|
|
|
|
# gather in weight groups
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: -1, bias_key: 0},
|
|
|
|
partition_states={weight_key: True, bias_key: False},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2022-02-14 03:15:02 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2022-10-26 12:54:39 +00:00
|
|
|
return vocab_parallel_classifier_3d(
|
|
|
|
input_,
|
|
|
|
self.weight,
|
|
|
|
self.bias,
|
|
|
|
self.input_parallel_mode,
|
|
|
|
self.weight_parallel_mode,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
|
|
|
class PatchEmbedding3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""2D Image to Patch Embedding.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
img_size (int): image size.
|
|
|
|
patch_size (int): patch size.
|
|
|
|
in_chans (int): number of channels of input image.
|
|
|
|
embed_size (int): size of embedding.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
flatten (bool, optional): whether to flatten output tensor, defaults to True.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of weight, defaults to kaiming uniform initializer.
|
|
|
|
bias_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of bias, defaults to xavier uniform initializer.
|
|
|
|
position_embed_initializer (:class:`typing.Callable`, optional):
|
|
|
|
The initializer of position embedding, defaults to zeros initializer.
|
|
|
|
|
|
|
|
More details about ``initializer`` please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_.
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
img_size: int,
|
|
|
|
patch_size: int,
|
|
|
|
in_chans: int,
|
|
|
|
embed_size: int,
|
|
|
|
flatten: bool = True,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)),
|
|
|
|
bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1),
|
|
|
|
position_embed_initializer: Callable = init.zeros_(),
|
|
|
|
):
|
2021-12-27 07:04:32 +00:00
|
|
|
super().__init__()
|
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
|
|
|
self.input_x_weight_parallel_mode = get_parallel_mode_from_env(INPUT_X_WEIGHT_3D)
|
|
|
|
img_size = to_2tuple(img_size)
|
|
|
|
patch_size = to_2tuple(patch_size)
|
|
|
|
self.img_size = img_size
|
|
|
|
self.patch_size = patch_size
|
|
|
|
self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
|
|
|
|
self.num_patches = self.grid_size[0] * self.grid_size[1]
|
2021-12-27 07:04:32 +00:00
|
|
|
self.embed_size = embed_size
|
2022-10-26 12:54:39 +00:00
|
|
|
embed_size_per_partition = embed_size // self.depth
|
2021-12-27 07:04:32 +00:00
|
|
|
self.flatten = flatten
|
|
|
|
|
|
|
|
self.weight = nn.Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty(
|
|
|
|
(embed_size_per_partition, in_chans, *self.patch_size), device=get_current_device(), dtype=dtype
|
|
|
|
)
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
self.bias = nn.Parameter(torch.empty(embed_size_per_partition, device=get_current_device(), dtype=dtype))
|
|
|
|
|
|
|
|
self.cls_token = nn.Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros((1, 1, embed_size_per_partition), device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
self.pos_embed = nn.Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.zeros((1, self.num_patches + 1, embed_size_per_partition), device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
self.reset_parameters(weight_initializer, bias_initializer, position_embed_initializer)
|
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
|
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth)
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.bias, self.depth)
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.cls_token, self.depth)
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.pos_embed, self.depth)
|
|
|
|
|
2022-02-14 03:15:02 +00:00
|
|
|
def _sync_grad_hook(self, grad) -> Tensor:
|
2022-10-26 12:54:39 +00:00
|
|
|
grad = all_reduce(grad.clone(), self.input_x_weight_parallel_mode)
|
2021-12-27 07:04:32 +00:00
|
|
|
return grad
|
|
|
|
|
|
|
|
def reset_parameters(self, weight_initializer, bias_initializer, position_embed_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
|
|
|
|
fan_out = self.embed_size
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
|
|
|
bias_initializer(self.bias, fan_in=fan_in)
|
|
|
|
position_embed_initializer(self.pos_embed)
|
|
|
|
|
2022-10-26 12:54:39 +00:00
|
|
|
src_rank = gpc.get_ranks_in_group(self.input_x_weight_parallel_mode)[0]
|
|
|
|
broadcast(self.weight, src_rank, self.input_x_weight_parallel_mode)
|
|
|
|
broadcast(self.bias, src_rank, self.input_x_weight_parallel_mode)
|
|
|
|
broadcast(self.pos_embed, src_rank, self.input_x_weight_parallel_mode)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
2022-02-14 03:15:02 +00:00
|
|
|
self.weight.register_hook(self._sync_grad_hook)
|
2021-12-27 07:04:32 +00:00
|
|
|
self.bias.register_hook(self._sync_grad_hook)
|
|
|
|
self.cls_token.register_hook(self._sync_grad_hook)
|
|
|
|
self.pos_embed.register_hook(self._sync_grad_hook)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
|
|
|
cls_token_key = prefix + "cls_token"
|
|
|
|
pos_embed_key = prefix + "pos_embed"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight
|
|
|
|
# bias
|
|
|
|
bias = state_dict.pop(bias_key, None)
|
|
|
|
if bias is not None:
|
|
|
|
local_state[bias_key] = bias
|
|
|
|
# cls token
|
|
|
|
cls_token = state_dict.pop(cls_token_key, None)
|
|
|
|
if cls_token is not None:
|
|
|
|
local_state[cls_token_key] = cls_token
|
|
|
|
# pos embed
|
|
|
|
pos_embed = state_dict.pop(pos_embed_key, None)
|
|
|
|
if pos_embed is not None:
|
|
|
|
local_state[pos_embed_key] = pos_embed
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0, cls_token_key: -1, pos_embed_key: -1},
|
|
|
|
partition_states={weight_key: True, bias_key: True, cls_token_key: True, pos_embed_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
)
|
|
|
|
# broadcast in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = broadcast_state_dict(local_state, self.input_parallel_mode)
|
|
|
|
# broadcast in weight groups
|
|
|
|
local_state = broadcast_state_dict(local_state, self.weight_parallel_mode)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
|
|
|
bias_key = prefix + "bias"
|
|
|
|
cls_token_key = prefix + "cls_token"
|
|
|
|
pos_embed_key = prefix + "pos_embed"
|
|
|
|
local_state = OrderedDict(
|
|
|
|
{weight_key: self.weight, bias_key: self.bias, cls_token_key: self.cls_token, pos_embed_key: self.pos_embed}
|
|
|
|
)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
2023-09-19 06:20:26 +00:00
|
|
|
dims={weight_key: 0, bias_key: 0, cls_token_key: -1, pos_embed_key: -1},
|
|
|
|
partition_states={weight_key: True, bias_key: True, cls_token_key: True, pos_embed_key: True},
|
2022-04-01 08:52:47 +00:00
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2023-09-19 06:20:26 +00:00
|
|
|
input_ = split_batch_3d(
|
|
|
|
input_, input_parallel_mode=self.input_parallel_mode, weight_parallel_mode=self.weight_parallel_mode
|
|
|
|
)
|
2022-02-14 03:15:02 +00:00
|
|
|
output = F.conv2d(input_, self.weight, self.bias, stride=self.patch_size)
|
2021-12-27 07:04:32 +00:00
|
|
|
if self.flatten:
|
2023-09-19 06:20:26 +00:00
|
|
|
output = output.flatten(2).transpose(1, 2) # BCHW -> BNC
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
cls_token = self.cls_token.expand(output.shape[0], -1, -1)
|
|
|
|
output = torch.cat((cls_token, output), dim=1)
|
|
|
|
output = output + self.pos_embed
|
|
|
|
|
|
|
|
return output
|
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
|
|
|
class Embedding3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Embedding for 3D parallelism.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
num_embeddings (int): number of embeddings.
|
|
|
|
embedding_dim (int): dimension of embedding.
|
|
|
|
padding_idx (int, optional): If specified, the entries at padding_idx do not contribute to the gradient;
|
|
|
|
therefore, the embedding vector at padding_idx is not updated during training,
|
|
|
|
i.e. it remains as a fixed “pad”, defaults to None.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
he initializer of weight, defaults to normal initializer.
|
|
|
|
|
|
|
|
The ``args`` and ``kwargs`` used in :class:``torch.nn.functional.embedding`` should contain:
|
|
|
|
::
|
|
|
|
|
|
|
|
max_norm (float, optional): If given, each embedding vector with norm larger than max_norm is
|
|
|
|
renormalized to have norm max_norm. Note: this will modify weight in-place.
|
|
|
|
norm_type (float, optional): The p of the p-norm to compute for the max_norm option. Default 2.
|
|
|
|
scale_grad_by_freq (bool, optional): If given, this will scale gradients by the inverse
|
|
|
|
of frequency of the words in the mini-batch. Default False.
|
|
|
|
sparse (bool, optional): If True, gradient w.r.t. weight will be a sparse tensor. Default False.
|
|
|
|
|
|
|
|
More details about ``args`` and ``kwargs`` could be found in
|
|
|
|
`Embedding <https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding.html#torch.nn.functional.embedding>`_.
|
|
|
|
|
|
|
|
More details about initializer please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_
|
2022-01-10 10:05:58 +00:00
|
|
|
"""
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
num_embeddings: int,
|
|
|
|
embedding_dim: int,
|
|
|
|
padding_idx: int = None,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
weight_initializer: Callable = init.normal_(),
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2021-12-27 07:04:32 +00:00
|
|
|
super().__init__()
|
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
|
|
|
self.input_x_weight_parallel_mode = get_parallel_mode_from_env(INPUT_X_WEIGHT_3D)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
self.num_embeddings = num_embeddings
|
|
|
|
self.embed_dim = embedding_dim
|
|
|
|
embed_dim_per_partition = divide(embedding_dim, self.depth)
|
|
|
|
self.padding_idx = padding_idx
|
|
|
|
self.embed_args = args
|
|
|
|
self.embed_kwargs = kwargs
|
|
|
|
|
|
|
|
self.weight = nn.Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty((num_embeddings, embed_dim_per_partition), device=get_current_device(), dtype=dtype)
|
|
|
|
)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
self.reset_parameters(weight_initializer)
|
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
|
|
|
|
def _set_tensor_parallel_attributes(self) -> None:
|
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth)
|
|
|
|
|
2022-10-26 12:54:39 +00:00
|
|
|
def _sync_grad_hook(self, grad) -> Tensor:
|
|
|
|
grad = all_reduce(grad.clone(), self.input_x_weight_parallel_mode)
|
|
|
|
return grad
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def reset_parameters(self, weight_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, fan_out = self.num_embeddings, self.embed_dim
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
|
|
|
self._fill_padding_idx_with_zero()
|
2023-09-19 06:20:26 +00:00
|
|
|
broadcast(
|
|
|
|
self.weight, gpc.get_ranks_in_group(self.input_x_weight_parallel_mode)[0], self.input_x_weight_parallel_mode
|
|
|
|
)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.weight.register_hook(self._sync_grad_hook)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
def _fill_padding_idx_with_zero(self) -> None:
|
|
|
|
if self.padding_idx is not None:
|
|
|
|
with torch.no_grad():
|
|
|
|
self.weight[self.padding_idx].fill_(0)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
)
|
|
|
|
# broadcast in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = broadcast_state_dict(local_state, self.input_parallel_mode)
|
|
|
|
# broadcast in weight groups
|
|
|
|
local_state = broadcast_state_dict(local_state, self.weight_parallel_mode)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict({weight_key: self.weight})
|
|
|
|
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2021-12-27 07:04:32 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
2023-09-19 06:20:26 +00:00
|
|
|
input_ = split_batch_3d(
|
|
|
|
input_, input_parallel_mode=self.input_parallel_mode, weight_parallel_mode=self.weight_parallel_mode
|
|
|
|
)
|
2022-10-26 12:54:39 +00:00
|
|
|
output = F.embedding(input_, self.weight, self.padding_idx, *self.embed_args, **self.embed_kwargs)
|
2021-12-27 07:04:32 +00:00
|
|
|
|
|
|
|
return output
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
@LAYERS.register_module
|
2022-09-06 12:18:35 +00:00
|
|
|
class VocabParallelEmbedding3D(ParallelLayer):
|
2022-03-25 05:02:39 +00:00
|
|
|
r"""Embedding parallelized in the vocabulary dimension.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
num_embeddings (int): number of embeddings.
|
|
|
|
embedding_dim (int): dimension of embedding.
|
|
|
|
padding_idx (int, optional): If specified, the entries at padding_idx do not contribute to the gradient;
|
|
|
|
therefore, the embedding vector at padding_idx is not updated during training,
|
|
|
|
i.e. it remains as a fixed “pad”, defaults to None.
|
|
|
|
dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
|
|
|
|
weight_initializer (:class:`typing.Callable`, optional):
|
|
|
|
he initializer of weight, defaults to normal initializer.
|
|
|
|
|
|
|
|
The ``args`` and ``kwargs`` used in :class:``torch.nn.functional.embedding`` should contain:
|
|
|
|
::
|
|
|
|
|
|
|
|
max_norm (float, optional): If given, each embedding vector with norm larger than max_norm is
|
|
|
|
renormalized to have norm max_norm. Note: this will modify weight in-place.
|
|
|
|
norm_type (float, optional): The p of the p-norm to compute for the max_norm option. Default 2.
|
|
|
|
scale_grad_by_freq (bool, optional): If given, this will scale gradients by the inverse
|
|
|
|
of frequency of the words in the mini-batch. Default False.
|
|
|
|
sparse (bool, optional): If True, gradient w.r.t. weight will be a sparse tensor. Default False.
|
|
|
|
|
|
|
|
More details about ``args`` and ``kwargs`` could be found in
|
|
|
|
`Embedding <https://pytorch.org/docs/stable/generated/torch.nn.functional.embedding.html#torch.nn.functional.embedding>`_.
|
|
|
|
|
|
|
|
More details about initializer please refer to
|
|
|
|
`init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_.
|
2022-02-14 03:15:02 +00:00
|
|
|
"""
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
num_embeddings: int,
|
|
|
|
embedding_dim: int,
|
|
|
|
padding_idx: int = None,
|
|
|
|
dtype: torch.dtype = None,
|
|
|
|
weight_initializer: Callable = init.normal_(),
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2022-02-14 03:15:02 +00:00
|
|
|
super().__init__()
|
|
|
|
self.num_embeddings = num_embeddings
|
|
|
|
self.embed_dim = embedding_dim
|
|
|
|
self.padding_idx = padding_idx
|
|
|
|
self.embed_args = args
|
|
|
|
self.embed_kwargs = kwargs
|
|
|
|
|
|
|
|
self.depth = get_depth_from_env()
|
|
|
|
self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D)
|
|
|
|
self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D)
|
2022-10-26 12:54:39 +00:00
|
|
|
self.output_parallel_mode = get_parallel_mode_from_env(OUTPUT_GROUP_3D)
|
2022-02-17 14:03:39 +00:00
|
|
|
self.num_embeddings_per_partition = divide(self.num_embeddings, self.depth**2)
|
2022-02-14 03:15:02 +00:00
|
|
|
self.embed_dim_per_partition = divide(self.embed_dim, self.depth)
|
|
|
|
vocab_parallel_rank = gpc.get_local_rank(self.input_parallel_mode)
|
2022-02-17 14:03:39 +00:00
|
|
|
self.vocab_start_index = vocab_parallel_rank * self.num_embeddings_per_partition * self.depth
|
|
|
|
self.vocab_end_index = self.vocab_start_index + self.num_embeddings_per_partition * self.depth
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
self.weight = Parameter(
|
2023-09-19 06:20:26 +00:00
|
|
|
torch.empty(
|
|
|
|
(self.num_embeddings_per_partition, self.embed_dim_per_partition),
|
|
|
|
device=get_current_device(),
|
|
|
|
dtype=dtype,
|
|
|
|
)
|
|
|
|
)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
self.reset_parameters(weight_initializer)
|
|
|
|
self._set_tensor_parallel_attributes()
|
|
|
|
env.vocab_parallel = True
|
|
|
|
|
|
|
|
def _set_tensor_parallel_attributes(self):
|
2022-04-11 02:17:55 +00:00
|
|
|
set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
def reset_parameters(self, weight_initializer) -> None:
|
|
|
|
with seed(ParallelMode.TENSOR):
|
|
|
|
fan_in, fan_out = self.num_embeddings, self.embed_dim
|
|
|
|
weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
|
|
|
|
self._fill_padding_idx_with_zero()
|
|
|
|
|
|
|
|
def _fill_padding_idx_with_zero(self) -> None:
|
2023-09-19 06:20:26 +00:00
|
|
|
if (
|
|
|
|
self.padding_idx is not None
|
|
|
|
and self.padding_idx >= self.vocab_start_index
|
|
|
|
and self.padding_idx < self.vocab_end_index
|
|
|
|
):
|
2022-02-14 03:15:02 +00:00
|
|
|
with torch.no_grad():
|
2022-02-17 14:03:39 +00:00
|
|
|
self.weight[self.padding_idx - self.vocab_start_index].fill_(0)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict()
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
2022-04-01 08:52:47 +00:00
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
# weight
|
|
|
|
weight = state_dict.pop(weight_key, None)
|
|
|
|
if weight is not None:
|
|
|
|
local_state[weight_key] = weight
|
|
|
|
|
|
|
|
# partition in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
dims={weight_key: -1},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
)
|
|
|
|
# partition in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
)
|
|
|
|
# partition in weight groups
|
|
|
|
local_state = partition_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
)
|
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
|
2022-04-01 08:52:47 +00:00
|
|
|
|
2022-09-06 12:18:35 +00:00
|
|
|
def _save_to_global_state_dict(self, destination, prefix, keep_vars):
|
2023-09-19 06:20:26 +00:00
|
|
|
weight_key = prefix + "weight"
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = OrderedDict({weight_key: self.weight})
|
|
|
|
|
|
|
|
# gather in weight groups
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.weight_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in input groups
|
|
|
|
if gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.input_parallel_mode,
|
|
|
|
dims={weight_key: 0},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
# gather in output groups
|
2023-09-19 06:20:26 +00:00
|
|
|
if gpc.get_local_rank(self.input_parallel_mode) == 0 and gpc.get_local_rank(self.weight_parallel_mode) == 0:
|
2022-04-01 08:52:47 +00:00
|
|
|
local_state = gather_tensor_parallel_state_dict(
|
|
|
|
local_state,
|
|
|
|
self.output_parallel_mode,
|
|
|
|
dims={weight_key: -1},
|
|
|
|
partition_states={weight_key: True},
|
|
|
|
keep_vars=keep_vars,
|
|
|
|
)
|
|
|
|
if gpc.get_local_rank(ParallelMode.TENSOR) == 0:
|
|
|
|
destination.update(local_state)
|
|
|
|
|
2022-02-14 03:15:02 +00:00
|
|
|
def forward(self, input_: Tensor) -> Tensor:
|
|
|
|
input_ = split_tensor_3d(input_, 0, self.weight_parallel_mode)
|
|
|
|
|
|
|
|
input_mask = (input_ < self.vocab_start_index) | (input_ >= self.vocab_end_index)
|
|
|
|
masked_input = input_.clone() - self.vocab_start_index
|
|
|
|
masked_input[input_mask] = 0
|
|
|
|
|
2022-02-17 14:03:39 +00:00
|
|
|
weight = all_gather_tensor_3d(self.weight, 0, self.weight_parallel_mode)
|
2022-02-14 03:15:02 +00:00
|
|
|
|
|
|
|
output_parallel = F.embedding(masked_input, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs)
|
|
|
|
|
2023-09-19 06:20:26 +00:00
|
|
|
output_parallel[input_mask, :] = 0.0
|
2022-02-14 03:15:02 +00:00
|
|
|
output = reduce_scatter_tensor_3d(output_parallel, 0, self.input_parallel_mode)
|
|
|
|
|
|
|
|
return output
|