python_code
stringlengths
0
108k
from torch.optim.lr_scheduler import OneCycleLR as _OneCycleLR from colossalai.registry import LR_SCHEDULERS @LR_SCHEDULERS.register_module class OneCycleLR(_OneCycleLR): r"""Sets the learning rate of each parameter group according to the 1cycle learning rate policy. The 1cycle policy anneals the learning rate from an initial learning rate to some maximum learning rate and then from that maximum learning rate to some minimum learning rate much lower than the initial learning rate. This policy was initially described in the paper `Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates`_. The 1cycle learning rate policy changes the learning rate after every batch. `step` should be called after a batch has been used for training. This scheduler is not chainable. Note also that the total number of steps in the cycle can be determined in one of two ways (listed in order of precedence): * A value for total_steps is explicitly provided. * A number of epochs (epochs) and a number of steps per epoch (steps_per_epoch) are provided. In this case, the number of total steps is inferred by total_steps = epochs * steps_per_epoch You must either provide a value for total_steps or provide a value for both epochs and steps_per_epoch. The default behaviour of this scheduler follows the fastai implementation of 1cycle, which claims that "unpublished work has shown even better results by using only two phases". To mimic the behaviour of the original paper instead, set ``three_phase=True``. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. pct_start (float, optional): The percentage of the cycle (in number of steps) spent increasing the learning rate, defaults to 0.3. anneal_strategy (str, optional): {'cos', 'linear'}, Specifies the annealing strategy: "cos" for cosine annealing, "linear" for linear annealing, defaults to 'cos'. cycle_momentum (bool, optional): If ``True``, momentum is cycled inversely to learning rate between 'base_momentum' and 'max_momentum', defaults to True. base_momentum (float, optional): Lower momentum boundaries in the cycle for each parameter group. Note that momentum is cycled inversely to learning rate; at the peak of a cycle, momentum is 'base_momentum' and learning rate is 'max_lr', defaults to 0.85. max_momentum (float, optional): Upper momentum boundaries in the cycle for each parameter group. Functionally, it defines the cycle amplitude (max_momentum - base_momentum). Note that momentum is cycled inversely to learning rate; at the start of a cycle, momentum is 'max_momentum' and learning rate is 'base_lr', defaults to 0.95. div_factor (float, optional): Determines the initial learning rate via initial_lr = max_lr/div_factor, defaults to 25.0. final_div_factor (float, optional): Determines the minimum learning rate via min_lr = initial_lr/final_div_factor, defaults to 10000.0. last_epoch (int, optional): The index of the last batch. This parameter is used when resuming a training job. Since `step()` should be invoked after each batch instead of after each epoch, this number represents the total number of *batches* computed, not the total number of epochs computed. When last_epoch=-1, the schedule is started from the beginning, defaults to -1 The ``kwargs`` for initializing torch.optim.lr_scheduler.OneCycleLR should include parameters below: :: epochs (int, optional, default=None) steps_per_epoch (int, optional, default=None) three_phase (bool, optional, default=False) verbose (bool, optional, default=False) More details about kwargs could be found in `OneCycleLR <https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.OneCycleLR.html#torch.optim.lr_scheduler.OneCycleLR>`_. .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates: https://arxiv.org/abs/1708.07120 """ def __init__(self, optimizer, total_steps: int, pct_start=0.3, anneal_strategy='cos', cycle_momentum=True, base_momentum=0.85, max_momentum=0.95, div_factor=25.0, final_div_factor=10000.0, last_epoch=-1, **kwargs): max_lrs = list(map(lambda group: group['lr'], optimizer.param_groups)) super().__init__(optimizer, max_lrs, total_steps=total_steps, pct_start=pct_start, anneal_strategy=anneal_strategy, cycle_momentum=cycle_momentum, base_momentum=base_momentum, max_momentum=max_momentum, div_factor=div_factor, final_div_factor=final_div_factor, last_epoch=last_epoch)
from typing import List from torch.optim.lr_scheduler import MultiStepLR as _MultiStepLR from colossalai.registry import LR_SCHEDULERS from .delayed import WarmupScheduler @LR_SCHEDULERS.register_module class MultiStepLR(_MultiStepLR): """Decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones. Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler. When last_epoch=-1, sets initial lr as lr. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. milestones (List[int], optional): List of epoch indices. Must be increasing, defaults to None. gamma (float, optional): Multiplicative factor of learning rate decay, defaults to 0.1. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, total_steps: int, milestones: List[int] = None, gamma: float = 0.1, last_epoch: int = -1, **kwargs): super().__init__(optimizer, milestones, gamma=gamma, last_epoch=last_epoch) @LR_SCHEDULERS.register_module class MultiStepWarmupLR(WarmupScheduler): """Multistep learning rate scheduler with warmup. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. warmup_steps (int, optional): Number of warmup steps, defaults to 0. milestones (List[int], optional): List of epoch indices. Must be increasing, defaults to None. gamma (float, optional): Multiplicative factor of learning rate decay, defaults to 0.1. num_steps_per_epoch (int, optional): Number of steps per epoch, defaults to -1. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, total_steps: int, warmup_steps: int = 0, milestones: List[int] = None, gamma: float = 0.1, last_epoch: int = -1, **kwargs): if len(milestones) == 0: raise ValueError('milestones cannot be empty') milestones = [ v - warmup_steps for v in milestones if v >= warmup_steps] base_scheduler = _MultiStepLR(optimizer, milestones=milestones, gamma=gamma) super().__init__(optimizer, warmup_steps, base_scheduler, last_epoch=last_epoch)
from .cosine import CosineAnnealingLR, CosineAnnealingWarmupLR, FlatAnnealingLR, FlatAnnealingWarmupLR from .linear import LinearWarmupLR from .multistep import MultiStepLR, MultiStepWarmupLR from .onecycle import OneCycleLR from .poly import PolynomialLR, PolynomialWarmupLR from .torch import LambdaLR, MultiplicativeLR, StepLR, ExponentialLR __all__ = [ 'CosineAnnealingLR', 'CosineAnnealingWarmupLR', 'FlatAnnealingLR', 'FlatAnnealingWarmupLR', 'LinearWarmupLR', 'MultiStepLR', 'MultiStepWarmupLR', 'OneCycleLR', 'PolynomialLR', 'PolynomialWarmupLR', 'LambdaLR', 'MultiplicativeLR', 'StepLR', 'ExponentialLR' ]
from torch.optim.lr_scheduler import _LRScheduler from colossalai.registry import LR_SCHEDULERS from .delayed import WarmupScheduler @LR_SCHEDULERS.register_module class PolynomialLR(_LRScheduler): """Polynomial learning rate scheduler. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. end_lr (float, optional): Minimum learning rate, defaults to 0.0001. power (float, optional): The power of polynomial, defaults to 1.0. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, total_steps: int, end_lr: float = 0.0001, power: float = 1.0, last_epoch: int = -1, **kwargs): if end_lr < 0: raise ValueError(f'end_lr must >= 0, got {end_lr}') self.total_steps = total_steps self.end_lr = end_lr self.power = power super().__init__(optimizer, last_epoch=last_epoch) def get_lr(self): return self._get_closed_form_lr() def _get_closed_form_lr(self): return [ (base_lr - self.end_lr) * ((1 - min(self.last_epoch, self.total_steps) / self.total_steps) ** self.power) + self.end_lr for base_lr in self.base_lrs ] @LR_SCHEDULERS.register_module class PolynomialWarmupLR(WarmupScheduler): """Polynomial learning rate scheduler with warmup. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. warmup_steps (int, optional): Number of warmup steps, defaults to 0. end_lr (float, optional): Minimum learning rate, defaults to 0.0001. power (float, optional): The power of polynomial, defaults to 1.0. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, total_steps: int, warmup_steps: int = 0, end_lr: float = 0.0001, power: float = 1.0, last_epoch: int = -1, **kwargs): base_scheduler = PolynomialLR( optimizer, total_steps - warmup_steps, end_lr=end_lr, power=power) super().__init__(optimizer, warmup_steps, base_scheduler, last_epoch=last_epoch)
from torch.optim.lr_scheduler import _LRScheduler class _enable_get_lr_call: def __init__(self, o): self.o = o def __enter__(self): self.o._get_lr_called_within_step = True return self def __exit__(self, type, value, traceback): self.o._get_lr_called_within_step = False class DelayerScheduler(_LRScheduler): """Starts with a flat lr schedule until it reaches N epochs then applies the specific scheduler (For example: ReduceLROnPlateau) Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. delay_epochs (int): Number of epochs to keep the initial lr until starting applying the scheduler. after_scheduler (:class:`torch.optim.lr_scheduler`): After target_epoch, use this scheduler. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, delay_epochs, after_scheduler, last_epoch=-1): if delay_epochs < 0: raise ValueError(f'delay_epochs must >= 0, got {delay_epochs}') self.delay_epochs = delay_epochs self.after_scheduler = after_scheduler self.finished = False super().__init__(optimizer, last_epoch) def get_lr(self): if self.last_epoch >= self.delay_epochs: if not self.finished: self.after_scheduler.base_lrs = self.base_lrs self.finished = True with _enable_get_lr_call(self.after_scheduler): return self.after_scheduler.get_lr() return self.base_lrs def step(self, epoch=None): if self.finished: if epoch is None: self.after_scheduler.step(None) self._last_lr = self.after_scheduler.get_last_lr() else: self.after_scheduler.step(epoch - self.delay_epochs) self._last_lr = self.after_scheduler.get_last_lr() else: return super(DelayerScheduler, self).step(epoch) class WarmupScheduler(_LRScheduler): """Starts with a linear warmup lr schedule until it reaches N epochs then applies the specific scheduler (For example: ReduceLROnPlateau). Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. warmup_epochs (int): Number of epochs to linearly warmup lr until starting applying the scheduler. after_scheduler (:class:`torch.optim.lr_scheduler`): After target_epoch, use this scheduler. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, warmup_epochs, after_scheduler, last_epoch=-1): self.warmup_epochs = int(warmup_epochs) self.after_scheduler = after_scheduler self.finished = False super().__init__(optimizer, last_epoch) def get_lr(self): if self.last_epoch >= self.warmup_epochs: if not self.finished: self.after_scheduler.base_lrs = self.base_lrs self.finished = True return self.after_scheduler.get_lr() return [(self.last_epoch + 1) / self.warmup_epochs * lr for lr in self.base_lrs] def step(self, epoch=None): if self.finished: if epoch is None: self.after_scheduler.step(None) self._last_lr = self.after_scheduler.get_last_lr() else: self.after_scheduler.step(epoch - self.warmup_epochs) self._last_lr = self.after_scheduler.get_last_lr() else: return super().step(epoch) class WarmupDelayerScheduler(_LRScheduler): """Starts with a linear warmup lr schedule until it reaches N epochs and a flat lr schedule until it reaches M epochs then applies the specific scheduler (For example: ReduceLROnPlateau). Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. warmup_epochs (int): Number of epochs to linearly warmup lr until starting applying the scheduler. delay_epochs (int): Number of epochs to keep the initial lr until starting applying the scheduler. after_scheduler (:class:`torch.optim.lr_scheduler`): After target_epoch, use this scheduler. last_epoch (int, optional): The index of last epoch, defaults to -1. When last_epoch=-1, the schedule is started from the beginning or When last_epoch=-1, sets initial lr as lr. """ def __init__(self, optimizer, warmup_epochs, delay_epochs, after_scheduler, last_epoch=-1): if delay_epochs < 0: raise ValueError(f'delay_epochs must >= 0, got {delay_epochs}') if warmup_epochs < 0: raise ValueError(f'warmup_epochs must >= 0, got {warmup_epochs}') self.warmup_epochs = warmup_epochs self.delay_epochs = delay_epochs self.after_scheduler = after_scheduler self.finished = False super().__init__(optimizer, last_epoch) def get_lr(self): if self.last_epoch >= self.warmup_epochs + self.delay_epochs: if not self.finished: self.after_scheduler.base_lrs = self.base_lrs # reset lr to base_lr for group, base_lr in zip(self.optimizer.param_groups, self.base_lrs): group['lr'] = base_lr self.finished = True with _enable_get_lr_call(self.after_scheduler): return self.after_scheduler.get_lr() elif self.last_epoch >= self.warmup_epochs: return self.base_lrs return [(self.last_epoch + 1) / self.warmup_epochs * lr for lr in self.base_lrs] def step(self, epoch=None): if self.finished: if epoch is None: self.after_scheduler.step(None) self._last_lr = self.after_scheduler.get_last_lr() else: self.after_scheduler.step(epoch - self.warmup_epochs) self._last_lr = self.after_scheduler.get_last_lr() else: return super().step(epoch)
from torch.optim.lr_scheduler import LambdaLR as _LambdaLR from torch.optim.lr_scheduler import MultiplicativeLR as _MultiplicativeLR from torch.optim.lr_scheduler import StepLR as _StepLR from torch.optim.lr_scheduler import ExponentialLR as _ExponentialLR from colossalai.registry import LR_SCHEDULERS @LR_SCHEDULERS.register_module class LambdaLR(_LambdaLR): """Sets the learning rate of each parameter group to the initial lr times a given function. When last_epoch=-1, sets initial lr as lr. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. lr_lambda (Union[``function``, ``list[function]``]): A function which computes a multiplicative factor given an integer parameter epoch, or a list of such functions, one for each group in optimizer.param_groups, defaults to None. last_epoch (int, optional): The index of last epoch, defaults to -1. """ def __init__(self, optimizer, total_steps, lr_lambda=None, last_epoch: int = -1) -> None: super().__init__(optimizer, lr_lambda, last_epoch=last_epoch) @LR_SCHEDULERS.register_module class MultiplicativeLR(_MultiplicativeLR): """Multiply the learning rate of each parameter group by the factor given in the specified function. When last_epoch=-1, sets initial lr as lr. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. lr_lambda (Union[``function``, ``list[function]``]): A function which computes a multiplicative factor given an integer parameter epoch, or a list of such functions, one for each group in optimizer.param_groups, defaults to None. last_epoch (int, optional): The index of last epoch, defaults to -1. """ def __init__(self, optimizer, total_steps, lr_lambda=None, last_epoch: int = -1) -> None: super().__init__(optimizer, lr_lambda, last_epoch=last_epoch) @LR_SCHEDULERS.register_module class StepLR(_StepLR): """Decays the learning rate of each parameter group by gamma every step_size epochs. Notice that such decay can happen simultaneously with other changes to the learning rate from outside this scheduler. When last_epoch=-1, sets initial lr as lr. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. total_steps (int): Number of total training steps. step_size (int, optional): Period of learning rate decay, defaults to 1. gamma (float, optional): Multiplicative factor of learning rate decay, defaults to 0.1. last_epoch (int, optional): The index of last epoch, defaults to -1. """ def __init__(self, optimizer, total_steps, step_size: int = 1, gamma: float = 0.1, last_epoch: int = -1) -> None: super().__init__(optimizer, step_size, gamma=gamma, last_epoch=last_epoch) @LR_SCHEDULERS.register_module class ExponentialLR(_ExponentialLR): """Decays the learning rate of each parameter group by gamma every epoch. When last_epoch=-1, sets initial lr as lr Args: optimizer (Union[:class:`torch.optim.Optimizer`, :class:`colossalai.nn.optimizer`]): Wrapped optimizer. total_steps (int): Number of total training steps. gamma (float, optional): Multiplicative factor of learning rate decay, defaults to 1.0. last_epoch (int, optional): The index of last epoch, defaults to -1. """ def __init__(self, optimizer, total_steps, gamma: float = 1.0, last_epoch: int = -1) -> None: super().__init__(optimizer, gamma, last_epoch=last_epoch)
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch.nn as nn from colossalai.context import ParallelMode from colossalai.core import global_context as gpc class ParallelLayer(nn.Module): def __init__(self): super().__init__() self.data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank( ParallelMode.DATA) self.data_parallel_size = 1 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_world_size( ParallelMode.DATA) self.tensor_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.TENSOR) else gpc.get_local_rank( ParallelMode.TENSOR) self.tensor_parallel_size = 1 if not gpc.is_initialized(ParallelMode.TENSOR) else gpc.get_world_size( ParallelMode.TENSOR) self.pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank( ParallelMode.PIPELINE) self.pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size( ParallelMode.PIPELINE) def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) if gpc.get_local_rank(ParallelMode.TENSOR) != 0: missing_keys.clear() unexpected_keys.clear()
from .colossalai_layer import * from .parallel_1d import * from .parallel_2d import * from .parallel_2p5d import * from .parallel_3d import * from .parallel_sequence import * from .moe import * from .utils import * from .vanilla import * from .wrapper import *
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch from torch import distributed as dist from colossalai.communication import ring_forward from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.nn.layer.parallel_sequence._utils import _calc_incoming_device_range, _calc_current_device_range from colossalai.utils import get_current_device from torch.cuda.amp import custom_bwd, custom_fwd class RingQK(torch.autograd.Function): """ Calculate QK in a ring-exchange style """ @staticmethod @custom_fwd def forward(ctx, sub_q, sub_k, batch_size, num_attention_heads, sub_seq_length): # save tensor for backward ctx.save_for_backward(sub_q, sub_k) ctx.sub_seq_length = sub_seq_length # create local segment of attention score attention_score = torch.empty( batch_size * num_attention_heads, sub_seq_length, sub_seq_length * gpc.get_world_size(ParallelMode.SEQUENCE), dtype=sub_q.dtype, device=get_current_device() ) # compute local QK^T part_a = torch.matmul(sub_q, sub_k.transpose(2, 1)) local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE) local_world_size = gpc.get_world_size(ParallelMode.SEQUENCE) start_idx = local_rank * sub_seq_length end_idx = (local_rank + 1) * sub_seq_length attention_score[:, :, start_idx: end_idx] = part_a # compute QK^T in ring-all-reduce style for i in range(local_world_size - 1): sub_k = ring_forward(sub_k, ParallelMode.SEQUENCE) start_idx, end_idx = _calc_incoming_device_range(i, local_rank, local_world_size, sub_seq_length) part_a = torch.matmul(sub_q, sub_k.transpose(2, 1)) attention_score[:, :, start_idx:end_idx] = part_a return attention_score @staticmethod @custom_bwd def backward(ctx, grad_output): sub_q, sub_k, = ctx.saved_tensors local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE) local_world_size = gpc.get_world_size(ParallelMode.SEQUENCE) # calculate gradient of sub_k grad_k = torch.matmul( grad_output.transpose(2, 1), sub_q ) dist.all_reduce(grad_k, group=gpc.get_group(ParallelMode.SEQUENCE)) grad_k = grad_k[:, local_rank * ctx.sub_seq_length: (local_rank + 1) * ctx.sub_seq_length] grad_k /= local_world_size # calculate gradient for sub_q grad_q = torch.zeros_like(sub_q, dtype=sub_q.dtype, device=get_current_device(), ) # compute with local sub_k start_idx, end_idx = _calc_current_device_range(local_rank, ctx.sub_seq_length) grad_q += torch.matmul(grad_output[:, :, start_idx:end_idx], sub_k) # compute QK^T in ring-all-reduce style for i in range(local_world_size - 1): sub_k = ring_forward(sub_k, ParallelMode.SEQUENCE) start_idx, end_idx = _calc_incoming_device_range(i, local_rank, local_world_size, ctx.sub_seq_length) grad_q += torch.matmul(grad_output[:, :, start_idx: end_idx], sub_k) grad_q /= local_world_size return grad_q, grad_k, None, None, None class RingAV(torch.autograd.Function): """ Calculate AV in a ring-exchange style """ @staticmethod @custom_fwd def forward(ctx, attention_score, sub_v, batch_size, num_attention_heads, attention_head_size, sub_seq_length): local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE) local_world_size = gpc.get_world_size(ParallelMode.SEQUENCE) local_start_idx, local_end_idx = _calc_current_device_range(local_rank, sub_seq_length) sub_attention_result = torch.zeros( batch_size * num_attention_heads, sub_seq_length, attention_head_size, device=get_current_device(), dtype=attention_score.dtype) # save tensors for backward ctx.save_for_backward(attention_score, sub_v) ctx.sub_seq_length = sub_seq_length # compute local AV part_av = torch.matmul(attention_score[:, :, local_start_idx:local_end_idx], sub_v) sub_attention_result += part_av # compute AV in ring - all - reduce style for i in range(local_world_size - 1): sub_v = ring_forward(sub_v, ParallelMode.SEQUENCE) start_idx, end_idx = _calc_incoming_device_range(i, local_rank, local_world_size, sub_seq_length) # compute QK^T part_av = torch.matmul(attention_score[:, :, start_idx:end_idx], sub_v) sub_attention_result += part_av return sub_attention_result @staticmethod @custom_bwd def backward(ctx, grad_output): local_rank = gpc.get_local_rank(ParallelMode.SEQUENCE) local_world_size = gpc.get_world_size(ParallelMode.SEQUENCE) local_start_idx, local_end_idx = _calc_current_device_range(local_rank, ctx.sub_seq_length) attention_scores, sub_v = ctx.saved_tensors # calculate gradient of v grad_v = torch.matmul( attention_scores.transpose(2, 1), grad_output ) dist.all_reduce(grad_v, group=gpc.get_group(ParallelMode.SEQUENCE)) grad_v = grad_v[:, local_start_idx:local_end_idx] grad_v /= local_world_size # calculate gradient for attention score grad_attention_score = torch.zeros_like(attention_scores, dtype=grad_output.dtype, device=get_current_device()) # compute with local sub_k grad_attention_score[:, :, local_start_idx:local_end_idx] += torch.matmul( grad_output, sub_v.transpose(2, 1)) # compute QK^T in ring-all-reduce style for i in range(local_world_size - 1): sub_v = ring_forward(sub_v, ParallelMode.SEQUENCE) start_idx, end_idx = _calc_incoming_device_range(i, local_rank, local_world_size, ctx.sub_seq_length) # compute grad_q grad_attention_score[:, :, start_idx:end_idx] += torch.matmul( grad_output, sub_v.transpose(2, 1)) return grad_attention_score, grad_v, None, None, None, None
from ._operation import RingQK, RingAV from .layers import TransformerSelfAttentionRing __all__ = ['TransformerSelfAttentionRing', 'RingAV', 'RingQK']
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math import colossalai import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.nn.layer.parallel_sequence._operation import RingQK, RingAV from colossalai.registry import LAYERS from colossalai.kernel.cuda_native.scaled_softmax import AttnMaskType from colossalai.kernel import FusedScaleMaskSoftmax from colossalai.context import seed @LAYERS.register_module class TransformerSelfAttentionRing(nn.Module): """Parallel self-attention layer abstract class. Self-attention layer takes input with size [b, s, h] and returns output of the same size. Args: hidden_size (int): hidden size. num_attention_heads (int): number of attention heads. attention_dropout (float): dropout probability for attention layer. attention_mask_func (:class:`typing.Callable`): Mask function to be applied. layer_number (int): number of layers. """ def __init__(self, hidden_size, num_attention_heads, attention_dropout, attention_mask_func, layer_number, apply_query_key_layer_scaling: bool = False, convert_fp16_to_fp32_in_softmax: bool = False, attn_mask_type=AttnMaskType.padding, masked_softmax_fusion=True, fp16=False, bf16=False ): super().__init__() self.convert_fp16_to_fp32_in_softmax = convert_fp16_to_fp32_in_softmax self.apply_query_key_layer_scaling = apply_query_key_layer_scaling self.attention_mask_func = attention_mask_func self.layer_number = layer_number self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.attn_mask_type = attn_mask_type assert self.layer_number > 0 self.attention_dropout = attention_dropout if self.apply_query_key_layer_scaling: self.convert_fp16_to_fp32_in_softmax = True assert self.hidden_size % self.num_attention_heads == 0, \ 'hidden size is not divisible by the number of attention heads' self.hidden_size_per_attention_head = self.hidden_size // num_attention_heads self.world_size = gpc.get_world_size(ParallelMode.SEQUENCE) # Strided linear layer. self.query_key_value = _Linear( hidden_size, 3 * self.hidden_size, ) self.coeff = None self.norm_factor = math.sqrt(self.hidden_size) if self.apply_query_key_layer_scaling: self.coeff = layer_number self.norm_factor *= self.coeff self.scale_mask_softmax = FusedScaleMaskSoftmax( fp16, bf16, self.attn_mask_type, masked_softmax_fusion, self.attention_mask_func, self.convert_fp16_to_fp32_in_softmax, self.coeff) self.attention_dropout = nn.Dropout(attention_dropout) # Output. self.dense = _Linear(hidden_size, hidden_size, bias=True, skip_bias_add=True) def forward(self, hidden_states, attention_mask): # hidden_states: [sub_seq_len, batch_size, hidden_size] # attention_mask: [batch_size, 1, sub_seq_len, seq_len] sub_seq_length, batch_size, hidden_size = hidden_states.size() # ===================== # Query, Key, and Value # ===================== # Attention heads shape change: # [sub_seq_len, batch_size, hidden_size] --> [sub_seq_len, batch_size, (3 * head_size * num_heads)] mixed_x_layer = self.query_key_value(hidden_states) # [sub_seq_len, batch_size, num_heads, 3 * head_size] --> 3 [sub_seq_len, batch_size, num_heads, head_size] new_tensor_shape = mixed_x_layer.size()[:-1] + (self.num_attention_heads, 3 * self.hidden_size_per_attention_head) mixed_x_layer = mixed_x_layer.view(*new_tensor_shape) # split into query, key and value last_dim = mixed_x_layer.dim() - 1 last_dim_value = mixed_x_layer.size(-1) assert last_dim_value % 3 == 0, 'the last dimension is not a multiple of 3, ' \ 'cannot be divided into query, key and value' partition_size = last_dim_value // 3 (query_layer, key_layer, value_layer) = torch.split( mixed_x_layer, partition_size, dim=last_dim) # attention scores: [batch_size, num_heads, sub_seq_len, seq_len] output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0) * self.world_size) # [sub_seq_len, batch_size, num_heads, head_size] -> [sub_seq_len, batch_size * num_heads, head_size] query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1) # [sub_seq_len, batch_size, num_heads, head_size] -> [sub_seq_len, batch_size * num_heads, head_size] key_layer = key_layer.view(key_layer.size(0), output_size[0] * output_size[1], -1) # attention_scores: [batch_size * num_heads, sub_seq_len, seq_len] attention_scores = RingQK.apply( query_layer.transpose(0, 1).contiguous(), # [batch_size * num_heads, sub_seq_len, head_size] key_layer.transpose(0, 1).contiguous(), # [batch_size * num_heads, sub_seq_len, head_size], batch_size, self.num_attention_heads, sub_seq_length ) attention_scores /= self.norm_factor # change view to [batch_size, num_heads, sub_seq_len, seq_len] attention_scores = attention_scores.view(*output_size) # change shape to [batch_size, num_heads, sub_seq_len, seq_len] attention_probs = self.scale_mask_softmax(attention_scores, attention_mask) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. with seed(ParallelMode.TENSOR): attention_probs = self.attention_dropout(attention_probs) # context layer shape: [batch_size, num_heads, sub_seq_len, head_size] output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3)) # change view [sub_seq_len, batch_size * num_heads, head_size] value_layer = value_layer.contiguous().view(value_layer.size(0), output_size[0] * output_size[1], -1) # # change view [b * num_heads, sub_seq_len, seq_len] attention_probs = attention_probs.view(attention_probs.size(0) * attention_probs.size(1), attention_probs.size(2), attention_probs.size(3)) # matmul: [batch_size * num_heads, sub_seq_len, head_size] context_layer = RingAV.apply( attention_probs, value_layer.transpose(0, 1).contiguous(), batch_size, self.num_attention_heads, self.hidden_size_per_attention_head, sub_seq_length ) # change view [batch_size, num_heads, sub_seq_len, head_size] context_layer = context_layer.view(*output_size) # [batch_size, num_heads, sub_seq_len, head_size] -> [sub_seq_len, batch_size, num_heads, head_size] context_layer = context_layer.permute(2, 0, 1, 3).contiguous() # [sub_seq_len, batch_size, num_heads, head_size] -> [sub_seq_len, batch_size, hidden_size] new_context_layer_shape = context_layer.size()[:-2] + ( self.hidden_size_per_attention_head * self.num_attention_heads,) context_layer = context_layer.view(*new_context_layer_shape) output, bias = self.dense(context_layer) return output, bias def __repr__(self): return f'TransformerSelfAttentionRing(apply_query_key_layer_scaling={self.apply_query_key_layer_scaling}, ' \ f'layer_number={self.layer_number}, hidden_size:{self.hidden_size}, attention_dropout={self.attention_dropout}, ' \ f'attn_mask_type={self.attn_mask_type}, num_attention_heads={self.num_attention_heads}, ' \ f'hidden_size_per_attention_head={self.hidden_size_per_attention_head}, coeff={self.coeff}, norm_factor={self.norm_factor}, ' \ f'convert_fp16_to_fp32_in_softmax={self.convert_fp16_to_fp32_in_softmax})' class _Linear(nn.Module): """Linear layer with column parallelism. The linear layer is defined as Y = XA + b. A is parallelized along its second dimension as A = [A_1, ..., A_p]. Arguments: input_size: first dimension of matrix A. output_size: second dimension of matrix A. bias: If true, add bias init_method: method to initialize weights. Note that bias is always set to zero. stride: For the strided linear layers. keep_master_weight_for_test: This was added for testing and should be set to False. It returns the master weights used for initialization. skip_bias_add: This was added to enable performance optimations where bias can be fused with other elementwise operations. we skip adding bias but instead return it. """ def __init__(self, input_size, output_size, bias=True, skip_bias_add=False): super(_Linear, self).__init__() # Keep input parameters self.input_size = input_size self.output_size = output_size self.skip_bias_add = skip_bias_add self.weight = Parameter(torch.empty(self.output_size, self.input_size, )) nn.init.xavier_normal_(self.weight) if bias: self.bias = Parameter(torch.empty(self.output_size)) # Always initialize bias to zero. with torch.no_grad(): self.bias.zero_() else: self.register_parameter('bias', None) def forward(self, input_): # Matrix multiply. bias = self.bias if not self.skip_bias_add else None output = F.linear(input_, self.weight, bias) if self.skip_bias_add: return output, self.bias else: return output def __repr__(self): return f'Linear(in_features={self.input_size}, out_features={self.output_size}, ' + \ f'bias={self.bias is not None}, skip_bias_add={self.skip_bias_add})'
#!/usr/bin/env python # -*- encoding: utf-8 -*- def _calc_incoming_device_range(i, rank, world_size, sub_seq_length): device_of_incoming_k = (rank - i - 1) % world_size start_idx = sub_seq_length * device_of_incoming_k end_idx = sub_seq_length * (device_of_incoming_k + 1) return start_idx, end_idx def _calc_current_device_range(rank, sub_seq_length): start_idx = sub_seq_length * rank end_idx = sub_seq_length * (rank + 1) return start_idx, end_idx
import torch.nn as nn import torch.distributed as dist from typing import List, Tuple, Union from colossalai.context import ParallelMode from colossalai.core import global_context as gpc class PipelineSharedModuleWrapper: def __init__(self, pipeline_ranks: Union[List[int], Tuple[int]]) -> None: assert len(pipeline_ranks) > 1, f'Expect len(pipeline_ranks) > 1, got {len(pipeline_ranks)}' self.pipeline_ranks = pipeline_ranks self.group = None self.ranks_in_group = None self._init_group() def _init_group(self): world_size = gpc.get_world_size(ParallelMode.GLOBAL) dp_size = gpc.get_world_size(ParallelMode.DATA) pp_size = gpc.get_world_size(ParallelMode.PIPELINE) rank = gpc.get_global_rank() num_dp_groups = world_size // dp_size num_pp_stages = num_dp_groups // pp_size for i in range(dp_size): for j in range(num_pp_stages): pipeline_ranks = list( range(i * num_dp_groups + j, (i + 1) * num_dp_groups, num_pp_stages)) sub_ranks = [pipeline_ranks[idx] for idx in self.pipeline_ranks] group = dist.new_group(sub_ranks) if rank in sub_ranks: self.group = group self.ranks_in_group = sub_ranks def register_module(self, module: nn.Module): assert self.ranks_in_group is not None,\ f'Rank {gpc.get_local_rank(ParallelMode.PIPELINE)} is not in pipeline_ranks {self.pipeline_ranks}' src = self.ranks_in_group[self.pipeline_ranks[0]] for p in module.parameters(): setattr(p, 'pipeline_shared_module_pg', self.group) dist.broadcast(p, src, group=self.group) def register_parameter(self, param: nn.Parameter): assert self.ranks_in_group is not None,\ f'Rank {gpc.get_local_rank(ParallelMode.PIPELINE)} is not in pipeline_ranks {self.pipeline_ranks}' src = self.ranks_in_group[self.pipeline_ranks[0]] setattr(param, 'pipeline_shared_module_pg', self.group) dist.broadcast(param, src, group=self.group)
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch.nn as nn from colossalai.builder import build_layer from colossalai.registry import LAYERS @LAYERS.register_module class LambdaWrapper(nn.Module): """Wrap a function to nn.Module, which takes a config of layers and can fully access them. Args: func (``Callable``): User customed function. layers_cfg (dict, optional): Config of layers, defaults to None. """ def __init__(self, func, layers_cfg: dict = None): super().__init__() self.func = func self.layers = self._build_layers(layers_cfg) def _build_layers(self, layers_cfg: dict): if layers_cfg is None: return None else: layers = [] for cfg in layers_cfg: layer = build_layer(cfg) layers.append(layer) return layers def forward(self, *args, **kwargs): return self.func(self, *args, **kwargs)
from .lambda_wrapper import LambdaWrapper from .pipeline_wrapper import PipelineSharedModuleWrapper __all__ = ['LambdaWrapper', 'PipelineSharedModuleWrapper']
from typing import Any, Tuple import torch import torch.distributed as dist from colossalai.communication.collective import (all_gather, all_reduce, reduce_scatter) from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.utils import get_current_device from torch import Tensor from torch.cuda.amp import custom_bwd, custom_fwd def get_parallel_group(parallel_mode: ParallelMode): return gpc.get_group(parallel_mode) def get_global_rank(): return gpc.get_global_rank() def get_parallel_rank(parallel_mode: ParallelMode): return gpc.get_local_rank(parallel_mode) class _Classifier2p5D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, A: Tensor, B: Tensor, bias, tesseract_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: A = A.clone().detach() A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) B_temp = all_gather(B, -1, col_parallel_mode) if ctx: ctx.save_for_backward(A, B_temp) C = torch.matmul(A, B_temp.transpose(0, 1)) C = all_reduce(C, row_parallel_mode) ctx.use_bias = bias is not None if bias is not None: C = C + bias out = C.reshape(out_shape) if ctx: ctx.tesseract_dim = tesseract_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = torch.matmul(output_grad, B) A_grad = A_grad.reshape(ctx.A_shape) B_grad = torch.matmul(output_grad.reshape(-1, output_grad.shape[-1]).transpose(0, 1), A) B_grad = reduce_scatter(B_grad, -1, ctx.col_parallel_mode) B_grad = B_grad.reshape(ctx.B_shape) if ctx.use_bias: bias_grad = torch.sum(output_grad, dim=tuple(range(output_grad.ndim - 1))) bias_grad = all_reduce(bias_grad, ctx.col_parallel_mode) else: bias_grad = None return A_grad, B_grad, bias_grad, None, None, None, None, None, None, None, None, None, None def classifier_2p5d(A: Tensor, B: Tensor, bias, tesseract_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: r"""Classifier. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. bias (:class:`torch.tensor`): matrix of bias. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int): the rank of row. col_rank (int): the rank of column. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Classifier2p5D.apply(A, B, bias, tesseract_dim, out_shape, row_rank, col_rank, row_parallel_mode, col_parallel_mode, data_parallel_rank, pipeline_parallel_rank, pipeline_parallel_size, tensor_parallel_size) class Matmul_AB_2p5D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = AB`. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int): the rank of row. col_rank (int): the rank of column. dep_rank (int): the rank of depth. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, A: Tensor, B: Tensor, tesseract_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, dep_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: # A: [b / dq, s, h / q] -> [(b * s) / dq, h / q] # B: [h / dq, s / q] # C: [b / dq, s, s / q] -> [(b * s) / dq, s / q] assert A.shape[-1] == B.shape[-2], \ 'Invalid shapes: A={}, B={} for AB.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[0], B.shape[-1]) C = torch.zeros(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases A_list = [torch.empty_like(A) for _ in range(2)] B_list = [torch.empty_like(B) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_a = \ tesseract_dim * row_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_b = \ col_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opa = [None] * 2 opb = [None] * 2 A_list[0].copy_(A) B_list[0].copy_(B) opa[0] = dist.broadcast(A_list[0], src=src_a, group=row_group, async_op=True) opb[0] = dist.broadcast(B_list[0], src=src_b, group=col_group, async_op=True) cur = 0 for i in range(tesseract_dim): if i != tesseract_dim - 1: A_list[1 - cur].copy_(A) opa[1 - cur] = dist.broadcast(A_list[1 - cur], src=src_a + 1, group=row_group, async_op=True) B_list[1 - cur].copy_(B) opb[1 - cur] = dist.broadcast(B_list[1 - cur], src=src_b + tesseract_dim, group=col_group, async_op=True) if opa[cur] is not None: opa[cur].wait() if opb[cur] is not None: opb[cur].wait() torch.addmm(C, A_list[cur], B_list[cur], out=C) cur = 1 - cur src_a += 1 src_b += tesseract_dim out = C.reshape(out_shape) if ctx: ctx.tesseract_dim = tesseract_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.dep_rank = dep_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_ABT_2p5D.apply(output_grad, B, ctx.tesseract_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_ATB_2p5D.apply(A, output_grad, ctx.tesseract_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None, None, None, None class Matmul_ABT_2p5D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = AB^T`. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int): the rank of row. col_rank (int): the rank of column. dep_rank (int): the rank of depth. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, A: Tensor, B: Tensor, tesseract_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, dep_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: assert A.shape[-1] == B.shape[-1], \ 'Invalid shapes: A={}, B={} for ABT.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[0], B.shape[0]) C = torch.empty(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases B_list = [torch.empty_like(B) for _ in range(2)] C_list = [torch.empty_like(C) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_b = \ col_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_c = \ tesseract_dim * row_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opb = [None] * 2 opr = [None] * 2 B_list[0].copy_(B) opb[0] = dist.broadcast(B_list[0], src=src_b, group=col_group, async_op=True) cur = 0 for i in range(tesseract_dim): if i != tesseract_dim - 1: B_list[1 - cur].copy_(B) opb[1 - cur] = dist.broadcast(B_list[1 - cur], src=src_b + tesseract_dim, group=col_group, async_op=True) if opr[cur] is not None: opr[cur].wait() if i - 2 == col_rank: C.copy_(C_list[cur]) if opb[cur] is not None: opb[cur].wait() torch.matmul(A, B_list[cur].transpose(0, 1), out=C_list[cur]) opr[cur] = dist.reduce(C_list[cur], dst=src_c, group=row_group, async_op=True) cur = 1 - cur src_b += tesseract_dim src_c += 1 for op in opr: op.wait() if tesseract_dim - 2 == col_rank: C.copy_(C_list[cur]) if tesseract_dim - 1 == col_rank: C.copy_(C_list[1 - cur]) out = C.reshape(out_shape) if ctx: ctx.tesseract_dim = tesseract_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.dep_rank = dep_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_AB_2p5D.apply(output_grad, B, ctx.tesseract_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_ATB_2p5D.apply(output_grad, A, ctx.tesseract_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None, None, None, None class Matmul_ATB_2p5D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = A^TB` Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int): the rank of row. col_rank (int): the rank of column. dep_rank (int): the rank of depth. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, A: Tensor, B: Tensor, tesseract_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, dep_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int): assert A.shape[-2] == B.shape[-2], \ 'Invalid shapes: A={}, B={} for ATB.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[-1], B.shape[-1]) C = torch.empty(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases A_list = [torch.empty_like(A) for _ in range(2)] C_list = [torch.empty_like(C) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_a = \ tesseract_dim * row_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_c = \ col_rank + tesseract_dim ** 2 * dep_rank + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opa = [None] * 2 opr = [None] * 2 A_list[0].copy_(A) opa[0] = dist.broadcast(A_list[0], src=src_a, group=row_group, async_op=True) cur = 0 for i in range(tesseract_dim): if i != tesseract_dim - 1: A_list[1 - cur].copy_(A) opa[1 - cur] = dist.broadcast(A_list[1 - cur], src=src_a + 1, group=row_group, async_op=True) if opr[cur] is not None: opr[cur].wait() if i - 2 == row_rank: C.copy_(C_list[cur]) if opa[cur] is not None: opa[cur].wait() torch.matmul(A_list[cur].transpose(0, 1), B, out=C_list[cur]) opr[cur] = dist.reduce(C_list[cur], dst=src_c, group=col_group, async_op=True) cur = 1 - cur src_a += 1 src_c += tesseract_dim for op in opr: op.wait() if tesseract_dim - 2 == row_rank: C.copy_(C_list[cur]) if tesseract_dim - 1 == row_rank: C.copy_(C_list[1 - cur]) out = C.reshape(out_shape) if ctx: ctx.tesseract_dim = tesseract_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.dep_rank = dep_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_ABT_2p5D.apply(B, output_grad, ctx.tesseract_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_AB_2p5D.apply(A, output_grad, ctx.tesseract_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.dep_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None, None, None, None class _Add_Bias_2p5D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, input: Tensor, bias: Tensor, output_size_per_partition: int, tesseract_dim: int, row_rank: int, col_rank: int, dep_rank: int, col_parallel_mode: ParallelMode, skip_bias_add: bool, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: if row_rank == 0: bias_temp = bias.clone() else: bias_temp = torch.zeros(output_size_per_partition, dtype=bias.dtype, device=get_current_device()) src_rank = \ col_rank + dep_rank * tesseract_dim ** 2 + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size dist.broadcast(bias_temp, src=src_rank, group=get_parallel_group(col_parallel_mode)) ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.dep_rank = dep_rank ctx.tesseract_dim = tesseract_dim ctx.col_parallel_mode = col_parallel_mode ctx.bias = skip_bias_add ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size if skip_bias_add: return bias_temp else: output = input + bias_temp return output @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: row_rank = ctx.row_rank col_rank = ctx.col_rank dep_rank = ctx.dep_rank tesseract_dim = ctx.tesseract_dim col_parallel_mode = ctx.col_parallel_mode data_parallel_rank = ctx.data_parallel_rank pipeline_parallel_rank = ctx.pipeline_parallel_rank pipeline_parallel_size = ctx.pipeline_parallel_size tensor_parallel_size = ctx.tensor_parallel_size if ctx.bias: dst_rank = \ col_rank + dep_rank * (tesseract_dim ** 2) + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size dist.reduce(output_grad, dst=dst_rank, group=get_parallel_group(col_parallel_mode)) if row_rank == 0: return \ None, output_grad, None, None, None, None, None, None, \ None, None, None, None, None, None, None, None else: grad_tmp = torch.zeros_like(output_grad) return \ None, grad_tmp, None, None, None, None, None, None, \ None, None, None, None, None, None, None, None else: reduce_dim = tuple(range(output_grad.ndim - 1)) reduce = torch.sum(output_grad, dim=reduce_dim) dst_rank = \ col_rank + dep_rank * (tesseract_dim ** 2) + \ data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size dist.reduce(reduce, dst=dst_rank, group=get_parallel_group(col_parallel_mode)) if row_rank == 0: return \ output_grad, reduce, None, None, None, None, None, None, None, \ None, None, None, None, None, None, None, None else: reduce_tmp = torch.zeros_like(reduce) return \ output_grad, reduce_tmp, None, None, None, None, None, None, \ None, None, None, None, None, None, None, None, None def add_bias_2p5d(input: Tensor, bias: Tensor, output_size_per_partition: int, tesseract_dim: int, row_rank: int, col_rank: int, dep_rank: int, col_parallel_mode: ParallelMode, skip_bias_add: bool, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: r"""Matrix add bias: :math:`C = A + b`. Args: input (:class:`torch.tensor`): matrix :math:`A`. bias (:class:`torch.tensor`): matrix :math:`B`. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism. output_size_per_partition (int): output size in each partition. row_rank (int): the rank of row. col_rank (int): the rank of column. dep_rank (int): the rank of depth. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. skip_bias_add (bool): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Add_Bias_2p5D.apply(input, bias, output_size_per_partition, tesseract_dim, row_rank, col_rank, dep_rank, col_parallel_mode, skip_bias_add, data_parallel_rank, pipeline_parallel_rank, pipeline_parallel_size, tensor_parallel_size) class _Layernorm2p5D(torch.autograd.Function): r"""Layernorm. Args: input (:class:`torch.tensor`): input matrix. E_x (:class:`torch.tensor`): mean. Var_x (:class:`torch.tensor`): variance. hidden_size (int): hidden size. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx: Any, input: Tensor, E_x: Tensor, Var_x: Tensor, hidden_size: int, row_parallel_mode: ParallelMode) -> Tensor: input = input - E_x # in here, input = x - E[x], Var_x = 1 / sqrt(Var[x] + eps) ctx.hidden_size = hidden_size output = input * Var_x ctx.save_for_backward(output, Var_x) ctx.row_parallel_mode = row_parallel_mode return output @staticmethod @custom_bwd def backward(ctx, output_grad): row_parallel_mode = ctx.row_parallel_mode x, Var_x = ctx.saved_tensors # in here, Var_x = 1 / sqrt(Var[x] + eps), x = (x - E[x]) * Var_x with torch.no_grad(): output_grad_sum = torch.sum(output_grad, dim=-1, keepdim=True) torch.distributed.all_reduce(output_grad_sum, group=get_parallel_group(row_parallel_mode)) output_grad_sum /= ctx.hidden_size output_grad_mul_x_sum = torch.sum(output_grad * x, dim=-1, keepdim=True) torch.distributed.all_reduce(output_grad_mul_x_sum, group=get_parallel_group(row_parallel_mode)) output_grad_mul_x_sum /= ctx.hidden_size input_grad = output_grad.clone() input_grad -= x * output_grad_mul_x_sum input_grad -= output_grad_sum input_grad *= Var_x return input_grad, None, None, None, None, None, None def layernorm_2p5d(input: Tensor, E_x: Tensor, Var_x: Tensor, hidden_size: int, row_parallel_mode: ParallelMode) -> Tensor: r"""Layernorm. Args: input (:class:`torch.tensor`): input matrix. E_x (:class:`torch.tensor`): mean. Var_x (:class:`torch.tensor`): variance. hidden_size (int): hidden size. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ return _Layernorm2p5D.apply(input, E_x, Var_x, hidden_size, row_parallel_mode) class _AllGatherTensor2p5D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, inputs: Tensor, dim: int, col_parallel_mode: ParallelMode) -> Tensor: ctx.dim = dim ctx.col_parallel_mode = col_parallel_mode outputs = all_gather(inputs, dim, col_parallel_mode) return outputs @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: grad = reduce_scatter(output_grad, ctx.dim, ctx.col_parallel_mode) return grad.contiguous(), None, None def all_gather_tensor_2p5d(inputs: Tensor, dim: int, col_parallel_mode: ParallelMode) -> Tensor: r"""all gather the weight of 2.5D parallelism. Args: inputs (:class:`torch.tensor`): input tensor. dim (int): dimension of all-gather. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ return _AllGatherTensor2p5D.apply(inputs, dim, col_parallel_mode) class SplitFirst(torch.autograd.Function): r""" Args: inputs (:class:`torch.tensor`): input tensor. tesseract_dim (int): dimension of TESSERACT fo 2.5D parallelism col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, inputs: Tensor, tesseract_dim: int, col_parallel_mode: ParallelMode) -> Tensor: ctx.tesseract_dim = tesseract_dim ctx.batch_size = inputs.size(0) ctx.para_mode = col_parallel_mode row_rank = gpc.get_local_rank(col_parallel_mode) outputs = inputs.chunk(tesseract_dim, dim=0)[row_rank] return outputs @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: grad_shape = (ctx.batch_size,) + output_grad.shape[1:] grad = torch.empty(grad_shape, dtype=output_grad.dtype, device=get_current_device()) dist.all_gather(list(grad.chunk(ctx.tesseract_dim, dim=0)), output_grad.contiguous(), group=gpc.get_group(ctx.para_mode)) return grad, None, None def split_batch_2p5d(input_: Tensor, dim: int = 0) -> Tensor: """Splits 2P5D tensor in specified dimension across cols. Args: input_ (:class:`torch.tensor`): Input tensor. dim (int): Specified dimension in which to split. Returns: :class:`torch.tensor`: The tensor has been split. """ dim_size = input_.size(dim) world_size = gpc.get_world_size(ParallelMode.PARALLEL_2P5D_COL) if world_size <= 1: return input_ assert dim_size % world_size == 0, \ f'The batch size ({dim_size}) is not a multiple of 2.5D size * depth ({world_size}).' return torch.chunk(input_, gpc.get_world_size(ParallelMode.PARALLEL_2P5D_COL), dim=dim)[gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL)].contiguous() class _ReduceTensor2p5D(torch.autograd.Function): @staticmethod def forward(ctx, input_, parallel_mode): return all_reduce(input_, parallel_mode) @staticmethod def backward(ctx, output_grad): return output_grad, None def reduce_tensor_2p5d(input_: Tensor, parallel_mode: ParallelMode) -> Tensor: r"""All-reduce the input. Args: input_ (:class:`torch.tensor`): Input tensor. parallel_mode (:class:`colossalai.context.ParallelMode`): The parallel mode tensor used. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _ReduceTensor2p5D.apply(input_, parallel_mode) class _ReduceScatterTensor2p5D(torch.autograd.Function): @staticmethod def forward(ctx, input_, dim, parallel_mode): ctx.dim = dim ctx.parallel_mode = parallel_mode return reduce_scatter(input_, dim, parallel_mode) @staticmethod def backward(ctx, output_grad): return all_gather(output_grad, ctx.dim, ctx.parallel_mode), None, None def reduce_scatter_tensor_2p5d(input_: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""Reduce-scatter the input. Args: input_ (:class:`torch.tensor`): Input tensor. dim (int): Dimension to reduce. parallel_mode (:class:`colossalai.context.ParallelMode`): The parallel mode tensor used. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ dim_size = input_.size(dim) world_size = gpc.get_world_size(parallel_mode) assert dim_size % world_size == 0, \ f'The batch size ({dim_size}) is not a multiple of 2.5D size * depth ({world_size}).' return _ReduceScatterTensor2p5D.apply(input_, dim, parallel_mode) class _RreduceByBatch2p5D(torch.autograd.Function): @staticmethod def symbolic(graph, input_, reduce_mean: bool = False): output = all_reduce(input_, ParallelMode.PARALLEL_2P5D_COL) if reduce_mean: reduce_size = gpc.get_world_size(ParallelMode.PARALLEL_2P5D_COL) return output / reduce_size return output @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx, input_, reduce_mean: bool = False): output = all_reduce(input_, ParallelMode.PARALLEL_2P5D_COL) ctx.reduce_mean = reduce_mean if reduce_mean: reduce_size = gpc.get_world_size(ParallelMode.PARALLEL_2P5D_COL) ctx.reduce_size = reduce_size return output.clone() / reduce_size return output.clone() @staticmethod @custom_bwd def backward(ctx, output_grad): if ctx.reduce_mean: return output_grad / ctx.reduce_size, None else: return output_grad, None def reduce_by_batch_2p5d(input_, reduce_mean: bool = False) -> Tensor: r"""All-reduce the input from the model parallel region. Args: input_ (:class:`torch.tensor`): input matrix. reduce_mean (bool, optional): If set to ``True``, it will divide the output by column parallel size, default to False. """ return _RreduceByBatch2p5D.apply(input_, reduce_mean)
from ._operation import reduce_by_batch_2p5d, split_batch_2p5d from .layers import (Classifier2p5D, Embedding2p5D, LayerNorm2p5D, Linear2p5D, PatchEmbedding2p5D, VocabParallelClassifier2p5D, VocabParallelEmbedding2p5D) __all__ = [ 'split_batch_2p5d', 'reduce_by_batch_2p5d', 'Linear2p5D', 'LayerNorm2p5D', 'Classifier2p5D', 'PatchEmbedding2p5D', 'Embedding2p5D', 'VocabParallelClassifier2p5D', 'VocabParallelEmbedding2p5D' ]
import math from collections import OrderedDict from typing import Callable import torch import torch.nn as nn import torch.nn.functional as F from colossalai.communication import broadcast from colossalai.context import ParallelMode, seed from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from colossalai.nn import init as init from colossalai.registry import LAYERS from colossalai.utils.checkpointing import (broadcast_state_dict, gather_tensor_parallel_state_dict, partition_tensor_parallel_state_dict) from colossalai.utils.cuda import get_current_device from torch import Tensor from torch.nn import Parameter from ..base_layer import ParallelLayer from ..utils import divide, set_tensor_parallel_attribute_by_partition, to_2tuple from ._operation import (Matmul_AB_2p5D, Matmul_ABT_2p5D, add_bias_2p5d, all_gather_tensor_2p5d, classifier_2p5d, layernorm_2p5d, reduce_scatter_tensor_2p5d, split_batch_2p5d) from ._utils import assert_tesseract_initialization, get_tesseract_dim_dep_from_env @LAYERS.register_module class Linear2p5D(ParallelLayer): r"""Linear layer for 2.5D 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. skip_bias_add (bool, optional): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion, defaults to False. 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>`_. """ 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)): super().__init__() self.in_features = in_features self.out_features = out_features self.skip_bias_add = skip_bias_add # parallel setting assert_tesseract_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) self.dep_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP) self.tesseract_dim, _ = get_tesseract_dim_dep_from_env() # partitioning dimension self.input_size_per_partition = divide(in_features, self.tesseract_dim) self.hidden_size_per_partition = divide(out_features, self.tesseract_dim) # create weight, shape: [k/q, h/q] factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter( torch.empty(self.input_size_per_partition, self.hidden_size_per_partition, **factory_kwargs)) # create bias, shape: [h/q] if bias: self.bias = Parameter(torch.empty(self.hidden_size_per_partition, **factory_kwargs)) else: self.register_parameter('bias', None) # initialize parameters with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.tesseract_dim) def reset_parameters(self, weight_initializer, bias_initializer) -> None: fan_in, fan_out = self.in_features, self.out_features weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 # broadcast in dep groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0 and \ gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) == 0: broadcast_state_dict(local_state, ParallelMode.PARALLEL_2P5D_DEP) # partition in column groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # partition in row groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP) == 0: weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias # gather in row groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in column groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, 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) def forward(self, x: Tensor) -> Tensor: # input: [m/dq, n/q, k/q] # output: [m/dq, n/q, h/q] out_shape = x.shape[:-1] + (self.hidden_size_per_partition, ) output = Matmul_AB_2p5D.apply( x, self.weight, self.tesseract_dim, out_shape, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_ROW, ParallelMode.PARALLEL_2P5D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size, ) if self.bias is not None: if self.skip_bias_add: bias = add_bias_2p5d(None, self.bias, self.hidden_size_per_partition, self.tesseract_dim, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output, bias else: output = add_bias_2p5d(output, self.bias, self.hidden_size_per_partition, self.tesseract_dim, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_COL, False, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output else: return output @LAYERS.register_module class LayerNorm2p5D(ParallelLayer): r"""Layer Normalization for 2.5D 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-05. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps: float = 1e-05, bias=True, dtype=None): super().__init__() # layer norm config self.normalized_shape = normalized_shape self.variance_epsilon = eps # parallel setting assert_tesseract_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) self.dep_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP) self.tesseract_dim, _ = get_tesseract_dim_dep_from_env() # partitioning dimension self.partitioned_partition = divide(normalized_shape, self.tesseract_dim) # * # create parameters factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter(torch.ones(self.partitioned_partition, **factory_kwargs)) if bias: self.bias = Parameter(torch.zeros(self.partitioned_partition, **factory_kwargs)) else: self.bias = None self._set_tensor_parallel_attribute() def _set_tensor_parallel_attribute(self): set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.tesseract_dim) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 # partition in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, x: Tensor) -> Tensor: with torch.no_grad(): E_x = torch.sum(x, dim=-1, keepdim=True) # [b/q, s, 1] torch.distributed.all_reduce(E_x, group=gpc.get_group(ParallelMode.PARALLEL_2P5D_ROW)) E_x /= self.normalized_shape # Var_x in the block below is the sum of input^2 Var_x = torch.sum(x * x, dim=-1, keepdim=True) # [b/q, s, 1] torch.distributed.all_reduce(Var_x, group=gpc.get_group(ParallelMode.PARALLEL_2P5D_ROW)) Var_x /= self.normalized_shape Var_x = Var_x - E_x * E_x # variance of x [b/q, s, 1] # this time 1/sqrt(Var_x + epsilon) Var_x = 1.0 / torch.sqrt(Var_x + self.variance_epsilon) output = layernorm_2p5d(x, E_x, Var_x, self.normalized_shape, ParallelMode.PARALLEL_2P5D_ROW) scale = add_bias_2p5d(None, self.weight, self.partitioned_partition, self.tesseract_dim, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) if self.bias is not None: bias = add_bias_2p5d(None, self.bias, self.partitioned_partition, self.tesseract_dim, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) output = torch.addcmul(bias, scale, output) else: output = torch.mul(scale, output) return output @LAYERS.register_module class PatchEmbedding2p5D(ParallelLayer): 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>`_. """ 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_()): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) assert_tesseract_initialization() self.tesseract_dim, self.tesseract_dep = get_tesseract_dim_dep_from_env() 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] self.flatten = flatten self.embed_size = embed_size self.embed_size_per_partition = embed_size // self.tesseract_dim**2 with seed(ParallelMode.TENSOR): self.weight = Parameter( torch.empty((self.embed_size_per_partition, in_chans, *self.patch_size), device=get_current_device(), dtype=dtype)) self.bias = Parameter(torch.empty(self.embed_size_per_partition, device=get_current_device(), dtype=dtype)) self.cls_token = Parameter( torch.zeros((1, 1, self.embed_size_per_partition), device=get_current_device(), dtype=dtype)) self.pos_embed = Parameter( torch.zeros((1, self.num_patches + 1, self.embed_size_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer, bias_initializer, position_embed_initializer) self._set_tensor_parallel_attribute() def _set_tensor_parallel_attribute(self): set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) set_tensor_parallel_attribute_by_partition(self.bias, self.tesseract_dim**2) set_tensor_parallel_attribute_by_partition(self.cls_token, self.tesseract_dim**2) set_tensor_parallel_attribute_by_partition(self.pos_embed, self.tesseract_dim**2) def reset_parameters(self, weight_initializer, bias_initializer, position_embed_initializer): 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) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' cls_token_key = prefix + 'cls_token' pos_embed_key = prefix + 'pos_embed' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, 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 }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, 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 }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): 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 }) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, 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 }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, 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 }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: input_ = split_batch_2p5d(input_, 0) B, C, H, W = input_.shape assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." weight = all_gather_tensor_2p5d(self.weight, 0, ParallelMode.PARALLEL_2P5D_COL) bias = all_gather_tensor_2p5d(self.bias, 0, ParallelMode.PARALLEL_2P5D_COL) output = F.conv2d(input_, weight, bias, stride=self.patch_size) if self.flatten: output = output.flatten(2).transpose(1, 2) # BCHW -> BNC cls_token = all_gather_tensor_2p5d(self.cls_token, -1, ParallelMode.PARALLEL_2P5D_COL) pos_embed = all_gather_tensor_2p5d(self.pos_embed, -1, ParallelMode.PARALLEL_2P5D_COL) cls_token = cls_token.expand(output.shape[0], -1, -1) output = torch.cat((cls_token, output), dim=1) output = output + pos_embed return output @LAYERS.register_module class Embedding2p5D(ParallelLayer): r"""Embedding for 2.5D 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>`_ """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): super().__init__() assert_tesseract_initialization() self.tesseract_dim, self.tesseract_dep = get_tesseract_dim_dep_from_env() self.num_embeddings = num_embeddings self.embed_dim = embedding_dim embed_dim_per_partition = embedding_dim // self.tesseract_dim**2 self.padding_idx = padding_idx self.embed_args = args self.embed_kwargs = kwargs self.weight = Parameter( torch.empty((num_embeddings, embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) 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: if self.padding_idx is not None: with torch.no_grad(): self.weight[self.padding_idx].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={weight_key: -1}, partition_states={weight_key: True}, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={weight_key: -1}, partition_states={weight_key: True}, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={weight_key: -1}, partition_states={weight_key: True}, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, 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) def forward(self, input_: Tensor) -> Tensor: input_ = split_batch_2p5d(input_, 0) weight = all_gather_tensor_2p5d(self.weight, -1, ParallelMode.PARALLEL_2P5D_COL) output = F.embedding(input_, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) return output @LAYERS.register_module class VocabParallelEmbedding2p5D(torch.nn.Module): """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>`_. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): 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 assert_tesseract_initialization() self.tesseract_dim, self.tesseract_dep = get_tesseract_dim_dep_from_env() self.num_embeddings_per_partition = divide(self.num_embeddings, self.tesseract_dim) self.embed_dim_per_partition = divide(self.embed_dim, self.tesseract_dim) tensor_parallel_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) self.vocab_start_index = tensor_parallel_rank * self.num_embeddings_per_partition self.vocab_end_index = self.vocab_start_index + self.num_embeddings_per_partition self.weight = Parameter( torch.empty((self.num_embeddings_per_partition, self.embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() env.vocab_parallel = True def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) 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: if self.padding_idx is not None and \ self.vocab_start_index <= self.padding_idx < self.vocab_end_index: with torch.no_grad(): self.weight[self.padding_idx - self.vocab_start_index].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={weight_key: -1}, partition_states={weight_key: True}, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={weight_key: 0}, partition_states={weight_key: True}, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={weight_key: 0}, partition_states={weight_key: True}, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, 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) def forward(self, input_: Tensor) -> Tensor: # Build the mask. input_mask = (input_ < self.vocab_start_index) | (input_ >= self.vocab_end_index) # Mask the input. masked_input = input_.clone() - self.vocab_start_index masked_input[input_mask] = 0 output_parallel = F.embedding(masked_input, self.weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) # Mask the output embedding. output_parallel[input_mask, :] = 0. # Reduce across all the model parallel GPUs. output = reduce_scatter_tensor_2p5d(output_parallel, 0, ParallelMode.PARALLEL_2P5D_COL) return output @LAYERS.register_module class Classifier2p5D(ParallelLayer): r"""Classifier for 2.5D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes assert_tesseract_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) self.dep_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP) self.tesseract_dim, self.tesseract_dep = get_tesseract_dim_dep_from_env() # partitioning dimension self.input_size_per_partition = divide(self.in_features, self.tesseract_dim**2) if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter( torch.empty(self.num_classes, self.input_size_per_partition, device=get_current_device(), dtype=dtype)) 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): if self.has_weight: set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) def reset_parameters(self, weight_initializer, bias_initializer) -> None: with seed(ParallelMode.TENSOR): fan_in, fan_out = self.in_features, self.num_classes col_src_rank = gpc.get_ranks_in_group(ParallelMode.PARALLEL_2P5D_COL)[0] row_src_rank = gpc.get_ranks_in_group(ParallelMode.PARALLEL_2P5D_ROW)[0] if self.has_weight: weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) broadcast(self.bias, col_src_rank, ParallelMode.PARALLEL_2P5D_COL) broadcast(self.bias, row_src_rank, ParallelMode.PARALLEL_2P5D_ROW) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: out_shape = input_.shape[:-1] + (self.num_classes, ) return classifier_2p5d(input_, self.weight, self.bias, self.tesseract_dim, out_shape, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2P5D_ROW, ParallelMode.PARALLEL_2P5D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) @LAYERS.register_module class VocabParallelClassifier2p5D(ParallelLayer): r"""Vocab parallel classifier layer for 2.5D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes # parallel setting assert_tesseract_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_ROW) self.dep_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_DEP) self.tesseract_dim, _ = get_tesseract_dim_dep_from_env() # partitioning dimension self.input_size_per_partition = divide(in_features, self.tesseract_dim) self.hidden_size_per_partition = divide(num_classes, self.tesseract_dim) # create weight, shape: [k/q, h/q] factory_kwargs = {'device': get_current_device(), 'dtype': dtype} if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter( torch.empty(self.hidden_size_per_partition, self.input_size_per_partition, **factory_kwargs)) self.has_weight = True # create bias, shape: [h/q] if bias: self.bias = Parameter(torch.empty(self.hidden_size_per_partition, **factory_kwargs)) else: self.bias = None # initialize parameters with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() env.vocab_parallel = True def _set_tensor_parallel_attributes(self): if self.has_weight: set_tensor_parallel_attribute_by_partition(self.weight, self.tesseract_dim**2) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.tesseract_dim) def reset_parameters(self, weight_initializer, bias_initializer) -> None: 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2P5D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2P5D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def forward(self, x: Tensor) -> Tensor: # input: [m/dq, n/q, k/q] # output: [m/dq, n/q, h/q] out_shape = x.shape[:-1] + (self.hidden_size_per_partition, ) output = Matmul_ABT_2p5D.apply( x, self.weight, self.tesseract_dim, out_shape, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_ROW, ParallelMode.PARALLEL_2P5D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size, ) if self.bias is not None: output = add_bias_2p5d(output, self.bias, self.hidden_size_per_partition, self.tesseract_dim, self.row_rank, self.col_rank, self.dep_rank, ParallelMode.PARALLEL_2P5D_COL, False, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output
from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env def get_tesseract_dim_dep_from_env(): try: tesseract_dim = env.tesseract_dim tesseract_dep = env.tesseract_dep assert tesseract_dim > 0, 'TESSERACT_DIM must be larger than zero' assert tesseract_dep > 0, 'TESSERACT_DEP must be larger than zero' return tesseract_dim, tesseract_dep except KeyError as e: raise EnvironmentError('TESSERACT_DIM or TESSERACT_DEP is not found in the current environment, ' 'please make sure that you have used the correct process group initializer') def assert_tesseract_initialization(): assert gpc.is_initialized(ParallelMode.PARALLEL_2P5D_COL) and \ gpc.is_initialized(ParallelMode.PARALLEL_2P5D_ROW) and \ gpc.is_initialized(ParallelMode.PARALLEL_2P5D_DEP) and \ gpc.is_initialized(ParallelMode.PARALLEL_2P5D_XZ), \ 'Both PARALLEL_2P5D_COL, PARALLEL_2P5D_ROW, PARALLEL_2P5D_DEP and PARALLEL_2P5D_XZ ' \ 'must be initialized by the process group initializer'
#!/usr/bin/env python # -*- encoding: utf-8 -*- from typing import Optional, Tuple import torch from colossalai.communication import (all_gather, all_reduce, broadcast, reduce, reduce_scatter) from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from torch import Tensor from torch.cuda.amp import custom_bwd, custom_fwd from ._utils import get_parallel_mode_from_env from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D class _Linear3D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx, input_: Tensor, weight: Tensor, bias: Optional[Tensor], input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode, input_dim: int = 0, weight_dim: int = -1, output_dim: int = 0) -> Tensor: ctx.use_bias = bias is not None input_ = all_gather(input_, input_dim, input_parallel_mode) weight = all_gather(weight, weight_dim, weight_parallel_mode) ctx.save_for_backward(input_, weight) output = torch.matmul(input_, weight) output = reduce_scatter(output, output_dim, output_parallel_mode) if bias is not None: output += bias ctx.input_parallel_mode = input_parallel_mode ctx.weight_parallel_mode = weight_parallel_mode ctx.output_parallel_mode = output_parallel_mode ctx.input_dim = input_dim ctx.weight_dim = weight_dim ctx.output_dim = output_dim return output @staticmethod @custom_bwd def backward(ctx, output_grad: Tensor) -> Tuple[Tensor, ...]: input_, weight = ctx.saved_tensors with torch.no_grad(): output_grad = all_gather(output_grad, ctx.output_dim, ctx.output_parallel_mode) async_ops = list() input_grad = torch.matmul(output_grad, weight.transpose(0, 1)) input_grad, op = reduce_scatter(input_grad, ctx.input_dim, ctx.input_parallel_mode, async_op=True) async_ops.append(op) weight_grad = torch.matmul( input_.reshape(-1, input_.shape[-1]).transpose(0, 1), output_grad.reshape(-1, output_grad.shape[-1])) weight_grad, op = reduce_scatter(weight_grad, ctx.weight_dim, ctx.weight_parallel_mode, async_op=True) async_ops.append(op) if ctx.use_bias: bias_grad = torch.sum(output_grad, dim=tuple(range(len(output_grad.shape))[:-1])) bias_grad, op = all_reduce(bias_grad, ctx.weight_parallel_mode, async_op=True) async_ops.append(op) else: bias_grad = None for op in async_ops: if op is not None: op.wait() return input_grad, weight_grad, bias_grad, None, None, None, None, None, None def linear_3d(input_: Tensor, weight: Tensor, bias: Optional[Tensor], input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode, input_dim: int = 0, weight_dim: int = -1, output_dim: int = 0) -> Tensor: r"""Linear layer for 3D parallelism. Args: input_ (:class:`torch.tensor`): input matrix. weight (:class:`torch.tensor`): matrix of weight. bias (:class:`torch.tensor`): matrix of bias. input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): weight parallel mode. output_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): output parallel mode. input_dim (int, optional): dimension of input, defaults to 0. weight_dim (int, optional): dimension of weight, defaults to -1. output_dim (int, optional): dimension of output, defaults to 0. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Linear3D.apply(input_, weight, bias, input_parallel_mode, weight_parallel_mode, output_parallel_mode, input_dim, weight_dim, output_dim) class _Classifier3D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx, input_: Tensor, weight: Tensor, bias: Optional[Tensor], input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: ctx.use_bias = bias is not None ranks_in_group = gpc.get_ranks_in_group(input_parallel_mode) src_rank = ranks_in_group[gpc.get_local_rank(output_parallel_mode)] weight = broadcast(weight, src_rank, input_parallel_mode) ctx.save_for_backward(input_, weight) output = torch.matmul(input_, weight.transpose(0, 1)) output = all_reduce(output, output_parallel_mode) if bias is not None: output += bias ctx.src_rank = src_rank ctx.input_parallel_mode = input_parallel_mode ctx.weight_parallel_mode = weight_parallel_mode ctx.output_parallel_mode = output_parallel_mode return output @staticmethod @custom_bwd def backward(ctx, output_grad: Tensor) -> Tuple[Tensor, ...]: input_, weight = ctx.saved_tensors with torch.no_grad(): async_ops = list() weight_grad = torch.matmul( output_grad.reshape(-1, output_grad.shape[-1]).transpose(0, 1), input_.reshape(-1, input_.shape[-1])) weight_grad = reduce(weight_grad, ctx.src_rank, ctx.input_parallel_mode) if gpc.get_local_rank(ctx.input_parallel_mode) == gpc.get_local_rank(ctx.output_parallel_mode): weight_grad, op = all_reduce(weight_grad, ctx.weight_parallel_mode, async_op=True) async_ops.append(op) else: weight_grad = None if ctx.use_bias: bias_grad = torch.sum(output_grad, dim=tuple(range(len(output_grad.shape))[:-1])) bias_grad = all_reduce(bias_grad, ctx.input_parallel_mode) bias_grad, op = all_reduce(bias_grad, ctx.weight_parallel_mode, async_op=True) async_ops.append(op) else: bias_grad = None input_grad = torch.matmul(output_grad, weight) for op in async_ops: if op is not None: op.wait() return input_grad, weight_grad, bias_grad, None, None, None, None, None, None def classifier_3d(input_: Tensor, weight: Tensor, bias: Optional[Tensor], input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: r"""3D parallel classifier. Args: input_ (:class:`torch.tensor`): input matrix. weight (:class:`torch.tensor`): matrix of weight. bias (:class:`torch.tensor`): matrix of bias. input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): weight parallel mode. output_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): output parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Classifier3D.apply(input_, weight, bias, input_parallel_mode, weight_parallel_mode, output_parallel_mode) class _Layernorm3D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx, input_: Tensor, weight: Tensor, bias: Optional[Tensor], normalized_shape: int, eps: float, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: mean = all_reduce(torch.sum(input_, dim=-1, keepdim=True), output_parallel_mode) / normalized_shape mu = input_ - mean var = all_reduce(torch.sum(mu**2, dim=-1, keepdim=True), output_parallel_mode) / normalized_shape sigma = torch.sqrt(var + eps) ctx.save_for_backward(mu, sigma, weight) z = mu / sigma output = weight * z if bias is not None: output = output + bias ctx.use_bias = bias is not None ctx.normalized_shape = normalized_shape ctx.input_parallel_mode = input_parallel_mode ctx.weight_parallel_mode = weight_parallel_mode ctx.output_parallel_mode = output_parallel_mode return output @staticmethod @custom_bwd def backward(ctx, output_grad: Tensor) -> Tuple[Tensor, ...]: mu, sigma, weight = ctx.saved_tensors with torch.no_grad(): weight_grad = output_grad * mu / sigma if ctx.use_bias: bias_grad = output_grad weight_grad = torch.stack([bias_grad, weight_grad]).contiguous() else: bias_grad = None weight_grad = torch.sum(weight_grad, dim=tuple(range(len(weight_grad.shape))[1:-1])) weight_grad = all_reduce(weight_grad, ctx.weight_parallel_mode) weight_grad = all_reduce(weight_grad, ctx.input_parallel_mode) if ctx.use_bias: bias_grad, weight_grad = weight_grad[0], weight_grad[1] dz = output_grad * weight dvar = dz * mu * (-0.5) * sigma**(-3) dvar = all_reduce(torch.sum(dvar, dim=-1, keepdim=True), ctx.output_parallel_mode) dmean = dz * (-1 / sigma) + dvar * -2 * mu / ctx.normalized_shape dmean = all_reduce(torch.sum(dmean, dim=-1, keepdim=True), ctx.output_parallel_mode) input_grad = dz / sigma + dvar * 2 * mu / \ ctx.normalized_shape + dmean / ctx.normalized_shape return input_grad, weight_grad, bias_grad, None, None, None, None, None def layernorm_3d(input_: Tensor, weight: Tensor, bias: Optional[Tensor], normalized_shape: int, eps: float, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: r"""3D parallel Layernorm. Args: input_ (:class:`torch.tensor`): input matrix. weight (:class:`torch.tensor`): matrix of weight. bias (:class:`torch.tensor`): matrix of bias. 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): a value added to the denominator for numerical stability input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): weight parallel mode. output_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): output parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Layernorm3D.apply(input_, weight, bias, normalized_shape, eps, input_parallel_mode, weight_parallel_mode, output_parallel_mode) def split_tensor_3d(tensor: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""Splits 3D parallel tensor in specified dimension. Args: tensor (:class:`torch.tensor`): Input tensor. dim (int): Specified dimension in which to split. parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`, optional): Parallel mode. Returns: :class:`torch.tensor`: The tensor has been split. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ dim_size = tensor.size(dim) world_size = gpc.get_world_size(parallel_mode) assert dim_size % world_size == 0, \ f'The dimension {dim} to split, size ({dim_size}) is not a multiple of world size ({world_size}), ' \ f'cannot split tensor evenly' if tensor.size(dim) <= 1: return tensor output = torch.chunk(tensor, gpc.get_world_size(parallel_mode), dim=dim)[gpc.get_local_rank(parallel_mode)].contiguous() return output def split_batch_3d(input_: Tensor, dim: int = 0, input_parallel_mode: ParallelMode = ParallelMode.PARALLEL_3D_INPUT, weight_parallel_mode: ParallelMode = ParallelMode.PARALLEL_3D_WEIGHT) -> Tensor: r"""Splits 3D tensor in batch. Args: input_ (:class:`torch.tensor`): Input tensor. dim (int): Specified dimension in which to split. input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`, optional): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`, optional): weight parallel mode. Returns: :class:`torch.tensor`: The tensor has been split. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ dim_size = input_.size(dim) weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D) input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D) weight_world_size = gpc.get_world_size(weight_parallel_mode) input_world_size = gpc.get_world_size(input_parallel_mode) assert dim_size % (input_world_size*weight_world_size) == 0, \ f'The batch size ({dim_size}) is not a multiple of square of 3D depth ({input_world_size*weight_world_size}).' if input_.size(dim) <= 1: return input_ output = torch.chunk(input_, weight_world_size, dim=dim)[gpc.get_local_rank(weight_parallel_mode)].contiguous() output = torch.chunk(output, input_world_size, dim=dim)[gpc.get_local_rank(input_parallel_mode)].contiguous() return output class _ReduceTensor3D(torch.autograd.Function): @staticmethod def forward(ctx, input_, parallel_mode): return all_reduce(input_, parallel_mode) @staticmethod def backward(ctx, output_grad): return output_grad, None def reduce_tensor_3d(tensor: Tensor, parallel_mode: ParallelMode) -> Tensor: r"""All-reduce the input Args: tensor (:class:`torch.tensor`): Input tensor. parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): Parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ return _ReduceTensor3D.apply(tensor, parallel_mode) class _AllGatherTensor3D(torch.autograd.Function): @staticmethod def forward(ctx, input_, dim, parallel_mode): ctx.dim = dim ctx.parallel_mode = parallel_mode output = all_gather(input_, dim, parallel_mode) return output @staticmethod def backward(ctx, output_grad): input_grad = reduce_scatter(output_grad, ctx.dim, ctx.parallel_mode) return input_grad, None, None def all_gather_tensor_3d(tensor: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""All-reduce the gradient in backward pass. Args: tensor (:class:`torch.tensor`): Input tensor. dim (int): Dimension to gather. parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): Parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ return _AllGatherTensor3D.apply(tensor, dim, parallel_mode) class _ReduceScatterTensor3D(torch.autograd.Function): @staticmethod def forward(ctx, input_, dim, parallel_mode): ctx.dim = dim ctx.parallel_mode = parallel_mode return reduce_scatter(input_, dim, parallel_mode) @staticmethod def backward(ctx, output_grad): input_grad = all_gather(output_grad, ctx.dim, ctx.parallel_mode) return input_grad, None, None def reduce_scatter_tensor_3d(tensor: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""Reduce-scatter the input. Args: tensor (:class:`torch.tensor`): Input tensor. dim (int): Dimension to scatter. parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): Parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ dim_size = tensor.size(dim) world_size = gpc.get_world_size(parallel_mode) assert dim_size % world_size == 0, \ f'The batch size ({dim_size}) is not a multiple of square of 3D depth ({world_size}).' return _ReduceScatterTensor3D.apply(tensor, dim, parallel_mode) class _ReduceByBatch3D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx, input_: Tensor, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, reduce_mean: bool = False) -> Tensor: output = all_reduce(input_, input_parallel_mode) output = all_reduce(output, weight_parallel_mode) ctx.reduce_mean = reduce_mean if reduce_mean: reduce_size = gpc.get_world_size(input_parallel_mode) * gpc.get_world_size(weight_parallel_mode) ctx.reduce_size = reduce_size return output.clone() / reduce_size return output.clone() @staticmethod @custom_bwd def backward(ctx, output_grad: Tensor) -> Tuple[Tensor, ...]: if ctx.reduce_mean: return output_grad / ctx.reduce_size, None, None, None else: return output_grad, None, None, None def reduce_by_batch_3d(tensor: Tensor, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, reduce_mean: bool = False) -> Tensor: r"""All-reduce the input from the model parallel region. Args: input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): weight parallel mode. reduce_mean (bool, optional): If set to ``True``, it will divide the output by (input parallel size * weight parallel size), default to False. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _ReduceByBatch3D.apply(tensor, input_parallel_mode, weight_parallel_mode, reduce_mean) class _BroadcastWeight3D_FromDiagonal(torch.autograd.Function): r"""broadcast weight from diagonal. Args: input_ (:class:`torch.tensor`): input matrix. input_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): input parallel mode. weight_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): weight parallel mode. output_parallel_mode (:class:`colossalai.context.parallel_mode.ParallelMode`): output parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx, input_: Tensor, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: ranks_in_group = gpc.get_ranks_in_group(input_parallel_mode) src_rank = ranks_in_group[gpc.get_local_rank(output_parallel_mode)] output = broadcast(input_, src_rank, input_parallel_mode) ctx.src_rank = src_rank ctx.input_parallel_mode = input_parallel_mode ctx.weight_parallel_mode = weight_parallel_mode ctx.output_parallel_mode = output_parallel_mode return output @staticmethod @custom_bwd def backward(ctx, output_grad: Tensor) -> Tuple[Tensor, ...]: input_grad = reduce(output_grad, ctx.src_rank, ctx.input_parallel_mode) if gpc.get_local_rank(ctx.input_parallel_mode) == gpc.get_local_rank(ctx.output_parallel_mode): input_grad = all_reduce(input_grad, ctx.weight_parallel_mode) else: input_grad = None return input_grad, None, None, None def broadcast_weight_3d_from_diagonal(tensor: Tensor, input_parallel_mode: ParallelMode, weight_parallel_mode: ParallelMode, output_parallel_mode: ParallelMode) -> Tensor: return _BroadcastWeight3D_FromDiagonal.apply(tensor, input_parallel_mode, weight_parallel_mode, output_parallel_mode)
from ._operation import reduce_by_batch_3d, split_batch_3d, split_tensor_3d from .layers import (Classifier3D, Embedding3D, LayerNorm3D, Linear3D, PatchEmbedding3D, VocabParallelClassifier3D, VocabParallelEmbedding3D) __all__ = [ 'reduce_by_batch_3d', 'split_tensor_3d', 'split_batch_3d', 'Linear3D', 'LayerNorm3D', 'PatchEmbedding3D', 'Classifier3D', 'Embedding3D', 'VocabParallelEmbedding3D', 'VocabParallelClassifier3D' ]
import math from collections import OrderedDict from typing import Callable import torch import torch.nn as nn import torch.nn.functional as F from colossalai.communication import all_reduce, broadcast from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D from colossalai.context import ParallelMode, seed from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from colossalai.nn import init as init from colossalai.nn.layer.base_layer import ParallelLayer from colossalai.registry import LAYERS from colossalai.utils.checkpointing import (broadcast_state_dict, gather_tensor_parallel_state_dict, partition_tensor_parallel_state_dict) from colossalai.utils.cuda import get_current_device from torch import Tensor from torch.nn import Parameter from ..utils import divide, set_tensor_parallel_attribute_by_partition, to_2tuple from ._operation import (all_gather_tensor_3d, broadcast_weight_3d_from_diagonal, classifier_3d, layernorm_3d, linear_3d, reduce_scatter_tensor_3d, split_tensor_3d) from ._utils import get_depth_from_env, get_last_group, get_parallel_mode_from_env, swap_in_out_group @LAYERS.register_module class LayerNorm3D(ParallelLayer): 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. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps: float = 1e-12, bias=True, dtype=None): super().__init__() self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D) self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) self.depth = get_depth_from_env() self.normalized_shape = normalized_shape self.normalized_shape_per_partition = divide(normalized_shape, self.depth) self.weight = Parameter( torch.ones(self.normalized_shape_per_partition, device=get_current_device(), dtype=dtype)) if bias: self.bias = Parameter(torch.zeros(self.normalized_shape_per_partition, device=get_current_device(), dtype=dtype)) else: self.bias = None self.variance_epsilon = eps self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self) -> None: set_tensor_parallel_attribute_by_partition(self.weight, self.depth) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.depth) def reset_parameters(self) -> None: init.ones_()(self.weight) if self.bias is not None: init.zeros_()(self.bias) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = partition_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: 0, bias_key: 0 }, 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) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias # gather in output groups if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = gather_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: return layernorm_3d(input_, self.weight, self.bias, self.normalized_shape, self.variance_epsilon, self.input_parallel_mode, self.weight_parallel_mode, self.output_parallel_mode) @LAYERS.register_module class Linear3D(ParallelLayer): 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>`_. """ def __init__(self, in_features: int, out_features: int, 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)): super().__init__() self.in_features = in_features self.out_features = out_features self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D) self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) self.depth = get_depth_from_env() self.in_features_per_partition = divide(in_features, self.depth) self.out_features_per_partition = divide(out_features, self.depth**2) self.bias_features_per_partition = divide(out_features, self.depth) self.weight = Parameter( torch.empty(self.in_features_per_partition, self.out_features_per_partition, device=get_current_device(), dtype=dtype)) if bias: self.bias = Parameter( torch.zeros(self.bias_features_per_partition, device=get_current_device(), dtype=dtype)) else: self.bias = None self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() swap_in_out_group() def _set_tensor_parallel_attributes(self) -> None: set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3) 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.out_features weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) weight_src_rank = gpc.get_ranks_in_group(self.weight_parallel_mode)[0] output_src_rank = gpc.get_ranks_in_group(self.output_parallel_mode)[0] broadcast(self.bias, weight_src_rank, self.weight_parallel_mode) broadcast(self.bias, output_src_rank, self.output_parallel_mode) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = partition_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # 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: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in weight groups local_state = partition_tensor_parallel_state_dict( local_state, self.weight_parallel_mode, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, 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: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in output groups if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = gather_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, 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) def forward(self, input_: Tensor) -> Tensor: return linear_3d(input_, self.weight, self.bias, self.input_parallel_mode, self.weight_parallel_mode, self.output_parallel_mode) @LAYERS.register_module class Classifier3D(ParallelLayer): 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>`_. """ 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)): 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) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) 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( torch.empty(self.num_classes, self.in_features_per_partition, device=get_current_device(), dtype=dtype)) 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 weight_src_rank = gpc.get_ranks_in_group(self.weight_parallel_mode)[0] output_src_rank = gpc.get_ranks_in_group(self.output_parallel_mode)[0] input_src_rank = gpc.get_ranks_in_group(self.input_parallel_mode)[0] if self.has_weight: weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) broadcast(self.weight, weight_src_rank, self.weight_parallel_mode) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) broadcast(self.bias, weight_src_rank, self.weight_parallel_mode) broadcast(self.bias, output_src_rank, self.output_parallel_mode) broadcast(self.bias, input_src_rank, self.input_parallel_mode) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = partition_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # 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) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = gather_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: return classifier_3d(input_, self.weight, self.bias, self.input_parallel_mode, self.weight_parallel_mode, self.output_parallel_mode) @LAYERS.register_module class VocabParallelClassifier3D(ParallelLayer): 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>`_. """ 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)): 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) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) self.depth = get_depth_from_env() self.in_features_per_partition = divide(in_features, self.depth) self.out_features_per_partition = divide(num_classes, self.depth**2) self.bias_features_per_partition = divide(num_classes, self.depth) if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter( torch.empty(self.out_features_per_partition, self.in_features_per_partition, device=get_current_device(), dtype=dtype)) self.has_weight = True if bias: self.bias = Parameter( torch.zeros(self.bias_features_per_partition, device=get_current_device(), dtype=dtype)) 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: set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3) 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) weight_src_rank = gpc.get_ranks_in_group(self.weight_parallel_mode)[0] output_src_rank = gpc.get_ranks_in_group(self.output_parallel_mode)[0] broadcast(self.bias, weight_src_rank, self.weight_parallel_mode) broadcast(self.bias, output_src_rank, self.output_parallel_mode) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = partition_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # 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, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in weight groups local_state = partition_tensor_parallel_state_dict( local_state, self.weight_parallel_mode, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, 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, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in output groups if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = gather_tensor_parallel_state_dict( local_state, self.output_parallel_mode, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: return linear_3d(input_, self.weight.transpose(0, 1), self.bias, self.input_parallel_mode, self.weight_parallel_mode, self.output_parallel_mode) @LAYERS.register_module class PatchEmbedding3D(ParallelLayer): 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>`_. """ 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_()): 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) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) self.patch_size = to_2tuple(patch_size) grid_size = to_2tuple(img_size // patch_size) num_patches = grid_size[0] * grid_size[1] self.embed_size = embed_size embed_size_per_partition = divide(embed_size, self.depth) self.flatten = flatten self.weight = nn.Parameter( torch.empty((embed_size_per_partition, in_chans, *self.patch_size), device=get_current_device(), dtype=dtype)) self.bias = nn.Parameter(torch.empty(embed_size_per_partition, device=get_current_device(), dtype=dtype)) self.cls_token = nn.Parameter( torch.zeros((1, 1, embed_size_per_partition), device=get_current_device(), dtype=dtype)) self.pos_embed = nn.Parameter( torch.zeros((1, num_patches + 1, embed_size_per_partition), device=get_current_device(), dtype=dtype)) 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) def _sync_grad_hook(self, grad) -> Tensor: grad = all_reduce(grad.clone(), self.input_parallel_mode) grad = all_reduce(grad, self.weight_parallel_mode) 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) weight_src_rank = gpc.get_ranks_in_group(self.weight_parallel_mode)[0] input_src_rank = gpc.get_ranks_in_group(self.input_parallel_mode)[0] broadcast(self.weight, weight_src_rank, self.weight_parallel_mode) broadcast(self.bias, weight_src_rank, self.weight_parallel_mode) broadcast(self.pos_embed, weight_src_rank, self.weight_parallel_mode) broadcast(self.weight, input_src_rank, self.input_parallel_mode) broadcast(self.bias, input_src_rank, self.input_parallel_mode) broadcast(self.pos_embed, input_src_rank, self.input_parallel_mode) self.weight.register_hook(self._sync_grad_hook) 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) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' cls_token_key = prefix + 'cls_token' pos_embed_key = prefix + 'pos_embed' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = partition_tensor_parallel_state_dict( local_state, self.output_parallel_mode, 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 }, ) # 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) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): 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 }) # gather in output groups if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: local_state = gather_tensor_parallel_state_dict( local_state, self.output_parallel_mode, 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 }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: input_ = split_tensor_3d(input_, 0, self.weight_parallel_mode) input_ = split_tensor_3d(input_, 0, self.input_parallel_mode) output = F.conv2d(input_, self.weight, self.bias, stride=self.patch_size) if self.flatten: output = output.flatten(2).transpose(1, 2) # BCHW -> BNC 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): 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>`_ """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): 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) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) 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( torch.empty((num_embeddings, embed_dim_per_partition), device=get_current_device(), dtype=dtype)) 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) 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() weight_src_rank = gpc.get_ranks_in_group(self.weight_parallel_mode)[0] broadcast(self.weight, weight_src_rank, self.weight_parallel_mode) 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) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: 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) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) # gather in output groups if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: 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) def forward(self, input_: Tensor) -> Tensor: input_ = split_tensor_3d(input_, 0, self.weight_parallel_mode) input_ = split_tensor_3d(input_, 0, self.input_parallel_mode) weight = broadcast_weight_3d_from_diagonal(self.weight, self.input_parallel_mode, self.weight_parallel_mode, self.output_parallel_mode) output = F.embedding(input_, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) return output @LAYERS.register_module class VocabParallelEmbedding3D(torch.nn.Module): 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>`_. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): 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) self.output_parallel_mode = get_last_group(self.input_parallel_mode, self.weight_parallel_mode) self.num_embeddings_per_partition = divide(self.num_embeddings, self.depth**2) self.embed_dim_per_partition = divide(self.embed_dim, self.depth) vocab_parallel_rank = gpc.get_local_rank(self.input_parallel_mode) 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 self.weight = Parameter( torch.empty((self.num_embeddings_per_partition, self.embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() env.vocab_parallel = True def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.depth**3) 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: if self.padding_idx is not None and \ self.padding_idx >= self.vocab_start_index and self.padding_idx < self.vocab_end_index: with torch.no_grad(): self.weight[self.padding_idx - self.vocab_start_index].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: 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}, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' 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 if gpc.get_local_rank(self.input_parallel_mode) == 0 and \ gpc.get_local_rank(self.weight_parallel_mode) == 0: 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) 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 weight = all_gather_tensor_3d(self.weight, 0, self.weight_parallel_mode) output_parallel = F.embedding(masked_input, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) output_parallel[input_mask, :] = 0. output = reduce_scatter_tensor_3d(output_parallel, 0, self.input_parallel_mode) return output
from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D, OUTPUT_GROUP_3D from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from torch import Tensor def get_depth_from_env() -> int: try: depth = env.depth_3d assert depth > 0, 'DEPTH must be greater than zero' return depth except KeyError as e: raise EnvironmentError('DEPTH is not found in the current environment, ' 'please make sure that you have used the correct process group initializer') def get_parallel_mode_from_env(group): assert group in [INPUT_GROUP_3D, WEIGHT_GROUP_3D, OUTPUT_GROUP_3D], \ f'{group} is not valid for 3D tensor parallelism.' return getattr(env, group) def get_last_group(a, b): mapping = { ParallelMode.PARALLEL_3D_INPUT: 'A', ParallelMode.PARALLEL_3D_WEIGHT: 'B', ParallelMode.PARALLEL_3D_OUTPUT: 'C', } res = chr(ord('A') + ord('B') + ord('C') - ord(mapping[a]) - ord(mapping[b])) if res == 'A': return ParallelMode.PARALLEL_3D_INPUT elif res == 'B': return ParallelMode.PARALLEL_3D_WEIGHT elif res == 'C': return ParallelMode.PARALLEL_3D_OUTPUT def swap_in_out_group(): env.input_group_3d, env.output_group_3d = env.output_group_3d, env.input_group_3d def dbg_check_shape(tensor: Tensor, shape: tuple): rank = gpc.get_global_rank() if rank == 0: print(tensor.shape) assert tensor.shape == shape, \ '{} does not match {}'.format(tensor.shape, shape)
from .common import (ACT2FN, CheckpointModule, _ntuple, divide, get_tensor_parallel_mode, set_tensor_parallel_attribute_by_partition, set_tensor_parallel_attribute_by_size, to_2tuple) __all__ = [ 'CheckpointModule', 'divide', 'ACT2FN', 'set_tensor_parallel_attribute_by_size', 'set_tensor_parallel_attribute_by_partition', 'get_tensor_parallel_mode', '_ntuple', 'to_2tuple' ]
#!/usr/bin/env python # -*- encoding: utf-8 -*- import collections.abc from itertools import repeat import numpy as np import torch from colossalai.constants import IS_TENSOR_PARALLEL, NUM_PARTITIONS from colossalai.global_variables import tensor_parallel_env as env from colossalai.utils import checkpoint from torch import Tensor, nn class CheckpointModule(nn.Module): def __init__(self, checkpoint: bool = True, offload : bool = False): super().__init__() self.checkpoint = checkpoint self._use_checkpoint = checkpoint self._offload = offload def _forward(self, *args, **kwargs): raise NotImplementedError('CheckpointModule should implement _forward method instead of origin forward') def forward(self, *args, **kwargs): if self._use_checkpoint: return checkpoint(self._forward, self._offload, *args, **kwargs) else: return self._forward(*args, **kwargs) def train(self, mode: bool = True): self._use_checkpoint = self.checkpoint return super().train(mode=mode) def eval(self): self._use_checkpoint = False return super().eval() def divide(numerator, denominator): """Only allow exact division. Args: numerator (int): Numerator of the division. denominator (int): Denominator of the division. Returns: int: the result of exact division. """ assert denominator != 0, 'denominator can not be zero' assert numerator % denominator == 0, \ '{} is not divisible by {}'.format(numerator, denominator) return numerator // denominator def swish(x: Tensor) -> Tensor: return x * torch.sigmoid(x) ACT2FN = {"gelu": torch.nn.functional.gelu, "relu": torch.nn.functional.relu, "swish": swish} def set_tensor_parallel_attribute_by_size(param, size): setattr(param, IS_TENSOR_PARALLEL, True) setattr(param, NUM_PARTITIONS, size // np.prod(param.shape)) def set_tensor_parallel_attribute_by_partition(param, num_partitions): setattr(param, IS_TENSOR_PARALLEL, True) setattr(param, NUM_PARTITIONS, num_partitions) def get_tensor_parallel_mode(): return env.mode # From PyTorch internals def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable): return x return tuple(repeat(x, n)) return parse to_2tuple = _ntuple(2)
import torch try: import fused_mix_prec_layer_norm_cuda except: fused_mix_prec_layer_norm_cuda = None class FusedLayerNormAffineFunction1D(torch.autograd.Function): r"""Layernorm Args: input: input matrix. weight: weight matrix. bias: bias matrix. normalized_shape: 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: a value added to the denominator for numerical stability """ @staticmethod def forward(ctx, input, weight, bias, normalized_shape, eps): ctx.normalized_shape = normalized_shape ctx.eps = eps input_ = input.contiguous() weight_ = weight.contiguous() bias_ = bias.contiguous() output, mean, invvar = fused_mix_prec_layer_norm_cuda.forward_affine(input_, ctx.normalized_shape, weight_, bias_, ctx.eps) ctx.save_for_backward(input_, weight_, bias_, mean, invvar) return output @staticmethod def backward(ctx, grad_output): input_, weight_, bias_, mean, invvar = ctx.saved_tensors grad_input = grad_weight = grad_bias = None grad_input, grad_weight, grad_bias \ = fused_mix_prec_layer_norm_cuda.backward_affine( grad_output.contiguous(), mean, invvar, input_, ctx.normalized_shape, weight_, bias_, ctx.eps) return grad_input, grad_weight, grad_bias, None, None
from .layers import (Classifier1D, Dropout1D, Embedding1D, LayerNorm1D, Linear1D, Linear1D_Col, Linear1D_Row, PatchEmbedding1D, VocabParallelClassifier1D, VocabParallelEmbedding1D) __all__ = [ 'Linear1D', 'Linear1D_Col', 'Linear1D_Row', 'Embedding1D', 'Dropout1D', 'Classifier1D', 'VocabParallelClassifier1D', 'VocabParallelEmbedding1D', 'LayerNorm1D', 'PatchEmbedding1D' ]
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math from collections import OrderedDict from typing import Callable, Tuple import torch import torch.nn.functional as F from colossalai.communication import broadcast from colossalai.context import ParallelMode, seed from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from colossalai.kernel import LayerNorm from colossalai.nn import init as init from colossalai.registry import LAYERS from colossalai.utils.checkpointing import (broadcast_state_dict, gather_tensor_parallel_state_dict, partition_tensor_parallel_state_dict) from colossalai.utils.cuda import get_current_device from torch import Tensor from torch.nn.parameter import Parameter from ..vanilla import VanillaPatchEmbedding, VanillaLayerNorm from ..base_layer import ParallelLayer from ..colossalai_layer._utils import ColossalaiModule from ..utils import divide, set_tensor_parallel_attribute_by_partition from ._utils import (gather_forward_split_backward, get_parallel_input, reduce_grad, reduce_input, set_parallel_input, split_forward_gather_backward) @LAYERS.register_module class Linear1D(ColossalaiModule): r"""Linear layer for 1D 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. gather_output (bool, optional): Whether to call all-gather on output, defaults to False. skip_bias_add (bool, optional): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion, defaults to False 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>`_. """ def __init__(self, in_features: int, out_features: int, bias: bool = True, dtype: torch.dtype = None, gather_output: bool = False, 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)): parallel_input = get_parallel_input() if not parallel_input: layer = Linear1D_Col(in_features, out_features, bias=bias, dtype=dtype, gather_output=gather_output, skip_bias_add=skip_bias_add, weight_initializer=weight_initializer, bias_initializer=bias_initializer) else: layer = Linear1D_Row(in_features, out_features, bias=bias, dtype=dtype, parallel_input=parallel_input, skip_bias_add=skip_bias_add, weight_initializer=weight_initializer, bias_initializer=bias_initializer) super().__init__(layer) @LAYERS.register_module class LayerNorm1D(ColossalaiModule): r""" Layer Normalization for colossalai 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): a value added to the denominator for numerical stability, defaults to 1e-05. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps=1e-05, bias=True, dtype=None): norm = VanillaLayerNorm(normalized_shape, eps=eps, bias=bias, dtype=dtype) super().__init__(norm) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 local_state = broadcast_state_dict(local_state, ParallelMode.PARALLEL_1D) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): if gpc.get_local_rank(ParallelMode.TENSOR) == 0: super()._save_to_state_dict(destination, prefix, keep_vars) @LAYERS.register_module class Classifier1D(ParallelLayer): r"""RowLinear with given weight. Classifier of 1D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes self.parallel_input = get_parallel_input() # Divide the weight matrix along the last dimension. self.input_size_per_partition = divide(in_features, gpc.tensor_parallel_size) # Parameters. # Initialize weight. factory_kwargs = {'device': get_current_device(), 'dtype': dtype} if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter(torch.empty(self.num_classes, self.input_size_per_partition, **factory_kwargs)) self.has_weight = True if bias: self.bias = Parameter(torch.empty(self.num_classes, **factory_kwargs)) else: self.bias = None with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() set_parallel_input(False) env.vocab_parallel = False def reset_parameters(self, weight_initializer, bias_initializer) -> None: 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) broadcast(self.bias, gpc.get_ranks_in_group(ParallelMode.PARALLEL_1D)[0], ParallelMode.PARALLEL_1D) def _set_tensor_parallel_attributes(self): if self.has_weight: num_partition = gpc.get_world_size(ParallelMode.TENSOR) set_tensor_parallel_attribute_by_partition(self.weight, num_partition) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: # Set up backprop all-reduce. if self.parallel_input: assert input_.shape[-1] == self.weight.shape[-1], \ 'Invalid shapes in Classifier1D forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1]) input_ = input_ else: assert divide(input_.shape[-1], gpc.tensor_parallel_size) == self.weight.shape[-1], \ 'Invalid shapes in Classifier1D forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1] * gpc.tensor_parallel_size) input_ = split_forward_gather_backward(input_, ParallelMode.PARALLEL_1D, dim=-1) output_parallel = F.linear(input_, self.weight) output = reduce_input(output_parallel, ParallelMode.PARALLEL_1D) if self.bias is not None: output = output + self.bias return output @LAYERS.register_module class VocabParallelClassifier1D(ParallelLayer): r"""ColLinear with given weight. Classifier of 1D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes self.parallel_input = get_parallel_input() # Divide the weight matrix along the last dimension. self.num_classes_per_partition = divide(num_classes, gpc.tensor_parallel_size) # Parameters. # Initialize weight. factory_kwargs = {'device': get_current_device(), 'dtype': dtype} if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter(torch.empty(self.num_classes_per_partition, self.in_features, **factory_kwargs)) self.has_weight = True if bias: self.bias = Parameter(torch.empty(self.num_classes_per_partition, **factory_kwargs)) else: self.bias = None with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() set_parallel_input(False) env.vocab_parallel = True def reset_parameters(self, weight_initializer, bias_initializer) -> None: 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _set_tensor_parallel_attributes(self): num_partition = gpc.get_world_size(ParallelMode.TENSOR) if self.has_weight: set_tensor_parallel_attribute_by_partition(self.weight, num_partition) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, num_partition) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: assert input_.shape[-1] == self.weight.shape[-1], \ 'Invalid shapes in VocabParallelClassifier1D forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1]) # Set up backprop all-reduce. input_parallel = reduce_grad(input_, ParallelMode.PARALLEL_1D) # Matrix multiply. output = F.linear(input_parallel, self.weight, self.bias) return output @LAYERS.register_module class Linear1D_Col(ParallelLayer): r"""Linear layer with column parallelism. The linear layer is defined as :math:`Y = XA + b`. A is parallelized along its second dimension as :math:`A = [A_1, ..., A_p]`. 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. gather_output (bool, optional): If true, call all-gather on output and make Y available to all GPUs, otherwise, every GPU will have its output which is :math:`Y_i = XA_i`, defaults to False skip_bias_add (bool, optional): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion, defaults to Fals 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>`_. """ def __init__(self, in_features: int, out_features: int, bias: bool = True, dtype: torch.dtype = None, gather_output: bool = False, 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)): super().__init__() # Keep input parameters self.in_features = in_features self.out_features = out_features self.gather_output = gather_output self.skip_bias_add = skip_bias_add if skip_bias_add and not bias: raise ValueError('cannot skip bias addition if bias is None') self.out_features_per_partition = divide(out_features, gpc.tensor_parallel_size) # Parameters. # Initialize weight. factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter(torch.empty(self.out_features_per_partition, self.in_features, **factory_kwargs)) if bias: self.bias = Parameter(torch.empty(self.out_features_per_partition, **factory_kwargs)) else: self.bias = None with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() is_parallel_output = not self.gather_output set_parallel_input(is_parallel_output) def reset_parameters(self, weight_initializer, bias_initializer) -> None: fan_in, fan_out = self.in_features, self.out_features weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _set_tensor_parallel_attributes(self): num_partition = gpc.get_world_size(ParallelMode.TENSOR) set_tensor_parallel_attribute_by_partition(self.weight, num_partition) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, num_partition) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if self.bias is not None: bias = state_dict.pop(bias_key, None) if bias is not None: local_state[bias_key] = bias local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tuple[Tensor, Tensor]: assert input_.shape[-1] == self.weight.shape[-1], \ 'Invalid shapes in Linear1D_Col forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1]) # Set up backprop all-reduce. input_parallel = reduce_grad(input_, ParallelMode.PARALLEL_1D) # Matrix multiply. bias = self.bias if not self.skip_bias_add else None output_parallel = F.linear(input_parallel, self.weight, bias) if self.gather_output: # All-gather across the partitions. output = gather_forward_split_backward(output_parallel, ParallelMode.PARALLEL_1D, dim=-1) else: output = output_parallel if self.skip_bias_add: return output, self.bias else: return output @LAYERS.register_module class Linear1D_Row(ParallelLayer): r""" Linear layer with row 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. parallel_input (bool, optional): If set to ``True``, it's assumed that the input is split, defaults to False. skip_bias_add (bool, optional): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion, defaults to Fals 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>`_. """ def __init__(self, in_features: int, out_features: int, bias: bool = True, dtype: torch.dtype = None, parallel_input: bool = True, 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)): super().__init__() # Keep input parameters self.in_features = in_features self.out_features = out_features self.parallel_input = parallel_input self.skip_bias_add = skip_bias_add if skip_bias_add and not bias: raise ValueError('cannot skip bias addition if bias is None') # Divide the weight matrix along the last dimension. self.input_size_per_partition = divide(in_features, gpc.tensor_parallel_size) # Parameters. # Initialize weight. factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter(torch.empty(self.out_features, self.input_size_per_partition, **factory_kwargs)) if bias: self.bias = Parameter(torch.empty(self.out_features, **factory_kwargs)) else: self.bias = None with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() set_parallel_input(False) def reset_parameters(self, weight_initializer, bias_initializer) -> None: fan_in, fan_out = self.in_features, self.out_features weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) broadcast(self.bias, gpc.get_ranks_in_group(ParallelMode.PARALLEL_1D)[0], ParallelMode.PARALLEL_1D) def _set_tensor_parallel_attributes(self): num_partition = gpc.get_world_size(ParallelMode.TENSOR) set_tensor_parallel_attribute_by_partition(self.weight, num_partition) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 if self.bias is not None: bias = state_dict.pop(bias_key, None) if bias is not None: local_state[bias_key] = bias local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: # Set up backprop all-reduce. if self.parallel_input: assert input_.shape[-1] == self.weight.shape[-1], \ 'Invalid shapes in Linear1D_Row forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1]) input_ = input_ else: assert divide(input_.shape[-1], gpc.tensor_parallel_size) == self.weight.shape[-1], \ 'Invalid shapes in Linear1D_Row forward: input={}, weight={}. Expected last dim of input {}.'.format( input_.shape, self.weight.shape, self.weight.shape[-1] * gpc.tensor_parallel_size) input_ = split_forward_gather_backward(input_, ParallelMode.PARALLEL_1D, dim=-1) output_parallel = F.linear(input_, self.weight) output = reduce_input(output_parallel, ParallelMode.PARALLEL_1D) if not self.skip_bias_add: if self.bias is not None: output = output + self.bias return output else: return output, self.bias @LAYERS.register_module class Embedding1D(ParallelLayer): r"""Embedding for 1D 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>`_ """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): super().__init__() self.num_embeddings = num_embeddings self.embed_dim = embedding_dim embed_dim_per_partition = divide(embedding_dim, gpc.tensor_parallel_size) self.padding_idx = padding_idx self.embed_args = args self.embed_kwargs = kwargs self.weight = Parameter( torch.empty((num_embeddings, embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() set_parallel_input(False) def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, gpc.tensor_parallel_size) 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: if self.padding_idx is not None: with torch.no_grad(): self.weight[self.padding_idx].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' 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 local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={weight_key: -1}, partition_states={weight_key: True}) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={weight_key: -1}, partition_states={weight_key: True}, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: output_parallel = F.embedding(input_, self.weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) output = gather_forward_split_backward(output_parallel, ParallelMode.PARALLEL_1D, dim=-1) return output @LAYERS.register_module class VocabParallelEmbedding1D(torch.nn.Module): 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>`_. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): 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 tensor_parallel_size = gpc.get_world_size(ParallelMode.PARALLEL_1D) tensor_parallel_rank = gpc.get_local_rank(ParallelMode.PARALLEL_1D) self.num_embeddings_per_partition = divide(num_embeddings, tensor_parallel_size) self.vocab_start_index = tensor_parallel_rank * self.num_embeddings_per_partition self.vocab_end_index = self.vocab_start_index + self.num_embeddings_per_partition self.weight = Parameter( torch.empty((self.num_embeddings_per_partition, self.embed_dim), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() set_parallel_input(False) env.vocab_parallel = True def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, gpc.tensor_parallel_size) 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: if self.padding_idx is not None and \ self.padding_idx >= self.vocab_start_index and self.padding_idx < self.vocab_end_index: with torch.no_grad(): self.weight[self.padding_idx - self.vocab_start_index].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() weight_key = prefix + 'weight' 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 local_state = partition_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={weight_key: 0}, partition_states={weight_key: True}) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) local_state = gather_tensor_parallel_state_dict(local_state, ParallelMode.PARALLEL_1D, dims={weight_key: 0}, partition_states={weight_key: True}, keep_vars=keep_vars) destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: # Build the mask. input_mask = (input_ < self.vocab_start_index) | (input_ >= self.vocab_end_index) # Mask the input. masked_input = input_.clone() - self.vocab_start_index masked_input[input_mask] = 0 output_parallel = F.embedding(masked_input, self.weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) # Mask the output embedding. output_parallel[input_mask, :] = 0. # Reduce across all the model parallel GPUs. output = reduce_input(output_parallel, ParallelMode.PARALLEL_1D) return output @LAYERS.register_module class Dropout1D(ParallelLayer): """Dropout layer of 1D parallelism. Args: p (float, optional): probability of an element to be zeroed, defaults 0.5. inplace (bool, optional): whether to do dropout in-place, default to be False. """ def __init__(self, p: float = 0.5, inplace: bool = False): super().__init__() self.parallel_input = get_parallel_input() self.p = p self.inplace = inplace def forward(self, input_: Tensor) -> Tensor: if self.parallel_input: with seed(ParallelMode.TENSOR): output = F.dropout(input_, self.p, self.training, self.inplace) else: output = F.dropout(input_, self.p, self.training, self.inplace) return output @LAYERS.register_module class PatchEmbedding1D(ColossalaiModule): """ 2D Image to Patch Embedding :param img_size: image size :type img_size: int :param patch_size: patch size :type patch_size: int :param in_chans: number of channels of input image :type in_chans: int :param embed_size: size of embedding :type embed_size: int :param dtype: The dtype of parameters, defaults to None :type dtype: torch.dtype, optional :param flatten: whether to flatten output tensor, defaults to True :type flatten: bool, optional :param weight_initializer: The intializer of weight, defaults to kaiming uniform initializer :type weight_initializer: typing.Callable, optional :param bias_initializer: The intializer of bias, defaults to xavier uniform initializer :type bias_initializer: typing.Callable, optional :param position_embed_initializer: The intializer of position embedding, defaults to zero :type position_embed_initializer: typing.Callable, optional """ def __init__(self, img_size: int, patch_size: int, in_chans: int, embed_size: int, dtype: torch.dtype = None, flatten: bool = True, 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_()): embed = VanillaPatchEmbedding(img_size, patch_size, in_chans, embed_size, dtype=dtype, flatten=flatten, weight_initializer=weight_initializer, bias_initializer=bias_initializer, position_embed_initializer=position_embed_initializer) super().__init__(embed) def _load_from_state_dict(self, state_dict, prefix, *args): local_state = OrderedDict() param_keys = [prefix + 'weight', prefix + 'bias', prefix + 'cls_token', prefix + 'pos_embed'] if gpc.get_local_rank(ParallelMode.TENSOR) == 0: for key in param_keys: param = state_dict.pop(key, None) if param is not None: local_state[key] = param local_state = broadcast_state_dict(local_state, ParallelMode.PARALLEL_1D) super()._load_from_state_dict(local_state, prefix, *args) def _save_to_state_dict(self, destination, prefix, keep_vars): if gpc.get_local_rank(ParallelMode.TENSOR) == 0: super()._save_to_state_dict(destination, prefix, keep_vars)
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch import torch.distributed as dist from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from ..utils import divide def set_parallel_input(input_parallel: bool): env.parallel_input_1d = input_parallel def get_parallel_input(): return env.parallel_input_1d def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank): index_f = rank * per_partition_vocab_size index_l = index_f + per_partition_vocab_size return index_f, index_l def vocab_range_from_global_vocab_size(global_vocab_size, rank, world_size): per_partition_vocab_size = divide(global_vocab_size, world_size) return vocab_range_from_per_partition_vocab_size(per_partition_vocab_size, rank) def _reduce(input_, parallel_mode): # skip if only one rank involved if gpc.get_world_size(parallel_mode) == 1: return input_ dist.all_reduce(input_, group=gpc.get_group(parallel_mode)) return input_ def _split(input_, parallel_mode, dim=-1): # skip if only one rank involved world_size = gpc.get_world_size(parallel_mode) if world_size == 1: return input_ # Split along last dimension. dim_size = input_.size(dim) assert dim_size % world_size == 0, \ f'The dimension to split ({dim_size}) is not a multiple of world size ({world_size}), ' \ f'cannot split tensor evenly' tensor_list = torch.split(input_, dim_size // world_size, dim=dim) rank = gpc.get_local_rank(parallel_mode) output = tensor_list[rank].contiguous() return output def _gather(input_, parallel_mode, dim=-1): # skip if only one rank involved world_size = gpc.get_world_size(parallel_mode) if world_size == 1: return input_ # all gather rank = gpc.get_local_rank(parallel_mode) tensor_list = [torch.empty_like(input_) for _ in range(world_size)] tensor_list[rank] = input_ torch.distributed.all_gather(tensor_list, input_, group=gpc.get_group(parallel_mode)) # concat output = torch.cat(tensor_list, dim=dim).contiguous() return output class _ReduceGrad(torch.autograd.Function): """ Pass the input to the model parallel region. Args: input_: input matrix. parallel_mode: parallel mode. """ @staticmethod def symbolic(graph, input_): return input_ @staticmethod def forward(ctx, input_, parallel_mode): ctx.mode = parallel_mode return input_ @staticmethod def backward(ctx, grad_output): return _reduce(grad_output, ctx.mode), None class _ReduceInput(torch.autograd.Function): """ All-reduce the input from the model parallel region. Args: input_: input matrix. parallel_mode: parallel mode. """ @staticmethod def symbolic(graph, input_): return _reduce(input_) @staticmethod def forward(ctx, input_, parallel_mode): return _reduce(input_, parallel_mode) @staticmethod def backward(ctx, grad_output): return grad_output, None class _SplitForwardGatherBackward(torch.autograd.Function): """ Split the input and keep only the corresponding chuck to the rank. Args: input_: input matrix. parallel_mode: parallel mode. dim: dimension """ @staticmethod def symbolic(graph, input_): return _split(input_) @staticmethod def forward(ctx, input_, parallel_mode, dim): ctx.mode = parallel_mode ctx.dim = dim return _split(input_, parallel_mode, dim) @staticmethod def backward(ctx, grad_output): return _gather(grad_output, ctx.mode, ctx.dim), None, None class _GatherForwardSplitBackward(torch.autograd.Function): """Gather the input from model parallel region and concatenate. Args: input_: input matrix. parallel_mode: parallel mode. dim: dimension """ @staticmethod def symbolic(graph, input_): return _gather(input_) @staticmethod def forward(ctx, input_, parallel_mode, dim): ctx.mode = parallel_mode ctx.dim = dim return _gather(input_, parallel_mode, dim) @staticmethod def backward(ctx, grad_output): return _split(grad_output, ctx.mode, ctx.dim), None, None def reduce_grad(input_, parallel_mode): return _ReduceGrad.apply(input_, parallel_mode) def reduce_input(input_, parallel_mode): return _ReduceInput.apply(input_, parallel_mode) def split_forward_gather_backward(input_, parallel_mode, dim): return _SplitForwardGatherBackward.apply(input_, parallel_mode, dim) def gather_forward_split_backward(input_, parallel_mode, dim): return _GatherForwardSplitBackward.apply(input_, parallel_mode, dim)
from typing import Any, Optional, Tuple import torch import torch.distributed as dist from colossalai.communication.collective import (all_gather, all_reduce, reduce, reduce_scatter) from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.utils import get_current_device from torch import Tensor from torch.cuda.amp import custom_bwd, custom_fwd from colossalai.global_variables import tensor_parallel_env as env def matmul_2d( a, b, summa_dim, out_shape, row_rank=None, col_rank=None, row_parallel_mode=ParallelMode.PARALLEL_2D_ROW, col_parallel_mode=ParallelMode.PARALLEL_2D_COL, ): r"""Matrix multiplication for 2D parallelism. Args: a (:class:`torch.tensor`): matrix :math:`A`. b (:class:`torch.tensor`): matrix :math:`B`. summa_dim (int): dimension of SUMMA fo 2D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`, optional): row parallel mode, defaults to ParallelMode.PARALLEL_2D_ROW. col_parallel_mode (:class:`colossalai.context.ParallelMode`, optional): column parallel mode, defaults to ParallelMode.PARALLEL_2D_COL. Returns: :class:`torch.tensor`: :math:`C = AB`. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ if row_rank is None: row_rank = gpc.get_local_rank(col_parallel_mode) if col_rank is None: col_rank = gpc.get_local_rank(row_parallel_mode) data_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.DATA) else gpc.get_local_rank(ParallelMode.DATA) pipeline_parallel_rank = 0 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_local_rank( ParallelMode.PIPELINE) pipeline_parallel_size = 1 if not gpc.is_initialized(ParallelMode.PIPELINE) else gpc.get_world_size( ParallelMode.PIPELINE) tensor_parallel_size = summa_dim**2 return Matmul_AB_2D(a, b, summa_dim, out_shape, row_rank, col_rank, row_parallel_mode, col_parallel_mode, data_parallel_rank, pipeline_parallel_rank, pipeline_parallel_size, tensor_parallel_size) class _Classifier2D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, A: Tensor, B: Tensor, bias: Optional[Tensor], summa_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: A = A.clone().detach() A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) B_temp = all_gather(B, -1, col_parallel_mode) if ctx: ctx.save_for_backward(A, B_temp) C = torch.matmul(A, B_temp.transpose(0, 1)) C = all_reduce(C, row_parallel_mode) ctx.use_bias = bias is not None if bias is not None: C = C + bias out = C.reshape(out_shape) if ctx: ctx.summa_dim = summa_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = torch.matmul(output_grad, B) A_grad = A_grad.reshape(ctx.A_shape) B_grad = torch.matmul(output_grad.reshape(-1, output_grad.shape[-1]).transpose(0, 1), A) B_grad = reduce_scatter(B_grad, -1, ctx.col_parallel_mode) B_grad = B_grad.reshape(ctx.B_shape) if ctx.use_bias: bias_grad = torch.sum(output_grad, dim=tuple(range(output_grad.ndim - 1))) bias_grad = all_reduce(bias_grad, ctx.col_parallel_mode) else: bias_grad = None return A_grad, B_grad, bias_grad, None, None, None, None, None, None, None, None, None, None def classifier_2d(A: Tensor, B: Tensor, bias: Optional[Tensor], summa_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: r"""2D parallel classifier. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. bias (:class:`torch.tensor`, optional): matrix of bias. summa_dim (int): dimension of SUMMA fo 2D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Classifier2D.apply(A, B, bias, summa_dim, out_shape, row_rank, col_rank, row_parallel_mode, col_parallel_mode, data_parallel_rank, pipeline_parallel_rank, pipeline_parallel_size, tensor_parallel_size) class Matmul_AB_2D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = AB`. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. summa_dim (int): dimension of SUMMA fo 2D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, A: Tensor, B: Tensor, summa_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: # A: [b / q, s, h / q] -> [(b * s) / q, h / q] # B: [h / q, s / q] # C: [b / q, s, s / q] -> [(b * s) / q, s / q] assert A.shape[-1] == B.shape[-2], \ 'Invalid shapes: A={}, B={} for AB.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[0], B.shape[-1]) C = torch.zeros(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases A_list = [torch.empty_like(A) for _ in range(2)] B_list = [torch.empty_like(B) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_a = summa_dim * row_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_b = col_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opa = [None] * 2 opb = [None] * 2 A_list[0].copy_(A) B_list[0].copy_(B) opa[0] = dist.broadcast(A_list[0], src=src_a, group=row_group, async_op=True) opb[0] = dist.broadcast(B_list[0], src=src_b, group=col_group, async_op=True) cur = 0 for i in range(summa_dim): if i != summa_dim - 1: A_list[1 - cur].copy_(A) opa[1 - cur] = dist.broadcast(A_list[1 - cur], src=src_a + 1, group=row_group, async_op=True) B_list[1 - cur].copy_(B) opb[1 - cur] = dist.broadcast(B_list[1 - cur], src=src_b + summa_dim, group=col_group, async_op=True) if opa[cur] is not None: opa[cur].wait() if opb[cur] is not None: opb[cur].wait() torch.addmm(C, A_list[cur], B_list[cur], out=C) cur = 1 - cur src_a += 1 src_b += summa_dim out = C.reshape(out_shape) if ctx: ctx.summa_dim = summa_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_ABT_2D.apply(output_grad, B, ctx.summa_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_ATB_2D.apply(A, output_grad, ctx.summa_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None class Matmul_ABT_2D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = AB^T` Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. summa_dim (int): dimension of SUMMA fo 2D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. column parallel mode, defaults to ParallelMode.PARALLEL_2D_COL. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, A: Tensor, B: Tensor, summa_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: assert A.shape[-1] == B.shape[-1], \ 'Invalid shapes: A={}, B={} for ABT.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[0], B.shape[0]) C = torch.empty(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases B_list = [torch.empty_like(B) for _ in range(2)] C_list = [torch.empty_like(C) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_b = col_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_c = summa_dim * row_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opb = [None] * 2 opr = [None] * 2 B_list[0].copy_(B) opb[0] = dist.broadcast(B_list[0], src=src_b, group=col_group, async_op=True) cur = 0 for i in range(summa_dim): if i != summa_dim - 1: B_list[1 - cur].copy_(B) opb[1 - cur] = dist.broadcast(B_list[1 - cur], src=src_b + summa_dim, group=col_group, async_op=True) if opr[cur] is not None: opr[cur].wait() if i - 2 == col_rank: C.copy_(C_list[cur]) if opb[cur] is not None: opb[cur].wait() torch.matmul(A, B_list[cur].transpose(0, 1), out=C_list[cur]) opr[cur] = dist.reduce(C_list[cur], dst=src_c, group=row_group, async_op=True) cur = 1 - cur src_b += summa_dim src_c += 1 for op in opr: op.wait() if summa_dim - 2 == col_rank: C.copy_(C_list[cur]) if summa_dim - 1 == col_rank: C.copy_(C_list[1 - cur]) out = C.reshape(out_shape) if ctx: ctx.summa_dim = summa_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_AB_2D.apply(output_grad, B, ctx.summa_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_ATB_2D.apply(output_grad, A, ctx.summa_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None class Matmul_ATB_2D(torch.autograd.Function): r"""Matrix multiplication for :math:`C = A^TB`. Args: A (:class:`torch.tensor`): matrix :math:`A`. B (:class:`torch.tensor`): matrix :math:`B`. summa_dim (int): dimension of SUMMA fo 2D parallelism. out_shape (:class:`torch.size`): shape of output tensor. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_. """ @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, A: Tensor, B: Tensor, summa_dim: int, out_shape: Tuple[int, ...], row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: assert A.shape[-2] == B.shape[-2], \ 'Invalid shapes: A={}, B={} for ATB.'.format(A.shape, B.shape) if ctx: ctx.save_for_backward(A, B) A_shape = A.shape A = A.reshape((-1, A_shape[-1])) B_shape = B.shape B = B.reshape((-1, B_shape[-1])) C_shape = (A.shape[-1], B.shape[-1]) C = torch.empty(C_shape, dtype=A.dtype, device=get_current_device()) # use circular buffer to store the communication tensor # 2 is enough for all cases A_list = [torch.empty_like(A) for _ in range(2)] C_list = [torch.empty_like(C) for _ in range(2)] row_group = gpc.get_group(row_parallel_mode) col_group = gpc.get_group(col_parallel_mode) src_a = summa_dim * row_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size src_c = col_rank + data_parallel_rank * pipeline_parallel_size * tensor_parallel_size + \ pipeline_parallel_rank * tensor_parallel_size opa = [None] * 2 opr = [None] * 2 A_list[0].copy_(A) opa[0] = dist.broadcast(A_list[0], src=src_a, group=row_group, async_op=True) cur = 0 for i in range(summa_dim): if i != summa_dim - 1: A_list[1 - cur].copy_(A) opa[1 - cur] = dist.broadcast(A_list[1 - cur], src=src_a + 1, group=row_group, async_op=True) if opr[cur] is not None: opr[cur].wait() if i - 2 == row_rank: C.copy_(C_list[cur]) if opa[cur] is not None: opa[cur].wait() torch.matmul(A_list[cur].transpose(0, 1), B, out=C_list[cur]) opr[cur] = dist.reduce(C_list[cur], dst=src_c, group=col_group, async_op=True) cur = 1 - cur src_a += 1 src_c += summa_dim for op in opr: op.wait() if summa_dim - 2 == row_rank: C.copy_(C_list[cur]) if summa_dim - 1 == row_rank: C.copy_(C_list[1 - cur]) out = C.reshape(out_shape) if ctx: ctx.summa_dim = summa_dim ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.A_shape = A_shape ctx.B_shape = B_shape ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size return out @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: A, B = ctx.saved_tensors with torch.no_grad(): A_grad = Matmul_ABT_2D.apply(B, output_grad, ctx.summa_dim, ctx.A_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) B_grad = Matmul_AB_2D.apply(A, output_grad, ctx.summa_dim, ctx.B_shape, ctx.row_rank, ctx.col_rank, ctx.row_parallel_mode, ctx.col_parallel_mode, ctx.data_parallel_rank, ctx.pipeline_parallel_rank, ctx.pipeline_parallel_size, ctx.tensor_parallel_size) return A_grad, B_grad, None, None, None, None, None, None, None, None, None, None class _Add_Bias_2D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward( ctx: Any, input_: Tensor, bias: Tensor, output_size_per_partition: int, row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, skip_bias_add: bool, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int, ) -> Tensor: bias_temp = all_gather(bias, -1, col_parallel_mode) ctx.row_rank = row_rank ctx.col_rank = col_rank ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode ctx.bias = skip_bias_add ctx.data_parallel_rank = data_parallel_rank ctx.pipeline_parallel_rank = pipeline_parallel_rank ctx.pipeline_parallel_size = pipeline_parallel_size ctx.tensor_parallel_size = tensor_parallel_size if skip_bias_add: return bias_temp else: output = input_ + bias_temp return output @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: col_parallel_mode = ctx.col_parallel_mode if ctx.bias: grad = reduce_scatter(output_grad, -1, col_parallel_mode) return None, grad, None, None, None, None, None, None, None, None, None, None else: reduce_dim = tuple(range(output_grad.ndim - 1)) reduce = torch.sum(output_grad, dim=reduce_dim) grad = reduce_scatter(reduce, -1, col_parallel_mode) return output_grad, grad, None, None, None, None, None, None, None, None, None, None def add_bias_2d(input_: Tensor, bias: Tensor, output_size_per_partition: int, row_rank: int, col_rank: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode, skip_bias_add: bool, data_parallel_rank: int, pipeline_parallel_rank: int, pipeline_parallel_size: int, tensor_parallel_size: int) -> Tensor: r"""Matrix add bias: :math:`C = A + b`. Args: input_ (:class:`torch.tensor`): matrix :math:`A`. bias (:class:`torch.tensor`): matrix :math:`B`. output_size_per_partition (int): size of output per partition. row_rank (int, optional): the rank of row, defaults to None. col_rank (int, optional): the rank of column, defaults to None. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. skip_bias_add (bool): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion. data_parallel_rank (int): data parallel rank. pipeline_parallel_rank (int): pipeline parallel rank pipeline_parallel_size (int): pipeline parallel size. tensor_parallel_size (int): tensor parallel size. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Add_Bias_2D.apply(input_, bias, output_size_per_partition, row_rank, col_rank, row_parallel_mode, col_parallel_mode, skip_bias_add, data_parallel_rank, pipeline_parallel_rank, pipeline_parallel_size, tensor_parallel_size) class _Layernorm_2D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx: Any, input_: Tensor, E_x: Tensor, Var_x: Tensor, hidden_size: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode) -> Tensor: input_ = input_ - E_x # in here, input = x - E[x], Var_x = 1 / sqrt(Var[x] + eps) ctx.normalized_shape = hidden_size output = input_ * Var_x ctx.save_for_backward(output, Var_x) ctx.row_parallel_mode = row_parallel_mode ctx.col_parallel_mode = col_parallel_mode return output @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: row_parallel_mode = ctx.row_parallel_mode col_parallel_mode = ctx.col_parallel_mode x, Var_x = ctx.saved_tensors # in here, Var_x = 1 / sqrt(Var[x] + eps), x = (x - E[x]) * Var_x output_grad_sum = torch.sum(output_grad, dim=-1, keepdim=True) torch.distributed.all_reduce(output_grad_sum, group=gpc.get_group(row_parallel_mode)) output_grad_sum /= ctx.normalized_shape output_grad_mul_x_sum = torch.sum(output_grad * x, dim=-1, keepdim=True) torch.distributed.all_reduce(output_grad_mul_x_sum, group=gpc.get_group(row_parallel_mode)) output_grad_mul_x_sum /= ctx.normalized_shape input_grad = output_grad.clone() input_grad -= x * output_grad_mul_x_sum input_grad -= output_grad_sum input_grad *= Var_x return input_grad, None, None, None, None, None def layernorm_2d(input_: Tensor, E_x: Tensor, Var_x: Tensor, hidden_size: int, row_parallel_mode: ParallelMode, col_parallel_mode: ParallelMode) -> Tensor: r"""Layernorm. Args: input_ (:class:`torch.tensor`): input matrix. E_x (:class:`torch.tensor`): mean. Var_x (:class:`torch.tensor`): variance. hidden_size (int): hidden size. row_parallel_mode (:class:`colossalai.context.ParallelMode`): row parallel mode. col_parallel_mode (:class:`colossalai.context.ParallelMode`): column parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _Layernorm_2D.apply(input_, E_x, Var_x, hidden_size, row_parallel_mode, col_parallel_mode) class _AllGatherTensor2D(torch.autograd.Function): @staticmethod @custom_fwd(cast_inputs=torch.float16) def forward(ctx: Any, inputs: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: ctx.dim = dim ctx.parallel_mode = parallel_mode outputs = all_gather(inputs, dim, parallel_mode) return outputs @staticmethod @custom_bwd def backward(ctx: Any, output_grad: Tensor) -> Tuple[Tensor, ...]: grad = reduce_scatter(output_grad, ctx.dim, ctx.parallel_mode) return grad.contiguous(), None, None def all_gather_tensor_2d(tensor: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""All gather the tensor of 2D parallelism. Args: tensor (:class:`torch.tensor`): Input tensor. dim (int): Dimension to gather. parallel_mode (:class:`colossalai.context.ParallelMode`): The parallel mode tensor used. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _AllGatherTensor2D.apply(tensor, dim, parallel_mode) def split_batch_2d(input_: Tensor, dim: int = 0) -> Tensor: """Splits 2D tensor in specified dimension across cols. Args: input_ (:class:`torch.tensor`): Input tensor. dim (int): Specified dimension in which to split. Returns: :class:`torch.tensor`: The tensor has been split. """ dim_size = input_.size(dim) world_size = gpc.get_world_size(ParallelMode.PARALLEL_2D_COL) if world_size <= 1: return input_ assert dim_size % world_size == 0, \ f'The batch size ({dim_size}) is not a multiple of 2D size ({world_size}).' return torch.chunk(input_, gpc.get_world_size(ParallelMode.PARALLEL_2D_COL), dim=dim)[gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)].contiguous() class _ReduceTensor2D(torch.autograd.Function): @staticmethod def forward(ctx, input_, parallel_mode): return all_reduce(input_, parallel_mode) @staticmethod def backward(ctx, output_grad): return output_grad, None def reduce_tensor_2d(input_: Tensor, parallel_mode: ParallelMode) -> Tensor: r"""All-reduce the input. Args: input_ (:class:`torch.tensor`): Input tensor. parallel_mode (:class:`colossalai.context.ParallelMode`): The parallel mode tensor used. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ return _ReduceTensor2D.apply(input_, parallel_mode) class _ReduceScatterTensor2D(torch.autograd.Function): @staticmethod def forward(ctx, input_, dim, parallel_mode): ctx.dim = dim ctx.parallel_mode = parallel_mode return reduce_scatter(input_, dim, parallel_mode) @staticmethod def backward(ctx, output_grad): return all_gather(output_grad, ctx.dim, ctx.parallel_mode), None, None def reduce_scatter_tensor_2d(tensor: Tensor, dim: int, parallel_mode: ParallelMode) -> Tensor: r"""Reduce-scatter the input. Args: tensor (:class:`torch.tensor`): Input tensor. dim (int): Dimension to reduce. parallel_mode (:class:`colossalai.context.ParallelMode`): The parallel mode tensor used. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ dim_size = tensor.size(dim) world_size = gpc.get_world_size(parallel_mode) assert dim_size % world_size == 0, \ f'The batch size ({dim_size}) is not a multiple of 2D size ({world_size}).' return _ReduceScatterTensor2D.apply(tensor, dim, parallel_mode) class _ReduceByBatch2D(torch.autograd.Function): @staticmethod def symbolic(graph, input_, reduce_mean: bool = False): output = all_reduce(input_, ParallelMode.PARALLEL_2D_COL) if reduce_mean: reduce_size = gpc.get_world_size(ParallelMode.PARALLEL_2D_COL) return output / reduce_size return output @staticmethod @custom_fwd(cast_inputs=torch.float32) def forward(ctx, input_, reduce_mean: bool = False): output = all_reduce(input_, ParallelMode.PARALLEL_2D_COL) ctx.reduce_mean = reduce_mean if reduce_mean: reduce_size = gpc.get_world_size(ParallelMode.PARALLEL_2D_COL) ctx.reduce_size = reduce_size return output.clone() / reduce_size return output.clone() @staticmethod @custom_bwd def backward(ctx, output_grad): if ctx.reduce_mean: return output_grad / ctx.reduce_size, None else: return output_grad, None def reduce_by_batch_2d(input_, reduce_mean: bool = False) -> Tensor: r"""All-reduce the input from the model parallel region. Args: input_ (:class:`torch.tensor`): input matrix. reduce_mean (bool, optional): If set to ``True``, it will divide the output by column parallel size, default to False. """ return _ReduceByBatch2D.apply(input_, reduce_mean)
from ._operation import reduce_by_batch_2d, split_batch_2d from .layers import (Classifier2D, Embedding2D, LayerNorm2D, Linear2D, PatchEmbedding2D, VocabParallelClassifier2D, VocabParallelEmbedding2D) __all__ = [ 'split_batch_2d', 'reduce_by_batch_2d', 'Linear2D', 'LayerNorm2D', 'Classifier2D', 'PatchEmbedding2D', 'Embedding2D', 'VocabParallelEmbedding2D', 'VocabParallelClassifier2D' ]
import math from collections import OrderedDict from typing import Callable import torch import torch.nn as nn import torch.nn.functional as F from colossalai.communication import broadcast from colossalai.context import ParallelMode, seed from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from colossalai.nn import init as init from colossalai.registry import LAYERS from colossalai.utils.checkpointing import gather_tensor_parallel_state_dict, partition_tensor_parallel_state_dict from colossalai.utils.cuda import get_current_device from torch import Tensor from torch.nn import Parameter from ..base_layer import ParallelLayer from ..utils import divide, set_tensor_parallel_attribute_by_partition, to_2tuple from ._operation import (Matmul_AB_2D, Matmul_ABT_2D, add_bias_2d, all_gather_tensor_2d, classifier_2d, layernorm_2d, reduce_scatter_tensor_2d, split_batch_2d) from ._utils import assert_summa_initialization, get_summa_dim_from_env @LAYERS.register_module class Linear2D(ParallelLayer): r"""Linear layer for 2D 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. skip_bias_add (bool, optional): If set to ``True``, it will skip bias add for linear layer, which is preserved for kernel fusion, defaults to False. 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>`_. """ 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)): super().__init__() self.in_features = in_features self.out_features = out_features self.skip_bias_add = skip_bias_add # parallel settings assert_summa_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW) self.summa_dim = get_summa_dim_from_env() # partitioning dimension self.input_size_per_partition = divide(self.in_features, self.summa_dim) self.hidden_size_per_partition = divide(self.out_features, self.summa_dim) # create weight, shape: [k/q, h/q] factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter( torch.empty(self.input_size_per_partition, self.hidden_size_per_partition, **factory_kwargs)) # create bias, shape: [h/q] if bias: self.bias = Parameter(torch.empty(divide(self.out_features, self.summa_dim**2), **factory_kwargs)) else: self.register_parameter('bias', None) # initialize parameters with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2) def reset_parameters(self, weight_initializer, bias_initializer) -> None: fan_in, fan_out = self.in_features, self.out_features weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, 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) def forward(self, x: Tensor) -> Tensor: # input: [m/q, n/q, k/q] # output: [m/q, n/q, h/q] out_shape = x.shape[:-1] + (self.hidden_size_per_partition, ) output = Matmul_AB_2D.apply(x, self.weight, self.summa_dim, out_shape, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) if self.bias is not None: if self.skip_bias_add: bias = add_bias_2d(None, self.bias, self.hidden_size_per_partition, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output, bias else: output = add_bias_2d(output, self.bias, self.hidden_size_per_partition, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, False, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output else: return output @LAYERS.register_module class LayerNorm2D(ParallelLayer): r"""Layer Normalization for 2D 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-05. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps: float = 1e-05, bias=True, dtype=None): super().__init__() # layer norm config self.normalized_shape = normalized_shape self.variance_epsilon = eps # parallel setting assert_summa_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW) self.summa_dim = get_summa_dim_from_env() # partitioning dimension self.partitioned_partition = divide(normalized_shape, self.summa_dim**2) # create parameters factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = Parameter(torch.ones(self.partitioned_partition, **factory_kwargs)) if bias: self.bias = Parameter(torch.zeros(self.partitioned_partition, **factory_kwargs)) else: self.bias = None self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 # partition in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' local_state = OrderedDict({weight_key: self.weight}) if self.bias is not None: local_state[bias_key] = self.bias # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, x: Tensor) -> Tensor: with torch.no_grad(): E_x = torch.sum(x, dim=-1, keepdim=True) # [b/q, s, 1] torch.distributed.all_reduce(E_x, group=gpc.get_group(ParallelMode.PARALLEL_2D_ROW)) E_x /= self.normalized_shape # Var_x in the block below is the sum of input^2 Var_x = torch.sum(x * x, dim=-1, keepdim=True) # [b/q, s, 1] torch.distributed.all_reduce(Var_x, group=gpc.get_group(ParallelMode.PARALLEL_2D_ROW)) Var_x /= self.normalized_shape Var_x = Var_x - E_x * E_x # variance of x [b/q, s, 1] # this time 1/sqrt(Var_x + epsilon) Var_x = 1.0 / torch.sqrt(Var_x + self.variance_epsilon) output = layernorm_2d(x, E_x, Var_x, self.normalized_shape, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL) scale = add_bias_2d(None, self.weight, self.partitioned_partition, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) if self.bias is not None: bias = add_bias_2d(None, self.bias, self.partitioned_partition, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, True, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) output = torch.addcmul(bias, scale, output) else: output = torch.mul(scale, output) return output @LAYERS.register_module class PatchEmbedding2D(ParallelLayer): 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>`_. """ 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_()): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) assert_summa_initialization() self.summa_dim = get_summa_dim_from_env() 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] self.flatten = flatten self.embed_size = embed_size self.embed_size_per_partition = embed_size // (self.summa_dim**2) with seed(ParallelMode.TENSOR): self.weight = Parameter( torch.empty((self.embed_size_per_partition, in_chans, *self.patch_size), device=get_current_device(), dtype=dtype)) self.bias = Parameter(torch.empty(self.embed_size_per_partition, device=get_current_device(), dtype=dtype)) self.cls_token = Parameter( torch.zeros((1, 1, self.embed_size_per_partition), device=get_current_device(), dtype=dtype)) self.pos_embed = Parameter( torch.zeros((1, self.num_patches + 1, self.embed_size_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer, bias_initializer, position_embed_initializer) self._set_tensor_parallel_attribute() def _set_tensor_parallel_attribute(self): set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2) set_tensor_parallel_attribute_by_partition(self.cls_token, self.summa_dim**2) set_tensor_parallel_attribute_by_partition(self.pos_embed, self.summa_dim**2) def reset_parameters(self, weight_initializer, bias_initializer, position_embed_initializer): 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) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' cls_token_key = prefix + 'cls_token' pos_embed_key = prefix + 'pos_embed' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, 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 }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, 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 }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): 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 }) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, 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 }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, 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 }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: input_ = split_batch_2d(input_) B, C, H, W = input_.shape assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." weight = all_gather_tensor_2d(self.weight, 0, ParallelMode.PARALLEL_2D_COL) bias = all_gather_tensor_2d(self.bias, 0, ParallelMode.PARALLEL_2D_COL) output = F.conv2d(input_, weight, bias, stride=self.patch_size) if self.flatten: output = output.flatten(2).transpose(1, 2) # BCHW -> BNC cls_token = all_gather_tensor_2d(self.cls_token, -1, ParallelMode.PARALLEL_2D_COL) pos_embed = all_gather_tensor_2d(self.pos_embed, -1, ParallelMode.PARALLEL_2D_COL) cls_token = cls_token.expand(output.shape[0], -1, -1) output = torch.cat((cls_token, output), dim=1) output = output + pos_embed return output @LAYERS.register_module class Embedding2D(ParallelLayer): r"""Embedding for 2D 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>`_ """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): super().__init__() assert_summa_initialization() self.summa_dim = get_summa_dim_from_env() self.num_embeddings = num_embeddings self.embed_dim = embedding_dim embed_dim_per_partition = divide(embedding_dim, self.summa_dim**2) self.padding_idx = padding_idx self.embed_args = args self.embed_kwargs = kwargs self.weight = Parameter( torch.empty((num_embeddings, embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) 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: if self.padding_idx is not None: with torch.no_grad(): self.weight[self.padding_idx].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={weight_key: -1}, partition_states={weight_key: True}, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={weight_key: -1}, partition_states={weight_key: True}, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={weight_key: -1}, partition_states={weight_key: True}, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, 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) def forward(self, input_: Tensor) -> Tensor: input_ = split_batch_2d(input_) weight = all_gather_tensor_2d(self.weight, -1, ParallelMode.PARALLEL_2D_COL) output = F.embedding(input_, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) return output @LAYERS.register_module class VocabParallelEmbedding2D(torch.nn.Module): 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>`_. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: torch.dtype = None, weight_initializer: Callable = init.normal_(), *args, **kwargs): 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 assert_summa_initialization() self.summa_dim = get_summa_dim_from_env() self.num_embeddings_per_partition = divide(self.num_embeddings, self.summa_dim) self.embed_dim_per_partition = divide(self.embed_dim, self.summa_dim) tensor_parallel_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) self.vocab_start_index = tensor_parallel_rank * self.num_embeddings_per_partition self.vocab_end_index = self.vocab_start_index + self.num_embeddings_per_partition self.weight = Parameter( torch.empty((self.num_embeddings_per_partition, self.embed_dim_per_partition), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer) self._set_tensor_parallel_attributes() env.vocab_parallel = True def _set_tensor_parallel_attributes(self): set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) 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: if self.padding_idx is not None and \ self.padding_idx >= self.vocab_start_index and self.padding_idx < self.vocab_end_index: with torch.no_grad(): self.weight[self.padding_idx - self.vocab_start_index].fill_(0) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={weight_key: -1}, partition_states={weight_key: True}, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={weight_key: 0}, partition_states={weight_key: True}, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' local_state = OrderedDict({weight_key: self.weight}) # gather in column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={weight_key: 0}, partition_states={weight_key: True}, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, 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) def forward(self, input_: Tensor) -> Tensor: 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 output_parallel = F.embedding(masked_input, self.weight, self.padding_idx, *self.embed_args, **self.embed_kwargs) output_parallel[input_mask, :] = 0. output = reduce_scatter_tensor_2d(output_parallel, 0, ParallelMode.PARALLEL_2D_COL) return output @LAYERS.register_module class Classifier2D(ParallelLayer): r"""Classifier for 2D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes assert_summa_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW) self.summa_dim = get_summa_dim_from_env() # partitioning dimension self.input_size_per_partition = divide(self.in_features, self.summa_dim**2) if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter( torch.empty(self.num_classes, self.input_size_per_partition, device=get_current_device(), dtype=dtype)) 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): if self.has_weight: set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) def reset_parameters(self, weight_initializer, bias_initializer) -> None: with seed(ParallelMode.TENSOR): fan_in, fan_out = self.in_features, self.num_classes col_src_rank = gpc.get_ranks_in_group(ParallelMode.PARALLEL_2D_COL)[0] row_src_rank = gpc.get_ranks_in_group(ParallelMode.PARALLEL_2D_ROW)[0] if self.has_weight: weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) broadcast(self.bias, col_src_rank, ParallelMode.PARALLEL_2D_COL) broadcast(self.bias, row_src_rank, ParallelMode.PARALLEL_2D_ROW) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: False }, keep_vars=keep_vars, ) if gpc.get_local_rank(ParallelMode.TENSOR) == 0: destination.update(local_state) def forward(self, input_: Tensor) -> Tensor: out_shape = input_.shape[:-1] + (self.num_classes, ) return classifier_2d(input_, self.weight, self.bias, self.summa_dim, out_shape, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) @LAYERS.register_module class VocabParallelClassifier2D(ParallelLayer): r"""Vocab parallel classifier layer for 2D 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>`_. """ 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)): super().__init__() self.in_features = in_features self.num_classes = num_classes # parallel setting assert_summa_initialization() self.row_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) self.col_rank = gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW) self.summa_dim = get_summa_dim_from_env() # partitioning dimension self.input_size_per_partition = divide(in_features, self.summa_dim) self.output_size_per_partition = divide(num_classes, self.summa_dim) # create weight, shape: [k/q, h/q] factory_kwargs = {'device': get_current_device(), 'dtype': dtype} if weight is not None: self.weight = weight self.has_weight = False else: self.weight = Parameter( torch.empty(self.output_size_per_partition, self.input_size_per_partition, **factory_kwargs)) self.has_weight = True # create bias, shape: [h/q] if bias: self.bias = Parameter(torch.empty(divide(self.num_classes, self.summa_dim**2), **factory_kwargs)) else: self.bias = None # initialize parameters with seed(ParallelMode.TENSOR): self.reset_parameters(weight_initializer, bias_initializer) self._set_tensor_parallel_attributes() env.vocab_parallel = True def _set_tensor_parallel_attributes(self): if self.has_weight: set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2) if self.bias is not None: set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2) def reset_parameters(self, weight_initializer, bias_initializer) -> None: 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): local_state = OrderedDict() weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) # partition in column groups local_state = partition_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, ) super()._load_from_state_dict(local_state, prefix, *args, **kwargs) def _save_to_state_dict(self, destination, prefix, keep_vars): weight_key = prefix + 'weight' bias_key = prefix + 'bias' 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 column groups local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_COL, dims={ weight_key: 0, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, keep_vars=keep_vars, ) # gather in row groups if gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL) == 0: local_state = gather_tensor_parallel_state_dict( local_state, ParallelMode.PARALLEL_2D_ROW, dims={ weight_key: -1, bias_key: 0 }, partition_states={ weight_key: True, bias_key: True }, 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) def forward(self, x: Tensor) -> Tensor: # input: [m/q, n/q, k/q] # output: [m/q, n/q, h/q] out_shape = x.shape[:-1] + (self.output_size_per_partition, ) output = Matmul_ABT_2D.apply(x, self.weight, self.summa_dim, out_shape, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) if self.bias is not None: output = add_bias_2d(output, self.bias, self.output_size_per_partition, self.row_rank, self.col_rank, ParallelMode.PARALLEL_2D_ROW, ParallelMode.PARALLEL_2D_COL, False, self.data_parallel_rank, self.pipeline_parallel_rank, self.pipeline_parallel_size, self.tensor_parallel_size) return output
from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env def get_summa_dim_from_env() -> int: try: summa_dim = env.summa_dim assert summa_dim > 0, 'SUMMA_DIM must be larger than zero' return summa_dim except KeyError as e: raise EnvironmentError('SUMMA_DIM is not found in the current environment, ' 'please make sure that you have used the correct process group initializer') def assert_summa_initialization(): assert gpc.is_initialized(ParallelMode.PARALLEL_2D_COL) and \ gpc.is_initialized(ParallelMode.PARALLEL_2D_ROW), \ 'Both TWO_DIMENSION_COL and TWO_DIMENSION_ROW must be initialized by the process group initializer'
import math from typing import Callable from colossalai.utils import get_current_device from torch import dtype, nn from ... import init as init from ..parallel_1d import Embedding1D, PatchEmbedding1D, VocabParallelEmbedding1D from ..parallel_2d import Embedding2D, PatchEmbedding2D, VocabParallelEmbedding2D from ..parallel_2p5d import Embedding2p5D, PatchEmbedding2p5D, VocabParallelEmbedding2p5D from ..parallel_3d import Embedding3D, PatchEmbedding3D, VocabParallelEmbedding3D from ..utils import get_tensor_parallel_mode from ..vanilla import VanillaPatchEmbedding from ._utils import ColossalaiModule _parallel_embedding = { '1d': Embedding1D, '2d': Embedding2D, '2.5d': Embedding2p5D, '3d': Embedding3D, } _vocab_parallel_embedding = { '1d': VocabParallelEmbedding1D, '2d': VocabParallelEmbedding2D, '2.5d': VocabParallelEmbedding2p5D, '3d': VocabParallelEmbedding3D } _parallel_patchembedding = { None: VanillaPatchEmbedding, '1d': PatchEmbedding1D, '2d': PatchEmbedding2D, '2.5d': PatchEmbedding2p5D, '3d': PatchEmbedding3D } class Embedding(ColossalaiModule): r"""Embedding for colossalai. 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>`_ """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int = None, dtype: dtype = None, weight_initializer: Callable = init.normal_(), vocab_parallel_limit: int = 2048, *args, **kwargs) -> None: tensor_parallel = get_tensor_parallel_mode() if tensor_parallel is None: embed = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx, *args, **kwargs).to(dtype).to(get_current_device()) weight_initializer(embed.weight, fan_in=num_embeddings, fan_out=embedding_dim) elif num_embeddings <= vocab_parallel_limit: embed = _parallel_embedding[tensor_parallel]( num_embeddings, embedding_dim, padding_idx=padding_idx, dtype=dtype, weight_initializer=weight_initializer, *args, **kwargs, ) else: embed = _vocab_parallel_embedding[tensor_parallel]( num_embeddings, embedding_dim, padding_idx=padding_idx, dtype=dtype, weight_initializer=weight_initializer, *args, **kwargs, ) super().__init__(embed) class PatchEmbedding(ColossalaiModule): """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>`_. """ def __init__( self, img_size: int, patch_size: int, in_chans: int, embed_size: int, dtype: dtype = None, flatten: bool = True, 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_() ) -> None: tensor_parallel = get_tensor_parallel_mode() embed = _parallel_patchembedding[tensor_parallel]( img_size, patch_size, in_chans, embed_size, dtype=dtype, flatten=flatten, weight_initializer=weight_initializer, bias_initializer=bias_initializer, position_embed_initializer=position_embed_initializer, ) super().__init__(embed)
import math import inspect from typing import Callable from colossalai.utils import get_current_device from torch import dtype, nn from ... import init as init from ..parallel_1d import * from ..parallel_2d import * from ..parallel_2p5d import * from ..parallel_3d import * from ..utils import get_tensor_parallel_mode from ..vanilla import * from ._utils import ColossalaiModule _parallel_linear = {'1d': Linear1D, '2d': Linear2D, '2.5d': Linear2p5D, '3d': Linear3D} _parallel_classifier = { None: VanillaClassifier, '1d': Classifier1D, '2d': Classifier2D, '2.5d': Classifier2p5D, '3d': Classifier3D } _vocab_parallel_classifier = { '1d': VocabParallelClassifier1D, '2d': VocabParallelClassifier2D, '2.5d': VocabParallelClassifier2p5D, '3d': VocabParallelClassifier3D } class Linear(ColossalaiModule): """Linear layer of colossalai. 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. Note: ``kwargs`` would contain different parameters when you use different parallelisms. The ``kwargs`` should contain parameters below: :: Linear1D: gather_output: bool (optional, default to be false) skip_bias_add: bool (optional, default to be false) Linear2D: skip_bias_add: bool (optional, default to be false) Linear2p5D: skip_bias_add: bool (optional, default to be false) Linear3D: None More details about ``initializer`` please refer to `init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_. """ def __init__(self, in_features: int, out_features: int, bias: bool = True, dtype: dtype = None, weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)), bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1), **kwargs) -> None: tensor_parallel = get_tensor_parallel_mode() if tensor_parallel is None: layer = nn.Linear(in_features, out_features, bias=bias).to(dtype).to(get_current_device()) weight_initializer(layer.weight, fan_in=in_features, fan_out=out_features) if layer.bias is not None: bias_initializer(layer.bias, fan_in=in_features) else: linear_cls = _parallel_linear[tensor_parallel] gather_output = kwargs.pop('gather_output', None) if 'gather_output' in inspect.signature(linear_cls.__init__).parameters.keys(): # gather_out arg is available kwargs['gather_output'] = gather_output layer = linear_cls( in_features, out_features, bias=bias, dtype=dtype, weight_initializer=weight_initializer, bias_initializer=bias_initializer, **kwargs, ) super().__init__(layer) class Classifier(ColossalaiModule): """Classifier layer of colossalai. 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>`_. """ def __init__(self, in_features: int, num_classes: int, weight: nn.Parameter = None, bias: bool = True, dtype: dtype = None, weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)), bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1), vocab_parallel_limit: int = 2048) -> None: tensor_parallel = get_tensor_parallel_mode() if num_classes <= vocab_parallel_limit or tensor_parallel is None: layer = _parallel_classifier[tensor_parallel]( in_features, num_classes, weight=weight, bias=bias, dtype=dtype, weight_initializer=weight_initializer, bias_initializer=bias_initializer, ) else: layer = _vocab_parallel_classifier[tensor_parallel]( in_features, num_classes, weight=weight, bias=bias, dtype=dtype, weight_initializer=weight_initializer, bias_initializer=bias_initializer, ) super().__init__(layer)
from ._utils import partition_batch from .dropout import Dropout from .embedding import Embedding, PatchEmbedding from .linear import Classifier, Linear from .normalization import LayerNorm __all__ = ['Linear', 'Classifier', 'Embedding', 'PatchEmbedding', 'LayerNorm', 'Dropout', 'partition_batch']
import torch.nn as nn from colossalai.context import ParallelMode, seed from ..parallel_1d import * from ..utils import get_tensor_parallel_mode from ._utils import ColossalaiModule class Dropout(ColossalaiModule): """Dropout layer of colossalai. Args: p (float, optional): probability of an element to be zeroed, defaults 0.5. inplace (bool, optional): whether to do dropout in-place, default to be False. """ def __init__(self, p: float = 0.5, inplace: bool = False) -> None: tensor_parallel = get_tensor_parallel_mode() if tensor_parallel == "1d": drop = Dropout1D(p, inplace) else: drop = nn.Dropout(p, inplace) super().__init__(drop, tensor_parallel=tensor_parallel) def forward(self, *args): if self.tensor_parallel in [None, '1d']: return self._forward_func(*args) else: with seed(ParallelMode.TENSOR): return self._forward_func(*args)
from colossalai.utils import get_current_device from torch import nn from ..parallel_1d import LayerNorm1D from ..parallel_2d import LayerNorm2D from ..parallel_2p5d import LayerNorm2p5D from ..parallel_3d import LayerNorm3D from ..utils import get_tensor_parallel_mode from ..vanilla import VanillaLayerNorm from ._utils import ColossalaiModule _parallel_layernorm = { None: VanillaLayerNorm, "1d": LayerNorm1D, "2d": LayerNorm2D, "2.5d": LayerNorm2p5D, "3d": LayerNorm3D, } class LayerNorm(ColossalaiModule): r"""Layer Normalization for colossalai. 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): a value added to the denominator for numerical stability, defaults to 1e-05. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps=1e-05, bias=True, dtype=None) -> None: tensor_parallel = get_tensor_parallel_mode() if tensor_parallel is None: norm = nn.LayerNorm(normalized_shape, eps=eps).to(dtype).to(get_current_device()) else: norm = _parallel_layernorm[tensor_parallel](normalized_shape, eps=eps, dtype=dtype) super().__init__(norm)
import torch.nn as nn from torch import Tensor from ..parallel_2d._operation import split_batch_2d from ..parallel_2p5d._operation import split_batch_2p5d from ..parallel_3d._operation import split_batch_3d from ..utils import get_tensor_parallel_mode _parallel_split_batch = {'2d': split_batch_2d, '2.5d': split_batch_2p5d, '3d': split_batch_3d} def partition_batch(input_) -> Tensor: tensor_parallel_mode = get_tensor_parallel_mode() if tensor_parallel_mode in _parallel_split_batch: if isinstance(input_, dict): return {k: _parallel_split_batch[tensor_parallel_mode](v) for k, v in input_.items()} else: return _parallel_split_batch[tensor_parallel_mode](input_) else: return input_ class ColossalaiModule(nn.Module): def __init__(self, module: nn.Module, **kwargs): super().__init__() # copy values self.__dict__ = module.__dict__.copy() # copy methods for name, attr in module.__class__.__dict__.items(): if name not in ['__init__', 'forward'] and callable(attr): setattr(self, name, getattr(module, name)) self._forward_func = module.forward for k, v in kwargs.items(): setattr(self, k, v) def forward(self, *args): return self._forward_func(*args)
from .layers import (DropPath, VanillaClassifier, VanillaLayerNorm, VanillaPatchEmbedding, WrappedDropout, WrappedDropPath) __all__ = [ "VanillaLayerNorm", "VanillaPatchEmbedding", "VanillaClassifier", "DropPath", "WrappedDropout", "WrappedDropPath" ]
import math from typing import Callable import torch import torch.nn.functional as F from colossalai.context import seed from colossalai.nn import init as init from colossalai.registry import LAYERS from colossalai.utils.cuda import get_current_device from torch import Tensor from torch import nn as nn from ..utils import to_2tuple def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. Args: drop_prob (float, optional): probability of dropping path, defaults 0.0. training (bool, optional): whether in training progress, defaults False. """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0], ) + (1, ) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output class DropPath(nn.Module): """ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py Args: drop_prob (float, optional): probability of dropping path, defaults None. """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) class WrappedDropout(nn.Module): r"""Same as torch.nn.Dropout. But it is wrapped with the context of seed manager. During training, randomly zeroes some elements of the input tensor with probability p using samples from a Bernoulli distribution. Each channel will be zeroed out independently on every forward call. Furthermore, the outputs are scaled by a factor of 1/(1-p) during training. This means that during evaluation the module simply computes an identity function. Args: p (float, optional): probability of an element to be zeroed, defaults 0.5. inplace (bool, optional): whether to do dropout in-place, default to be False. mode (:class:`colossalai.context.ParallelMode`): The chosen parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ def __init__(self, p: float = 0.5, inplace: bool = False, mode=None): super().__init__() if p < 0 or p > 1: raise ValueError("dropout probability has to be between 0 and 1, " "but got {}".format(p)) self.p = p self.inplace = inplace if mode is None: self.func = self.nonefunc else: self.func = self.normalfunc self.mode = mode def nonefunc(self, inputs): return F.dropout(inputs, self.p, self.training, self.inplace) def normalfunc(self, inputs): with seed(self.mode): return F.dropout(inputs, self.p, self.training, self.inplace) def forward(self, inputs): return self.func(inputs) class WrappedDropPath(nn.Module): r"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Here, it is wrapped with the context of seed manager. Args: p (float, optional): probability of dropping path, defaults 0.0. mode (:class:`colossalai.context.ParallelMode`): The chosen parallel mode. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ def __init__(self, p: float = 0., mode=None): super().__init__() self.p = p self.mode = mode if self.mode is None: self.func = self.nonefunc else: self.func = self.normalfunc self.mode = mode def nonefunc(self, inputs): return drop_path(inputs, self.p, self.training) def normalfunc(self, inputs): with seed(self.mode): return drop_path(inputs, self.p, self.training) def forward(self, inputs): return self.func(inputs) @LAYERS.register_module class VanillaPatchEmbedding(nn.Module): 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>`_. """ 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_()): super().__init__() 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] self.flatten = flatten self.weight = nn.Parameter( torch.empty((embed_size, in_chans, *self.patch_size), device=get_current_device(), dtype=dtype)) self.bias = nn.Parameter(torch.empty(embed_size, device=get_current_device(), dtype=dtype)) self.cls_token = nn.Parameter(torch.zeros((1, 1, embed_size), device=get_current_device(), dtype=dtype)) self.pos_embed = nn.Parameter( torch.zeros((1, self.num_patches + 1, embed_size), device=get_current_device(), dtype=dtype)) self.reset_parameters(weight_initializer, bias_initializer, position_embed_initializer) def reset_parameters(self, weight_initializer, bias_initializer, position_embed_initializer): fan_in, fan_out = nn.init._calculate_fan_in_and_fan_out(self.weight) 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) def forward(self, input_: Tensor) -> Tensor: B, C, H, W = input_.shape assert H == self.img_size[0] and W == self.img_size[1], \ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." output = F.conv2d(input_, self.weight, self.bias, stride=self.patch_size) if self.flatten: output = output.flatten(2).transpose(1, 2) # BCHW -> BNC 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 VanillaClassifier(nn.Module): r"""Dense linear classifier. 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. 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. More details about initializer please refer to `init <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/nn/init.py>`_. """ def __init__(self, in_features: int, num_classes: int, weight: nn.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)): super().__init__() self.in_features = in_features self.num_classes = num_classes if weight is not None: self.weight = weight self.has_weight = False else: self.weight = nn.Parameter( torch.empty(self.num_classes, self.in_features, device=get_current_device(), dtype=dtype)) self.has_weight = True if bias: self.bias = nn.Parameter(torch.zeros(self.num_classes, device=get_current_device(), dtype=dtype)) else: self.bias = None self.reset_parameters(weight_initializer, bias_initializer) def reset_parameters(self, weight_initializer, bias_initializer): 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) if self.bias is not None: bias_initializer(self.bias, fan_in=fan_in) def forward(self, input_: Tensor) -> Tensor: return F.linear(input_, self.weight, self.bias) @LAYERS.register_module class VanillaLayerNorm(nn.Module): r""" Layer Normalization for colossalai 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): a value added to the denominator for numerical stability, defaults to 1e-05. bias (bool, optional): Whether to add a bias, defaults to ``True``. dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None. """ def __init__(self, normalized_shape: int, eps=1e-05, bias=True, dtype=None): super().__init__() self.normalized_shape = (normalized_shape,) self.variance_epsilon = eps factory_kwargs = {'device': get_current_device(), 'dtype': dtype} self.weight = nn.Parameter(torch.ones(normalized_shape, **factory_kwargs)) if bias: self.bias = nn.Parameter(torch.zeros(normalized_shape, **factory_kwargs)) else: self.bias = None def forward(self, x: Tensor) -> Tensor: return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.variance_epsilon)
import torch import torch.distributed as dist from torch import Tensor from typing import Any, Tuple, Optional from torch.distributed import ProcessGroup COL_MOE_KERNEL_FLAG = False try: import colossal_moe_cuda COL_MOE_KERNEL_FLAG = True except ImportError: print("If you want to activate cuda mode for MoE, please install with cuda_ext!") class AllGather(torch.autograd.Function): @staticmethod def forward(ctx: Any, inputs: Tensor, group: Optional[ProcessGroup] = None) -> Tensor: if ctx is not None: ctx.comm_grp = group comm_size = dist.get_world_size(group) if comm_size == 1: return inputs.unsqueeze(0) buffer_shape = (comm_size,) + inputs.shape outputs = torch.empty(buffer_shape, dtype=inputs.dtype, device=inputs.device) buffer_list = list(torch.chunk(outputs, comm_size, dim=0)) dist.all_gather(buffer_list, inputs, group=group) return outputs @staticmethod def backward(ctx: Any, grad_outputs: Tensor) -> Tuple[Tensor, None]: return ReduceScatter.forward(None, grad_outputs, ctx.comm_grp), None class ReduceScatter(torch.autograd.Function): @staticmethod def forward(ctx: Any, inputs: Tensor, group: Optional[ProcessGroup] = None) -> Tensor: if ctx is not None: ctx.comm_grp = group comm_size = dist.get_world_size(group) if comm_size == 1: return inputs.squeeze(0) if not inputs.is_contiguous(): inputs = inputs.contiguous() output_shape = inputs.shape[1:] outputs = torch.empty(output_shape, dtype=inputs.dtype, device=inputs.device) buffer_list = list(torch.chunk(inputs, comm_size, dim=0)) dist.reduce_scatter(outputs, buffer_list, group=group) return outputs @staticmethod def backward(ctx: Any, grad_outputs: Tensor) -> Tuple[Tensor, None]: return AllGather.forward(None, grad_outputs, ctx.comm_grp), None class AllToAll(torch.autograd.Function): """Dispatches input tensor [e, c, h] to all experts by all_to_all_single operation in torch.distributed. """ @staticmethod def forward(ctx: Any, inputs: Tensor, group: Optional[ProcessGroup] = None) -> Tensor: if ctx is not None: ctx.comm_grp = group if not inputs.is_contiguous(): inputs = inputs.contiguous() if dist.get_world_size(group) == 1: return inputs output = torch.empty_like(inputs) dist.all_to_all_single(output, inputs, group=group) return output @staticmethod def backward(ctx: Any, *grad_outputs: Tensor) -> Tuple[Tensor, None]: return AllToAll.forward(None, *grad_outputs, ctx.comm_grp), None class MoeDispatch(torch.autograd.Function): @staticmethod def forward(ctx, tokens, mask, dest_idx, ec): s = tokens.size(0) h = tokens.size(1) expert_input = colossal_moe_cuda.dispatch_forward(s, ec, h, tokens, mask, dest_idx) ctx.save_for_backward(mask, dest_idx) ctx.s = s ctx.h = h ctx.ec = ec return expert_input @staticmethod def backward(ctx, output_grad): mask, dest_idx = ctx.saved_tensors d_tokens = colossal_moe_cuda.dispatch_backward(ctx.s, ctx.ec, ctx.h, output_grad, mask, dest_idx) return d_tokens, None, None, None class MoeCombine(torch.autograd.Function): @staticmethod def forward(ctx, expert_tokens, logits, mask, dest_idx, ec): assert logits.dtype == torch.float32 s = logits.size(0) e = logits.size(1) c = ec // e h = expert_tokens.size(-1) fp16_flag = (expert_tokens.dtype == torch.float16) cb_input = expert_tokens.to(torch.float32) if fp16_flag else expert_tokens ctokens = colossal_moe_cuda.combine_forward(s, e, c, h, cb_input, logits, mask, dest_idx) output = ctokens.to(torch.float16) if fp16_flag else ctokens ctx.save_for_backward(expert_tokens, logits, mask, dest_idx) ctx.s = s ctx.e = e ctx.c = c ctx.h = h ctx.fp16_flag = fp16_flag return output @staticmethod def backward(ctx, tokens_grad): expert_tokens, logits, mask, dest_idx = ctx.saved_tensors cb_grad = tokens_grad.to(torch.float32) if tokens_grad.dtype is torch.float16 \ else tokens_grad cb_input = expert_tokens.to(torch.float32) if ctx.fp16_flag else expert_tokens d_expert, d_logits = colossal_moe_cuda.combine_backward(ctx.s, ctx.e, ctx.c, ctx.h, cb_grad, cb_input, logits, mask, dest_idx) d_expert = d_expert.to(torch.float16) if ctx.fp16_flag else d_expert return d_expert, d_logits, None, None, None def moe_cumsum(inputs: Tensor): dim0 = inputs.size(0) flag = (dim0 <= 1024) or (dim0 <= 2048 and dim0 % 2 == 0) or (dim0 % 4 == 0) if flag and COL_MOE_KERNEL_FLAG: return colossal_moe_cuda.cumsum_sub_one(inputs) else: return torch.cumsum(inputs, dim=0) - 1
from .experts import Experts, FFNExperts, TPExperts from .layers import MoeLayer, Top1Router, Top2Router, MoeModule from .utils import NormalNoiseGenerator, UniformNoiseGenerator, build_ffn_experts __all__ = [ 'Experts', 'FFNExperts', 'TPExperts', 'Top1Router', 'Top2Router', 'MoeLayer', 'NormalNoiseGenerator', 'UniformNoiseGenerator', 'build_ffn_experts', 'MoeModule' ]
import torch import torch.nn.functional as F from colossalai.utils import get_current_device from colossalai.context.moe_context import MOE_CONTEXT from .experts import FFNExperts, TPExperts class ForceFP32Parameter(torch.nn.Parameter): def half(self, memory_format=None): return self.data class NormalNoiseGenerator: """Generates a random noisy mask for logtis tensor. All noise is generated from a normal distribution :math:`(0, 1 / E^2)`, where `E = the number of experts`. Args: num_experts (int): The number of experts. """ def __init__(self, num_experts: int): self.normal = torch.distributions.normal.Normal(loc=torch.tensor(0.0, device=get_current_device()), scale=torch.tensor(1.0 / num_experts**2, device=get_current_device())).rsample def __call__(self, inputs: torch.Tensor): noisy = self.normal(inputs.shape) return inputs + noisy class UniformNoiseGenerator: """Generates a random noisy mask for logtis tensor. copied from mesh tensorflow: Multiply values by a random number between :math:`1-epsilon` and :math:`1+epsilon`. Makes models more resilient to rounding errors introduced by bfloat16. This seems particularly important for logits. Args: eps (float, optional): Epsilon in generator, defaults 1e-2. """ def __init__(self, eps: float = 1e-2): self.uniform = torch.distributions.uniform.Uniform(low=torch.tensor(1.0 - eps, device=get_current_device()), high=torch.tensor(1.0 + eps, device=get_current_device())).rsample def __call__(self, inputs: torch.Tensor): noisy = self.uniform(inputs.shape) return inputs * noisy def autocast_softmax(logit: torch.Tensor, dim: int): if logit.dtype != torch.float32: logit = logit.float() return F.softmax(logit, dim=dim) def build_ffn_experts(num_experts: int, d_model: int, d_ff: int, activation=None, drop_rate: float = 0): mep_size = MOE_CONTEXT.max_ep_size if num_experts % mep_size == 0 or mep_size % num_experts == 0: return FFNExperts(num_experts, d_model, d_ff, activation, drop_rate) elif d_ff % mep_size == 0: return TPExperts(num_experts, d_model, d_ff, activation, drop_rate) else: raise NotImplementedError(f"Can not build {num_experts} experts in {mep_size} GPUS.")
import math import torch import torch.nn as nn from colossalai.context import ParallelMode, seed from colossalai.utils import get_current_device from colossalai.context.moe_context import MOE_CONTEXT from colossalai.zero.init_ctx import no_shard_zero_decrator from typing import Type class MoeExperts(nn.Module): """Basic class for experts in MoE. It stores what kind of communication expersts use to exchange tokens, how many experts in a single GPU and parallel information such as expert parallel size, data parallel size and their distributed communication groups. """ def __init__(self, comm_name: str, num_experts: int): super().__init__() assert comm_name in {"all_to_all", "all_gather"}, \ "This kind of communication has not been implemented yet.\n Please use Experts build function." self.comm_name = comm_name # Get the configuration of experts' deployment and parallel information from moe contex self.num_local_experts, self.dist_info = MOE_CONTEXT.get_info(num_experts) class Experts(MoeExperts): """A wrapper class to create experts. It will create E experts across the moe model parallel group, where E is the number of experts. Every expert is a instence of the class, 'expert' in initialization parameters. Args: expert_cls (:class:`torch.nn.Module`): The class of all experts num_experts (int): The number of experts expert_args: Args used to initialize experts, the args could be found in corresponding expert class """ @no_shard_zero_decrator(is_replicated=False) def __init__(self, expert_cls: Type[nn.Module], num_experts: int, **expert_args): super().__init__("all_to_all", num_experts) # Use seed to make every expert different from others with seed(ParallelMode.TENSOR): self.experts = nn.ModuleList([expert_cls(**expert_args) for _ in range(self.num_local_experts)]) # Attach parallel information for all parameters in Experts for exp in self.experts: for param in exp.parameters(): param.__setattr__('moe_info', self.dist_info) def forward(self, inputs: torch.Tensor): # Split inputs for each expert expert_input = torch.chunk(inputs, self.num_local_experts, dim=1) expert_output = [] # Get outputs from each expert for i in range(self.num_local_experts): expert_output.append(self.experts[i](expert_input[i])) # Concatenate all outputs together output = torch.cat(expert_output, dim=1).contiguous() return output class FFNExperts(MoeExperts): """Use torch.bmm to speed up for multiple experts. """ def __init__(self, num_experts: int, d_model: int, d_ff: int, activation=None, drop_rate: float = 0): super().__init__("all_to_all", num_experts) self.w1 = nn.Parameter(torch.empty(self.num_local_experts, d_model, d_ff, device=get_current_device())) self.b1 = nn.Parameter(torch.empty(self.num_local_experts, 1, d_ff, device=get_current_device())) self.w2 = nn.Parameter(torch.empty(self.num_local_experts, d_ff, d_model, device=get_current_device())) self.b2 = nn.Parameter(torch.empty(self.num_local_experts, 1, d_model, device=get_current_device())) s1 = math.sqrt(0.1 / d_model) s2 = math.sqrt(0.1 / d_ff) with seed(ParallelMode.TENSOR): nn.init.trunc_normal_(self.w1, std=s1) nn.init.trunc_normal_(self.b1, std=s1) nn.init.trunc_normal_(self.w2, std=s2) nn.init.trunc_normal_(self.b2, std=s2) self.act = nn.GELU() if activation is None else activation self.drop = nn.Dropout(p=drop_rate) for param in self.parameters(): param.__setattr__('moe_info', self.dist_info) def forward(self, inputs): # inputs [g, el, c, h] el = inputs.size(1) h = inputs.size(-1) inputs = inputs.transpose(0, 1) inshape = inputs.shape inputs = inputs.reshape(el, -1, h) out_ff = torch.baddbmm(self.b1, inputs, self.w1) out_act = self.act(out_ff) with seed(ParallelMode.TENSOR): out_inter = self.drop(out_act) out_model = torch.baddbmm(self.b2, out_inter, self.w2) with seed(ParallelMode.TENSOR): outputs = self.drop(out_model) # outputs [el, gc, h] outputs = outputs.reshape(inshape) outputs = outputs.transpose(0, 1).contiguous() return outputs class TPExperts(MoeExperts): """Use tensor parallelism to split each expert evenly, which can deploy experts in case that the number of experts can't be divied by maximum expert parallel size or maximum expert parallel size can't be divied by the number of experts. """ def __init__(self, num_experts: int, d_model: int, d_ff: int, activation=None, drop_rate: float = 0): super().__init__("all_gather", MOE_CONTEXT.max_ep_size) assert d_ff % MOE_CONTEXT.max_ep_size == 0, \ "d_ff should be divied by maximum expert parallel size" p_ff = d_ff // MOE_CONTEXT.max_ep_size self.w1 = nn.Parameter(torch.empty(num_experts, d_model, p_ff, device=get_current_device())) self.b1 = nn.Parameter(torch.empty(num_experts, 1, p_ff, device=get_current_device())) self.w2 = nn.Parameter(torch.empty(num_experts, p_ff, d_model, device=get_current_device())) self.b2 = nn.Parameter(torch.empty(num_experts, 1, d_model, device=get_current_device())) s1 = math.sqrt(0.1 / d_model) s2 = math.sqrt(0.1 / d_ff) with seed(ParallelMode.TENSOR): nn.init.trunc_normal_(self.w1, std=s1) nn.init.trunc_normal_(self.b1, std=s1) nn.init.trunc_normal_(self.w2, std=s2) nn.init.trunc_normal_(self.b2, std=s2) self.act = nn.GELU() if activation is None else activation self.drop = nn.Dropout(p=drop_rate) self.w1.__setattr__('moe_info', self.dist_info) self.w2.__setattr__('moe_info', self.dist_info) self.b1.__setattr__('moe_info', self.dist_info) def forward(self, inputs): # inputs [g, e, c, h] e = inputs.size(1) h = inputs.size(-1) inputs = inputs.transpose(0, 1) inshape = inputs.shape inputs = inputs.reshape(e, -1, h) out_ff = torch.baddbmm(self.b1, inputs, self.w1) out_act = self.act(out_ff) with seed(ParallelMode.TENSOR): out_inter = self.drop(out_act) out_model = torch.baddbmm(self.b2, out_inter, self.w2) outputs = self.drop(out_model) # outputs [e, gc, h] outputs = outputs.reshape(inshape) outputs = outputs.transpose(0, 1).contiguous() return outputs # outputs [g, e, c, h]
import functools import math import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist from colossalai.context.moe_context import MOE_CONTEXT from colossalai.utils import get_current_device from ._operation import COL_MOE_KERNEL_FLAG, AllToAll, AllGather, ReduceScatter, MoeDispatch, MoeCombine, moe_cumsum from .experts import MoeExperts, Experts from .utils import ForceFP32Parameter, UniformNoiseGenerator, NormalNoiseGenerator, autocast_softmax from colossalai.zero.init_ctx import no_shard_zero_context, no_shard_zero_decrator from typing import Callable, Optional, Type from torch.distributed import ProcessGroup class Top1Router(nn.Module): """Top1 router that returns the dispatch mask [s, e, c] and combine weight [s, e, c] for routing usage. More deailted function can be found in the paper about Switch Transformer of Google. Args: capacity_factor_train (float, optional): Capacity factor in routing of training. capacity_factor_eval (float, optional): Capacity factor in routing of evaluation. min_capacity (int, optional): The minimum number of the capacity of each expert. select_policy (str, optional): The policy about tokens selection. noisy_func (:class:`typing.Callable`, optional): Noisy function used in logits. drop_tks (bool, optional): Whether drops tokens in evaluation """ def __init__(self, capacity_factor_train: float = 1.25, capacity_factor_eval: float = 2.0, min_capacity: int = 4, select_policy: str = "first", noisy_func: Callable = None, drop_tks: bool = True): super().__init__() self.capacity_factor_train = capacity_factor_train self.capacity_factor_eval = capacity_factor_eval self.min_capacity = min_capacity self.select_policy = select_policy self.noisy_func = noisy_func self.drop_tks = drop_tks assert select_policy in {"first", "random"} if select_policy == "random": self.uniform = torch.distributions.uniform.Uniform(low=torch.tensor(0.0, device=get_current_device()), high=torch.tensor(1.0, device=get_current_device())).rsample def get_capacity( self, logits_shape, ): capacity_factor = self.capacity_factor_train if self.training else self.capacity_factor_eval capacity = math.floor(capacity_factor * logits_shape[-2] / logits_shape[-1]) capacity += capacity % 2 capacity = max(capacity, self.min_capacity) assert capacity > 0 return capacity def forward(self, inputs: torch.Tensor, use_kernel: bool = False, ep_group: Optional[ProcessGroup] = None): if self.noisy_func is not None and self.training: inputs = self.noisy_func(inputs) logits = autocast_softmax(inputs, dim=-1) num_experts = logits.size(-1) capacity = self.get_capacity(logits.shape) top1_idx = torch.argmax(inputs, dim=-1) mask = F.one_hot(top1_idx, num_classes=num_experts).to(torch.int32) if self.training: me = torch.mean(logits, dim=0) ce = torch.mean(mask.float(), dim=0) l_aux = num_experts * torch.sum(me * ce) MOE_CONTEXT.add_loss(l_aux) elif not self.drop_tks: max_num = torch.max(torch.sum(mask, dim=0)) dist.all_reduce(max_num, op=dist.ReduceOp.MAX, group=ep_group) capacity = max_num.item() else: pass if self.select_policy == "random": rand_mask = mask * self.uniform(mask.shape) _, dispatch_idx = torch.topk(rand_mask, k=capacity, dim=0) mask = mask * torch.zeros_like(mask).scatter_(0, dispatch_idx, 1) ranks = moe_cumsum(mask) elif self.select_policy == "first": ranks = moe_cumsum(mask) mask = mask * torch.lt(ranks, capacity) else: raise NotImplementedError("Not support such select policy yet.") ranks = torch.sum(mask * ranks, dim=-1) if use_kernel: mask = torch.sum(mask, dim=-1) mask = torch.stack([mask], dim=0).to(torch.int32) dest_idx = torch.stack([top1_idx * capacity + ranks], dim=0).to(torch.int32) return logits, mask, dest_idx, num_experts * capacity else: ranks = F.one_hot(ranks, num_classes=capacity) weight = mask * logits.type_as(inputs) combine_weights = weight.unsqueeze(2) * ranks.unsqueeze(1) sec_mask = combine_weights.bool() return combine_weights, sec_mask class Top2Router(nn.Module): """Top2 router that returns the dispatch mask [s, e, c] and combine weight [s, e, c] for routing usage. More deailted function can be found in the paper about ViT-MoE. Args: capacity_factor_train (float, optional): Capacity factor in routing of training. capacity_factor_eval (float, optional): Capacity factor in routing of evaluation. min_capacity (int, optional): The minimum number of the capacity of each expert noisy_func (:class:`typing.Callable`, optional): Noisy function used in logits. drop_tks (bool, optional): Whether drops tokens in evaluation. """ def __init__(self, capacity_factor_train: float = 1.25, capacity_factor_eval: float = 2.0, min_capacity: int = 4, noisy_func: Callable = None, drop_tks: bool = True): super().__init__() self.capacity_factor_train = capacity_factor_train self.capacity_factor_eval = capacity_factor_eval self.min_capacity = min_capacity self.noisy_func = noisy_func self.drop_tks = drop_tks def get_capacity( self, logits_shape, ): capacity_factor = self.capacity_factor_train if self.training else self.capacity_factor_eval capacity = math.floor(capacity_factor * logits_shape[-2] / logits_shape[-1]) capacity += capacity % 2 capacity = max(capacity, self.min_capacity) assert capacity > 0 return capacity def forward(self, inputs: torch.Tensor, use_kernel: bool = False, ep_group: Optional[ProcessGroup] = None): # inputs: [s, h] if self.noisy_func is not None and self.training: inputs = self.noisy_func(inputs) logits = autocast_softmax(inputs, dim=-1) # logits: [s, e] num_experts = logits.size(-1) capacity = self.get_capacity(logits.shape) top1_idx = torch.argmax(logits, dim=-1) mask1 = F.one_hot(top1_idx, num_classes=num_experts).to(torch.int32) logits_except1 = logits.masked_fill(mask1.bool(), float("-inf")) top2_idx = torch.argmax(logits_except1, dim=-1) mask2 = F.one_hot(top2_idx, num_classes=num_experts).to(torch.int32) cmask = (mask1 + mask2) # loss: [s, e] if self.training: me = torch.mean(logits, dim=0) ce = torch.mean(cmask.float(), dim=0) l_aux = num_experts * torch.sum(me * ce) / 2.0 # div 2 to normalize it to 1 MOE_CONTEXT.add_loss(l_aux) elif not self.drop_tks: max_num = torch.max(torch.sum(cmask, dim=0)) dist.all_reduce(max_num, op=dist.ReduceOp.MAX, group=ep_group) capacity = max_num.item() else: pass rank1 = moe_cumsum(mask1) # rank1: [s, e] rank2 = moe_cumsum(mask2) rank2 += torch.sum(mask1, dim=-2, keepdim=True) mask1 *= torch.lt(rank1, capacity) mask2 *= torch.lt(rank2, capacity) rank1 = torch.sum(mask1 * rank1, dim=-1) rank2 = torch.sum(mask2 * rank2, dim=-1) if use_kernel: mask1 = torch.sum(mask1, dim=-1) mask2 = torch.sum(mask2, dim=-1) mask = torch.stack([mask1, mask2], dim=0).to(torch.int32) dest_idx = torch.stack([top1_idx * capacity + rank1, top2_idx * capacity + rank2], dim=0).to(torch.int32) return logits, mask, dest_idx, num_experts * capacity else: weight1 = mask1 * logits.type_as(inputs) weight2 = mask2 * logits.type_as(inputs) rank1_sc = F.one_hot(rank1, num_classes=capacity) rank2_sc = F.one_hot(rank2, num_classes=capacity) cb_weight1 = weight1.unsqueeze(2) * rank1_sc.unsqueeze(1) cb_weight2 = weight2.unsqueeze(2) * rank2_sc.unsqueeze(1) cb_weight = cb_weight1 + cb_weight2 sec_mask = cb_weight.bool() return cb_weight, sec_mask class FP32LinearGate(nn.Module): """Gate module used in MOE layer. Just a linear function without bias. But it should be kept as fp32 forever. Args: d_model (int): Hidden dimension of training model num_experts (int): The number experts Attributes: weight (ForceFP32Parameter): The weight of linear gate """ def __init__(self, d_model: int, num_experts: int, scale: float = 0.1): super().__init__() self.weight = ForceFP32Parameter(torch.empty(num_experts, d_model, device=get_current_device())) nn.init.trunc_normal_(self.weight, std=math.sqrt(scale / d_model)) def forward(self, x: torch.Tensor): return F.linear(x, self.weight) class MoeLayer(nn.Module): """A MoE layer, that puts its input tensor to its gate and uses the output logits to router all tokens, is mainly used to exchange all tokens for every expert across the moe tensor group by all to all comunication. Then it will get the output of all experts and exchange the output. At last returns the output of the moe system. Args: dim_model (int): Dimension of model. num_experts (int): The number of experts. router (:class:`torch.nn.Module`): Instance of router used in routing. experts (:class:`torch.nn.Module`): Instance of experts generated by Expert. """ @no_shard_zero_decrator(is_replicated=True) def __init__(self, dim_model: int, num_experts: int, router: nn.Module, experts: MoeExperts): super().__init__() self.d_model = dim_model self.num_experts = num_experts self.gate = FP32LinearGate(dim_model, num_experts) self.router = router self.experts = experts self.use_kernel = True if COL_MOE_KERNEL_FLAG and MOE_CONTEXT.use_kernel_optim else False self.ep_group = experts.dist_info.ep_group self.ep_size = experts.dist_info.ep_size self.num_local_experts = experts.num_local_experts def a2a_process(self, dispatch_data: torch.Tensor): expert_input = AllToAll.apply(dispatch_data, self.ep_group) input_shape = expert_input.shape expert_input = expert_input.reshape(self.ep_size, self.num_local_experts, -1, self.d_model) expert_output = self.experts(expert_input) expert_output = expert_output.reshape(input_shape) expert_output = AllToAll.apply(expert_output, self.ep_group) return expert_output def tp_process(self, dispatch_data: torch.Tensor): expert_in = AllGather.apply(dispatch_data, self.ep_group) expert_out = self.experts(expert_in) expert_out = ReduceScatter.apply(expert_out, self.ep_group) return expert_out def forward(self, inputs: torch.Tensor) -> torch.Tensor: tokens = inputs.reshape(-1, self.d_model) fp32_input = tokens.to(torch.float32) if inputs.dtype != torch.float32 else tokens gate_output = self.gate(fp32_input) router_res = self.router(inputs=gate_output, use_kernel=self.use_kernel, ep_group=self.ep_group) if self.use_kernel: dispatch_data = MoeDispatch.apply(tokens, *router_res[1:]) dispatch_data = dispatch_data.reshape(self.num_experts, -1, self.d_model) else: sec_mask_f = router_res[1].type_as(inputs) dispatch_data = torch.matmul(sec_mask_f.permute(1, 2, 0), tokens) # dispatch_data [e, c, h] if self.experts.comm_name == "all_to_all": expert_output = self.a2a_process(dispatch_data) elif self.experts.comm_name == "all_gather": expert_output = self.tp_process(dispatch_data) else: raise NotImplementedError("This kind of communication has not been implemented yet.\n Please use Experts " "build function.") # expert_output [e, c, h] if self.use_kernel: expert_output = expert_output.reshape(-1, self.d_model) ans = MoeCombine.apply(expert_output, *router_res) else: combine_weights = router_res[0].type_as(inputs) combine_weights = combine_weights.view(combine_weights.shape[0], -1) expert_output = expert_output.view(-1, expert_output.shape[-1]) ans = torch.matmul(combine_weights, expert_output) ans = ans.reshape(inputs.shape) return ans class MoeModule(nn.Module): """A class for users to create MoE modules in their models. Args: dim_model (int): Hidden dimension of training model num_experts (int): The number experts top_k (int, optional): The number of experts for dispatchment of each token capacity_factor_train (float, optional): Capacity factor in routing during training capacity_factor_eval (float, optional): Capacity factor in routing during evaluation min_capacity (int, optional): The minimum number of the capacity of each expert noisy_policy (str, optional): The policy of noisy function. Now we have 'Jitter' and 'Gaussian'. 'Jitter' can be found in `Switch Transformer paper`_. 'Gaussian' can be found in `ViT-MoE paper`_. drop_tks (bool, optional): Whether drops tokens in evaluation use_residual (bool, optional): Makes this MoE layer a Residual MoE. More information can be found in `Microsoft paper`_. residual_instance (nn.Module, optional): The instance of residual module in Resiual MoE expert_instance (MoeExperts, optional): The instance of experts module in MoeLayer expert_cls (Type[nn.Module], optional): The class of each expert when no instance is given expert_args (optional): The args of expert when no instance is given .. _Switch Transformer paper: https://arxiv.org/abs/2101.03961 .. _ViT-MoE paper: https://arxiv.org/abs/2106.05974 .. _Microsoft paper: https://arxiv.org/abs/2201.05596 """ def __init__(self, dim_model: int, num_experts: int, top_k: int = 1, capacity_factor_train: float = 1.25, capacity_factor_eval: float = 2.0, min_capacity: int = 4, noisy_policy: Optional[str] = None, drop_tks: bool = True, use_residual: bool = False, residual_instance: Optional[nn.Module] = None, expert_instance: Optional[MoeExperts] = None, expert_cls: Optional[Type[nn.Module]] = None, **expert_args): super().__init__() noisy_func = None if noisy_policy is not None: if noisy_policy == 'Jitter': noisy_func = UniformNoiseGenerator() elif noisy_policy == 'Gaussian': noisy_func = NormalNoiseGenerator(num_experts) else: raise NotImplementedError("Unsupported input noisy policy") if top_k == 1: moe_router_cls = Top1Router elif top_k == 2: moe_router_cls = Top2Router else: raise NotImplementedError("top_k > 2 is not supported yet") self.moe_router = moe_router_cls(capacity_factor_train=capacity_factor_train, capacity_factor_eval=capacity_factor_eval, min_capacity=min_capacity, noisy_func=noisy_func, drop_tks=drop_tks) self.use_residual = use_residual if use_residual: if residual_instance is not None: self.residual_module = residual_instance else: assert expert_cls is not None, \ "Expert class can't be None when residual instance is not given" self.residual_module = expert_cls(**expert_args) with no_shard_zero_context(): self.residual_combine = nn.Linear(dim_model, 2, device=get_current_device()) if expert_instance is not None: self.experts = expert_instance else: assert expert_cls is not None, \ "Expert class can't be None when experts instance is not given" self.experts = Experts(expert_cls, num_experts, **expert_args) self.moe_layer = MoeLayer(dim_model=dim_model, num_experts=num_experts, router=self.moe_router, experts=self.experts) def forward(self, inputs: torch.Tensor): moe_output = self.moe_layer(inputs) if self.use_residual: residual_output = self.residual_module(inputs) combine_coef = self.residual_combine(inputs) combine_coef = F.softmax(combine_coef, dim=-1) output = moe_output * combine_coef[..., 0:1] + residual_output * combine_coef[..., 1:] else: output = moe_output return output
from .model_from_config import ModelFromConfig __all__ = ['ModelFromConfig']
#!/usr/bin/env python # -*- encoding: utf-8 -*- from abc import ABC, abstractmethod import torch.nn as nn from colossalai.builder import build_layer class ModelFromConfig(nn.Module, ABC): def __init__(self): super(ModelFromConfig, self).__init__() self.layers = nn.ModuleList() self.layers_cfg = [] def build_from_cfg(self, start=None, end=None): assert hasattr(self, 'layers_cfg'), 'Cannot find attribute layers_cfg from the module, please check the ' \ 'spelling and if you have initialized this variable' if start is None: start = 0 if end is None: end = len(self.layers_cfg) for cfg in self.layers_cfg[start: end]: layer = build_layer(cfg) self.layers.append(layer) @abstractmethod def init_weights(self): pass def state_dict_for_save_checkpoint(self, destination=None, prefix='', keep_vars=False): """Use this function to override the state dict for saving checkpoints.""" return self.state_dict(destination, prefix, keep_vars)
from torch import nn from ._utils import calc_acc from .accuracy_2d import Accuracy2D from .accuracy_2p5d import Accuracy2p5D from .accuracy_3d import Accuracy3D from colossalai.nn.layer.utils import get_tensor_parallel_mode _parallel_accuracy = { '2d': Accuracy2D, '2.5d': Accuracy2p5D, '3d': Accuracy3D, } class Accuracy(nn.Module): def __init__(self): super().__init__() tensor_parallel = get_tensor_parallel_mode() if tensor_parallel not in _parallel_accuracy: self.acc = calc_acc else: self.acc = _parallel_accuracy[tensor_parallel]() def forward(self, *args): return self.acc(*args)
import torch from colossalai.nn.layer.parallel_2d import reduce_by_batch_2d, split_batch_2d from torch import nn from ._utils import calc_acc class Accuracy2D(nn.Module): """Accuracy for 2D parallelism """ def __init__(self): super().__init__() def forward(self, logits, targets): """Calculate the accuracy of predicted labels. Args: logits (:class:`torch.tensor`): Predicted labels. targets (:class:`torch.tensor`): True labels from data. Returns: float: the accuracy of prediction. """ with torch.no_grad(): targets = split_batch_2d(targets) correct = calc_acc(logits, targets) correct = reduce_by_batch_2d(correct) return correct
import torch from colossalai.constants import INPUT_GROUP_3D, WEIGHT_GROUP_3D from colossalai.nn.layer.parallel_3d import reduce_by_batch_3d, split_tensor_3d from colossalai.nn.layer.parallel_3d._utils import get_parallel_mode_from_env from torch import nn from ._utils import calc_acc class Accuracy3D(nn.Module): """Accuracy for 3D parallelism """ def __init__(self): super().__init__() self.input_parallel_mode = get_parallel_mode_from_env(INPUT_GROUP_3D) self.weight_parallel_mode = get_parallel_mode_from_env(WEIGHT_GROUP_3D) def forward(self, logits, targets): """Calculate the accuracy of predicted labels. Args: logits (:class:`torch.tensor`): Predicted labels. targets (:class:`torch.tensor`): True labels from data. Returns: float: the accuracy of prediction. """ with torch.no_grad(): targets = split_tensor_3d(targets, 0, self.weight_parallel_mode) targets = split_tensor_3d(targets, 0, self.input_parallel_mode) correct = calc_acc(logits, targets) correct = reduce_by_batch_3d(correct, self.input_parallel_mode, self.weight_parallel_mode) return correct
import torch from colossalai.nn.layer.parallel_2p5d import reduce_by_batch_2p5d, split_batch_2p5d from torch import nn from ._utils import calc_acc class Accuracy2p5D(nn.Module): """Accuracy for 2p5D parallelism """ def __init__(self): super().__init__() def forward(self, logits, targets): """Calculate the accuracy of predicted labels. Args: logits (:class:`torch.tensor`): Predicted labels. targets (:class:`torch.tensor`): True labels from data. Returns: float: the accuracy of prediction. """ with torch.no_grad(): targets = split_batch_2p5d(targets) correct = calc_acc(logits, targets) correct = reduce_by_batch_2p5d(correct) return correct
import torch def calc_acc(logits, targets): preds = torch.argmax(logits, dim=-1) correct = torch.sum(targets == preds) return correct
import torch import gc import psutil from collections import namedtuple from colossalai.context.parallel_mode import ParallelMode from colossalai.utils import get_current_device from colossalai.core import global_context as gpc from colossalai.context.parallel_mode import ParallelMode from colossalai.logging import get_dist_logger from packaging import version _GLOBAL_CUDA_MEM_FRACTION = 1.0 def _bytes_to_MB(val, decimal=2): """A byte-to-Megabyte converter, default using binary notation. :param val: X bytes to convert :return: X' MB """ return round(val / (1024 * 1024), decimal) # copy from PatrickStar def _get_cpu_memory_info(): ps_mem_info = namedtuple("ps_mem_info", ["total", "free", "cached", "buffers", "used"]) try: # psutil reads the memory info from /proc/memory_info, # which results in returning the host memory instead of # that of container. # Here we try to read the container memory with method in: # https://stackoverflow.com/a/46213331/5163915 mems = {} with open("/sys/fs/cgroup/memory/memory.meminfo", "rb") as f: for line in f: fields = line.split() mems[fields[0]] = int(fields[1]) * 1024 total = mems[b"MemTotal:"] free = mems[b"MemFree:"] cached = mems[b"Cached:"] buffers = mems[b"Buffers:"] used = total - free - cached - buffers if used < 0: used = total - free mem_info = ps_mem_info(total=total, free=free, cached=cached, buffers=buffers, used=used) except FileNotFoundError: mems = psutil.virtual_memory() mem_info = ps_mem_info( total=mems.total, free=mems.free, cached=mems.cached, buffers=mems.buffers, used=mems.used, ) return mem_info def report_memory_usage(message, logger=None, report_cpu=False): """Calculate and print RAM usage (in GB) Args: message (str): A prefix message to add in the log. logger (:class:`colossalai.logging.DistributedLogger`): The logger used to record memory information. report_cpu (bool, optional): Whether to report CPU memory. Raises: EnvironmentError: Raise error if no distributed environment has been initialized. """ if not gpc.is_initialized(ParallelMode.GLOBAL): raise EnvironmentError("No distributed environment is initialized") gpu_allocated = _bytes_to_MB(torch.cuda.memory_allocated()) gpu_max_allocated = _bytes_to_MB(torch.cuda.max_memory_allocated()) gpu_cached = _bytes_to_MB(torch.cuda.memory_reserved()) gpu_max_cached = _bytes_to_MB(torch.cuda.max_memory_reserved()) full_log = f"{message}: GPU: allocated {gpu_allocated} MB, max allocated {gpu_max_allocated} MB, " \ + f"cached: {gpu_cached} MB, max cached: {gpu_max_cached} MB" if report_cpu: # python doesn't do real-time garbage collection so do it explicitly to get the correct RAM reports gc.collect() vm_stats = psutil.virtual_memory() vm_used = _bytes_to_MB(vm_stats.total - vm_stats.available) full_log += f", CPU Virtual Memory: used = {vm_used} MB, percent = {vm_stats.percent}%" if logger is None: logger = get_dist_logger() logger.info(full_log) # get the peak memory to report correct data, so reset the counter for the next call if hasattr(torch.cuda, "reset_peak_memory_stats"): # pytorch 1.4+ torch.cuda.reset_peak_memory_stats() def colo_device_memory_capacity(device: torch.device) -> int: """ Get the capacity of the memory of the device Args: device (torch.device): a device Returns: int: size in byte """ assert isinstance(device, torch.device) if device.type == 'cpu': mem_info = _get_cpu_memory_info() # In the context of 1-CPU-N-GPU, the memory capacity of the current process is 1/N overall CPU memory. return mem_info.total / gpc.num_processes_on_current_node if device.type == 'cuda': return torch.cuda.get_device_properties(get_current_device()).total_memory * _GLOBAL_CUDA_MEM_FRACTION def colo_device_memory_used(device: torch.device) -> int: """ Get the device memory on device belonging to the current process. Args: device (torch.device): a device Returns: int: memory size in bytes """ if device.type == 'cpu': mem_info = _get_cpu_memory_info() # In the context of 1-CPU-N-GPU, the memory usage of the current process is 1/N CPU memory used. # Each process consumes the same amount of memory. ret = mem_info.used / gpc.num_processes_on_current_node return ret elif device.type == 'cuda': ret: int = torch.cuda.memory_allocated(device) # get the peak memory to report correct data, so reset the counter for the next call if hasattr(torch.cuda, "reset_peak_memory_stats"): # pytorch 1.4+ torch.cuda.reset_peak_memory_stats(device) return ret def colo_set_process_memory_fraction(ratio: float) -> None: """colo_set_process_memory_fraction set how much cuda memory used on the gpu belonging to the current process. Args: ratio (float): a ratio between 0. ~ 1. """ if version.parse(torch.__version__) < version.parse('1.8'): logger = get_dist_logger('colo_set_process_memory_fraction') logger.warning('colo_set_process_memory_fraction failed because torch version is less than 1.8') return global _GLOBAL_CUDA_MEM_FRACTION _GLOBAL_CUDA_MEM_FRACTION = ratio torch.cuda.set_per_process_memory_fraction(_GLOBAL_CUDA_MEM_FRACTION, get_current_device())
#!/usr/bin/env python # -*- encoding: utf-8 -*- import time from typing import Tuple from .cuda import synchronize class Timer: """A timer object which helps to log the execution times, and provides different tools to assess the times. """ def __init__(self): self._started = False self._start_time = time.time() self._elapsed = 0 self._history = [] @property def has_history(self): return len(self._history) != 0 @property def current_time(self) -> float: synchronize() return time.time() def start(self): """Firstly synchronize cuda, reset the clock and then start the timer. """ self._elapsed = 0 synchronize() self._start_time = time.time() self._started = True def lap(self): """lap time and return elapsed time """ return self.current_time - self._start_time def stop(self, keep_in_history: bool = False): """Stop the timer and record the start-stop time interval. Args: keep_in_history (bool, optional): Whether does it record into history each start-stop interval, defaults to False. Returns: int: Start-stop interval. """ synchronize() end_time = time.time() elapsed = end_time - self._start_time if keep_in_history: self._history.append(elapsed) self._elapsed = elapsed self._started = False return elapsed def get_history_mean(self): """Mean of all history start-stop time intervals. Returns: int: Mean of time intervals """ return sum(self._history) / len(self._history) def get_history_sum(self): """Add up all the start-stop time intervals. Returns: int: Sum of time intervals. """ return sum(self._history) def get_elapsed_time(self): """Return the last start-stop time interval. Returns: int: The last time interval. Note: Use it only when timer is not in progress """ assert not self._started, 'Timer is still in progress' return self._elapsed def reset(self): """Clear up the timer and its history """ self._history = [] self._started = False self._elapsed = 0 class MultiTimer: """An object contains multiple timers. Args: on (bool, optional): Whether the timer is enabled. Default is True. """ def __init__(self, on: bool = True): self._on = on self._timers = dict() def start(self, name: str): """Start namely one of the timers. Args: name (str): Timer's key. """ if self._on: if name not in self._timers: self._timers[name] = Timer() return self._timers[name].start() def stop(self, name: str, keep_in_history: bool): """Stop namely one of the timers. Args: name (str): Timer's key. keep_in_history (bool): Whether does it record into history each start-stop interval. """ if self._on: return self._timers[name].stop(keep_in_history) else: return None def get_timer(self, name): """Get timer by its name (from multitimer) Args: name (str): Timer's key. Returns: :class:`colossalai.utils.Timer`: Timer with the name you give correctly. """ return self._timers[name] def reset(self, name=None): """Reset timers. Args: name (str, optional): If name is designated, the named timer will be reset and others will not, defaults to None. """ if self._on: if name is not None: self._timers[name].reset() else: for timer in self._timers: timer.reset() def is_on(self): return self._on def set_status(self, mode: bool): self._on = mode def __iter__(self) -> Tuple[str, Timer]: for name, timer in self._timers.items(): yield name, timer
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch from torch.utils.checkpoint import check_backward_validity, detach_variable from colossalai.context.random import get_states, get_current_mode, set_seed_states, set_mode, sync_states from .cuda import get_current_device def copy_to_device(obj, device): if torch.is_tensor(obj): # Notice: # When in no_grad context, requires_gard is False after movement ret = obj.to(device).detach() ret.requires_grad = obj.requires_grad return ret elif isinstance(obj, list): return [copy_to_device(i, device) for i in obj] elif isinstance(obj, tuple): return tuple([copy_to_device(v, device) for v in obj]) elif isinstance(obj, dict): return {k: copy_to_device(v, device) for k, v in obj.items()} else: return obj class CheckpointFunction(torch.autograd.Function): @staticmethod def forward(ctx, run_function, activation_offload=False, *args): check_backward_validity(args) ctx.run_function = run_function ctx.activation_offload = activation_offload ctx.device = get_current_device() # preserve rng states ctx.fwd_cpu_rng_state = torch.get_rng_state() sync_states() ctx.fwd_seed_states = get_states(copy=True) ctx.fwd_current_mode = get_current_mode() if hasattr(torch, 'is_autocast_enabled'): ctx.had_autocast_in_fwd = torch.is_autocast_enabled() else: ctx.had_autocast_in_fwd = False if activation_offload: inputs_cuda = copy_to_device(args, ctx.device) else: inputs_cuda = args with torch.no_grad(): outputs = run_function(*inputs_cuda) # Save non-tensor inputs in ctx, keep a placeholder None for tensors # to be filled out during the backward. ctx.inputs = [] ctx.tensor_indices = [] tensor_inputs = [] for i, arg in enumerate(args): if torch.is_tensor(arg): if activation_offload: tensor_inputs.append(copy_to_device(arg, 'cpu')) else: tensor_inputs.append(arg) ctx.tensor_indices.append(i) ctx.inputs.append(None) else: ctx.inputs.append(arg) if activation_offload: ctx.tensor_inputs = tensor_inputs else: ctx.save_for_backward(*tensor_inputs) return outputs @staticmethod def backward(ctx, *args): if not torch.autograd._is_checkpoint_valid(): raise RuntimeError("Checkpointing is not compatible with .grad() or when an `inputs` parameter is " "passed to .backward(). Please use .backward() and do not pass its `inputs` argument.") # Copy the list to avoid modifying original list. inputs = list(ctx.inputs) tensor_indices = ctx.tensor_indices if ctx.activation_offload: tensors = ctx.tensor_inputs else: tensors = ctx.saved_tensors # store the current states bwd_cpu_rng_state = torch.get_rng_state() sync_states() bwd_seed_states = get_states(copy=True) bwd_current_mode = get_current_mode() # set the states to what it used to be torch.set_rng_state(ctx.fwd_cpu_rng_state) for parallel_mode, state in ctx.fwd_seed_states.items(): set_seed_states(parallel_mode, state) set_mode(ctx.fwd_current_mode) if ctx.activation_offload: tensors = copy_to_device(tensors, ctx.device) # Fill in inputs with appropriate saved tensors. for i, idx in enumerate(tensor_indices): inputs[idx] = tensors[i] detached_inputs = detach_variable(tuple(inputs)) if ctx.had_autocast_in_fwd: with torch.enable_grad(), torch.cuda.amp.autocast(): outputs = ctx.run_function(*detached_inputs) else: with torch.enable_grad(): outputs = ctx.run_function(*detached_inputs) if isinstance(outputs, torch.Tensor): outputs = (outputs,) # recover the rng states torch.set_rng_state(bwd_cpu_rng_state) for parallel_mode, state in bwd_seed_states.items(): set_seed_states(parallel_mode, state) set_mode(bwd_current_mode) # run backward() with only tensor that requires grad outputs_with_grad = [] args_with_grad = [] for i in range(len(outputs)): if torch.is_tensor(outputs[i]) and outputs[i].requires_grad: outputs_with_grad.append(outputs[i]) args_with_grad.append(args[i]) if len(outputs_with_grad) == 0: raise RuntimeError("none of output has requires_grad=True," " this checkpoint() is not necessary") torch.autograd.backward(outputs_with_grad, args_with_grad) grads = tuple(inp.grad if isinstance(inp, torch.Tensor) else None for inp in detached_inputs) return (None, None) + grads def checkpoint(function, activation_offload, *args): """Checkpoint the computation while preserve the rng states, modified from Pytorch torch.utils.checkpoint. Args: function: Describe the forward pass function. It should know how to handle the input tuples. args (list): Tuple containing the parameters of the function Returns: Output of running function with provided args. """ return CheckpointFunction.apply(function, activation_offload, *args)
from .cuda import empty_cache, get_current_device, set_to_cuda, synchronize from .activation_checkpoint import checkpoint from .checkpointing import load_checkpoint, save_checkpoint from .common import (clip_grad_norm_fp32, conditional_context, copy_tensor_parallel_attributes, count_zeros_fp32, ensure_path_exists, free_port, is_dp_rank_0, is_model_parallel_parameter, is_no_pp_or_last_stage, is_tp_rank_0, is_using_ddp, is_using_pp, is_using_sequence, multi_tensor_applier, param_is_not_tensor_parallel_duplicate, print_rank_0, switch_virtual_pipeline_parallel_rank, sync_model_param, disposable) from .data_sampler import DataParallelSampler, get_dataloader from .gradient_accumulation import accumulate_gradient from .memory import report_memory_usage, colo_device_memory_used, colo_set_process_memory_fraction, colo_device_memory_capacity from .timer import MultiTimer, Timer from .tensor_detector import TensorDetector __all__ = [ 'checkpoint', 'free_port', 'print_rank_0', 'sync_model_param', 'is_dp_rank_0', 'is_tp_rank_0', 'is_no_pp_or_last_stage', 'is_using_ddp', 'is_using_pp', 'is_using_sequence', 'conditional_context', 'is_model_parallel_parameter', 'clip_grad_norm_fp32', 'count_zeros_fp32', 'copy_tensor_parallel_attributes', 'param_is_not_tensor_parallel_duplicate', 'get_current_device', 'synchronize', 'empty_cache', 'set_to_cuda', 'report_memory_usage', 'colo_device_memory_capacity', 'colo_device_memory_used', 'colo_set_process_memory_fraction', 'Timer', 'MultiTimer', 'multi_tensor_applier', 'accumulate_gradient', 'DataParallelSampler', 'get_dataloader', 'switch_virtual_pipeline_parallel_rank', 'TensorDetector', 'load_checkpoint', 'save_checkpoint', 'ensure_path_exists', 'disposable' ]
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os import random import socket from pathlib import Path from typing import Callable, List, Union import functools import torch from torch._six import inf from torch.nn.parameter import Parameter try: import colossal_C except: pass from contextlib import contextmanager import torch.distributed as dist from colossalai.constants import (IS_TENSOR_PARALLEL, NUM_PARTITIONS, TENSOR_PARALLEL_ATTRIBUTES) from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.global_variables import tensor_parallel_env as env from .multi_tensor_apply import multi_tensor_applier def print_rank_0(msg: str, logger=None): """Print messages and save logs(optional). This is executed only if you are the rank-0 gpu. Args: msg (str): A string message to output. logger (:class:`colossalai.logging.DistributedLogger`, optional): The logger to record the message, defaults to None. """ if gpc.get_global_rank() == 0: if logger is None: print(msg, flush=True) else: logger.info(msg) def ensure_path_exists(filename: str): # ensure the path exists dirpath = os.path.dirname(filename) if not os.path.exists(dirpath): Path(dirpath).mkdir(parents=True, exist_ok=True) def free_port(): while True: try: sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) port = random.randint(20000, 65000) sock.bind(('localhost', port)) sock.close() return port except Exception: continue def sync_model_param(model, parallel_mode): r"""Make sure data parameters are consistent during Data Parallel Mode. Args: model (:class:`torch.nn.Module`): A pyTorch model on whose parameters you check the consistency. parallel_mode (:class:`colossalai.context.ParallelMode`): Parallel mode to be checked. Note: The parallel_mode should be concluded in ``ParallelMode``. More details about ``ParallelMode`` could be found in `parallel_mode <https://github.com/hpcaitech/ColossalAI/blob/main/colossalai/context/parallel_mode.py>`_ """ if gpc.is_initialized(parallel_mode) and gpc.get_world_size(parallel_mode) > 1: for param in model.parameters(): ranks = gpc.get_ranks_in_group(parallel_mode) dist.broadcast(param, src=ranks[0], group=gpc.get_group(parallel_mode)) def is_dp_rank_0(): return not gpc.is_initialized(ParallelMode.DATA) or gpc.is_first_rank(ParallelMode.DATA) def is_tp_rank_0(): return not gpc.is_initialized(ParallelMode.TENSOR) or gpc.is_first_rank(ParallelMode.TENSOR) def is_no_pp_or_last_stage(): return not gpc.is_initialized(ParallelMode.PIPELINE) or gpc.is_last_rank(ParallelMode.PIPELINE) def is_using_ddp(): return gpc.is_initialized(ParallelMode.DATA) and gpc.get_world_size(ParallelMode.DATA) > 1 def is_using_pp(): return gpc.is_initialized(ParallelMode.PIPELINE) and gpc.get_world_size(ParallelMode.PIPELINE) > 1 def is_using_sequence(): return gpc.is_initialized(ParallelMode.SEQUENCE) and gpc.get_world_size(ParallelMode.SEQUENCE) > 1 @contextmanager def conditional_context(context_manager, enable=True): if enable: with context_manager: yield else: yield class model_branch_context(object): def __enter__(self): self.env_status = env.save() def __exit__(self, *exc_info): env.load(**self.env_status) def is_model_parallel_parameter(p): return hasattr(p, IS_TENSOR_PARALLEL) and getattr(p, IS_TENSOR_PARALLEL) def _calc_l2_norm(grads): norm = 0.0 if len(grads) > 0: dummy_overflow_buf = torch.cuda.IntTensor([0]) norm, _ = multi_tensor_applier( colossal_C.multi_tensor_l2norm, dummy_overflow_buf, [grads], False # no per-parameter norm ) return norm def _calc_lp(grads, norm_type): norm = 0.0 for grad in grads: grad_norm = torch.norm(grad, norm_type) norm += grad_norm**norm_type return norm def _move_norm_to_cuda(norm: Union[float, torch.Tensor]) -> Union[float, torch.Tensor]: if torch.is_tensor(norm) and norm.device.type != 'cuda': norm = norm.to(torch.cuda.current_device()) return norm # ======== Gradient Clipping ========= def clip_grad_norm_fp32(parameters, max_norm, norm_type=2): """Clips gradient norm of an iterable of parameters whose gradients are in fp32. This is adapted from :func:`torch.nn.utils.clip_grad.clip_grad_norm_` and added functionality to handle model parallel parameters. Note: the gradients are modified in place. Args: parameters (Iterable[:class:`torch.tensor`] or :class:`torch.tensor`): An iterable of Tensors or a single Tensor that will have gradients normalized. max_norm (Union[float, int]): Max norm of the gradients. norm_type (Union[float, int, 'inf']): Type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: float: Total norm of the parameters. """ if isinstance(parameters, torch.Tensor): parameters = [parameters] # Filter parameters based on: # - grad should not be none # - parameter should not be shared # - should not be a replica due to tensor model parallelism params: List[Parameter] = [] has_zero_shared_param: bool = False for param in parameters: if param.grad is not None: # Make sure the grads are in fp32 assert param.grad.dtype == torch.float, \ f'expected gradient to be dtype torch.float, but got {param.grad.type()}' if hasattr(param, 'zero_is_sharded'): has_zero_shared_param = True params.append(param) if len(params) == 0: return 0.0 # Norm parameters. max_norm = float(max_norm) norm_type = float(norm_type) # Parameters can be on CPU or CUDA # If parameters are on CPU, disable CUDA kernerls enable_cuda_kernels = params[0].grad.device.type == 'cuda' # Calculate norm. if norm_type == inf: total_norm = max(p.grad.data.abs().max() for p in params) total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]) # Take max across all model-parallel GPUs. if gpc.is_initialized(ParallelMode.MODEL) and gpc.get_world_size(ParallelMode.MODEL) > 1: dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=gpc.get_group(ParallelMode.MODEL), async_op=False) if has_zero_shared_param: dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=gpc.get_group(ParallelMode.DATA), async_op=False) total_norm = total_norm_cuda[0].item() else: tensor_parallel_grads = [] no_tensor_parallel_grads = [] zero_sharded_grads = [] for p in params: if is_model_parallel_parameter(p): reductor = (gpc.get_world_size(ParallelMode.TENSOR) / getattr(p, NUM_PARTITIONS))**(1 / norm_type) tensor_parallel_grads.append(p.grad.data / reductor) elif hasattr(p, 'zero_is_sharded'): zero_sharded_grads.append(p.grad.data) else: no_tensor_parallel_grads.append(p.grad.data) if norm_type == 2.0 and enable_cuda_kernels: tensor_parallel_norm = _calc_l2_norm(tensor_parallel_grads)**norm_type no_tensor_parallel_norm = _calc_l2_norm(no_tensor_parallel_grads)**norm_type zero_sharded_norm = _calc_l2_norm(zero_sharded_grads)**norm_type else: tensor_parallel_norm = _calc_lp(tensor_parallel_grads, norm_type) no_tensor_parallel_norm = _calc_lp(no_tensor_parallel_grads, norm_type) zero_sharded_norm = _calc_lp(zero_sharded_grads, norm_type) # If grads are on CPU, the norms is also on CPU. Cast them to CUDA tensors if not enable_cuda_kernels: tensor_parallel_norm = _move_norm_to_cuda(tensor_parallel_norm) no_tensor_parallel_norm = _move_norm_to_cuda(no_tensor_parallel_norm) zero_sharded_norm = _move_norm_to_cuda(zero_sharded_norm) # Sum across all model-parallel GPUs. if gpc.is_initialized(ParallelMode.TENSOR) and len(tensor_parallel_grads) > 0: dist.all_reduce(tensor_parallel_norm, op=dist.ReduceOp.SUM, group=gpc.get_group(ParallelMode.TENSOR)) # Sum across all zero sharded GPUs if len(zero_sharded_grads) > 0: dist.all_reduce(zero_sharded_norm, group=gpc.get_group(ParallelMode.DATA)) no_tensor_parallel_norm += zero_sharded_norm total_norm = tensor_parallel_norm + no_tensor_parallel_norm if gpc.is_initialized(ParallelMode.PIPELINE) and gpc.get_world_size(ParallelMode.PIPELINE) > 1: dist.all_reduce(total_norm, op=dist.ReduceOp.SUM, group=gpc.get_group(ParallelMode.PIPELINE)) total_norm = total_norm**(1.0 / norm_type) if torch.is_tensor(total_norm): total_norm = total_norm.item() # Scale. clip_coeff = max_norm / (total_norm + 1.0e-6) if clip_coeff < 1.0: if enable_cuda_kernels: grads = [p.grad.detach() for p in params] dummy_overflow_buf = torch.cuda.IntTensor([0]) multi_tensor_applier(colossal_C.multi_tensor_scale, dummy_overflow_buf, [grads, grads], clip_coeff) else: for p in params: p.grad.detach().mul_(clip_coeff) return total_norm def count_zeros_fp32(parameters): if isinstance(parameters, torch.Tensor): parameters = [parameters] # Filter parameters based on: # - grad should not be none # - parameter should not be shared # - should not be a replica due to tensor model parallelism total_num_zeros = 0.0 for param in parameters: grad_not_none = param.grad is not None is_not_tp_duplicate = param_is_not_tensor_parallel_duplicate(param) if grad_not_none and is_not_tp_duplicate: grad = param.grad.detach() num_zeros = grad.numel() - torch.count_nonzero(grad) total_num_zeros = num_zeros + total_num_zeros total_num_zeros = torch.IntTensor([int(total_num_zeros)]).cuda() # Sum across all model-parallel GPUs. ops = [] ops.append( dist.all_reduce(total_num_zeros, op=dist.ReduceOp.SUM, group=gpc.get_group(ParallelMode.TENSOR), async_op=True)) if gpc.is_initialized(ParallelMode.PIPELINE): ops.append( dist.all_reduce(total_num_zeros, op=dist.ReduceOp.SUM, group=gpc.get_group(ParallelMode.PIPELINE), async_op=True)) for req in ops: req.wait() total_num_zeros = total_num_zeros.item() return total_num_zeros def copy_tensor_parallel_attributes(src_tensor, dst_tensor): for attr in TENSOR_PARALLEL_ATTRIBUTES: if hasattr(src_tensor, attr): val = getattr(src_tensor, attr) setattr(dst_tensor, attr, val) def param_is_not_tensor_parallel_duplicate(param): return (hasattr(param, IS_TENSOR_PARALLEL) and getattr(param, IS_TENSOR_PARALLEL)) or (gpc.get_local_rank( ParallelMode.TENSOR) == 0) @contextmanager def switch_virtual_pipeline_parallel_rank(rank): prev_rank = gpc.virtual_pipeline_parallel_rank try: gpc.set_virtual_pipeline_parallel_rank(rank) yield finally: gpc.set_virtual_pipeline_parallel_rank(prev_rank) def disposable(func: Callable) -> Callable: executed = False @functools.wraps(func) def wrapper(*args, **kwargs): nonlocal executed if not executed: executed = True return func(*args, **kwargs) return wrapper
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch def set_to_cuda(models): """Send model to gpu. :param models: nn.module or a list of module """ if isinstance(models, list) and len(models) > 1: ret = [] for model in models: ret.append(model.to(get_current_device())) return ret elif isinstance(models, list): return models[0].to(get_current_device()) else: return models.to(get_current_device()) def get_current_device() -> torch.device: """ Returns currently selected device (gpu/cpu). If cuda available, return gpu, otherwise return cpu. """ if torch.cuda.is_available(): return torch.device(f'cuda:{torch.cuda.current_device()}') else: return torch.device('cpu') def synchronize(): """Similar to cuda.synchronize(). Waits for all kernels in all streams on a CUDA device to complete. """ if torch.cuda.is_available(): torch.cuda.synchronize() def empty_cache(): """Similar to cuda.empty_cache() Releases all unoccupied cached memory currently held by the caching allocator. """ if torch.cuda.is_available(): torch.cuda.empty_cache()
import torch.nn as nn import torch.distributed as dist from colossalai.core import global_context as gpc from colossalai.context.moe_context import MOE_CONTEXT from colossalai.context import ParallelMode from .common import is_using_ddp from typing import Dict, List def get_moe_epsize_param_dict(model: nn.Module) -> Dict[int, List[nn.Parameter]]: """Returns a parameter dictionary, the key of which is the expert parallel size of every parameter. Since the parameters in data parallelism is replicated in each GPU, we set their ep_size to 1. Args: model (:class:`torch.nn.Module`): A pyTorch `nn.Module` from which we get dict. """ epsize_param_dict = dict() for param in model.parameters(): if not hasattr(param, 'moe_info'): ep_size = 1 # set ep_size to 1 for dp parameters else: ep_size = param.moe_info.ep_size if ep_size not in epsize_param_dict: epsize_param_dict[ep_size] = [] epsize_param_dict[ep_size].append(param) return epsize_param_dict def sync_moe_model_param(model: nn.Module): """Make sure model parameters are consistent in MoE parallel context. Args: model (:class:`torch.nn.Module`): A pyTorch model on whose parameters you check the consistency. """ if is_using_ddp(): param_dict = get_moe_epsize_param_dict(model) # synchrosize the parameters whose dp_group is the whole world if 1 in param_dict: src_rank = gpc.get_ranks_in_group(ParallelMode.DATA)[0] for param in param_dict[1]: dist.broadcast(param, src=src_rank, group=gpc.get_group(ParallelMode.DATA)) for ep_size in param_dict: # When ep_size = world_size, communication is not needed if ep_size != 1 and ep_size != MOE_CONTEXT.world_size: src_rank = dist.get_rank(MOE_CONTEXT.parallel_info_dict[ep_size].ep_group) for param in param_dict[ep_size]: dist.broadcast(param, src=src_rank, group=param.moe_info.dp_group)
from collections import OrderedDict from itertools import chain import torch import torch.distributed as dist from colossalai.communication.collective import scatter_object_list from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc try: from torch.nn.modules.module import _EXTRA_STATE_KEY_SUFFIX except ImportError: _EXTRA_STATE_KEY_SUFFIX = '_extra_state' from .common import is_using_pp __all__ = ["save_checkpoint", "load_checkpoint"] def broadcast_state_dict(state_dict, parallel_mode): state_dict = [state_dict.copy() if isinstance(state_dict, dict) else state_dict] src_rank = gpc.get_ranks_in_group(parallel_mode)[0] dist.broadcast_object_list(state_dict, src=src_rank, group=gpc.get_cpu_group(parallel_mode)) return state_dict[0] def partition_tensor_parallel_state_dict(state_dict: OrderedDict, parallel_mode: ParallelMode, dims: dict = dict(), partition_states: dict = dict()): src_rank = gpc.get_ranks_in_group(parallel_mode)[0] depth = gpc.get_world_size(parallel_mode) if gpc.get_local_rank(parallel_mode) == 0: partitioned_state_list = [dict() for _ in range(depth)] for key in list(state_dict.keys()): param = state_dict.pop(key) dim = dims.get(key, 0) do_partition = partition_states.get(key, True) if do_partition: param = torch.chunk(param, depth, dim=dim) for i, p in enumerate(partitioned_state_list): p[key] = param[i] if do_partition else param else: partitioned_state_list = [None for _ in range(depth)] partitioned_state = [None] scatter_object_list(partitioned_state, partitioned_state_list, src=src_rank, group=gpc.get_cpu_group(parallel_mode)) return partitioned_state[0] def gather_tensor_parallel_state_dict( state_dict: OrderedDict, parallel_mode: ParallelMode, dims: dict = dict(), partition_states: dict = dict(), keep_vars: bool = False, ): dst_rank = gpc.get_ranks_in_group(parallel_mode)[0] depth = gpc.get_world_size(parallel_mode) for key in list(state_dict.keys()): param = state_dict.pop(key) param = param if keep_vars else param.detach() dim = dims.get(key, 0) do_partition = partition_states.get(key, True) if do_partition: temp = param.transpose(0, dim).contiguous() gather_list = None if gpc.get_local_rank(parallel_mode) == 0: shape = list(param.shape) shape[0], shape[dim] = shape[dim], shape[0] shape[0] *= depth param = torch.empty(shape, dtype=param.dtype, device=param.device) gather_list = list(torch.chunk(param, depth, dim=0)) dist.gather(temp, gather_list, dst=dst_rank, group=gpc.get_cpu_group(parallel_mode)) param = torch.transpose(param, 0, dim) # update params in state_dict only on local rank 0 if gpc.get_local_rank(parallel_mode) == 0: state_dict[key] = param return state_dict def _send_state_dict(state_dict, dst, parallel_mode): state_tensor, state_size = dist.distributed_c10d._object_to_tensor(state_dict) dist.send(state_size, dst, group=gpc.get_cpu_group(parallel_mode)) dist.send(state_tensor, dst, group=gpc.get_cpu_group(parallel_mode)) def _recv_state_dict(src, parallel_mode): state_size = torch.tensor([0], dtype=torch.long) dist.recv(state_size, src, group=gpc.get_cpu_group(parallel_mode)) state_tensor = torch.empty(state_size.item(), dtype=torch.uint8) dist.recv(state_tensor, src, group=gpc.get_cpu_group(parallel_mode)) state_dict = dist.distributed_c10d._tensor_to_object(state_tensor, state_size) return state_dict def partition_pipeline_parallel_state_dict(model, state_dict): pipeline_state = OrderedDict() if gpc.get_local_rank(ParallelMode.TENSOR) == 0: # receive all states from prev stage if not gpc.is_first_rank(ParallelMode.PIPELINE): state_dict = _recv_state_dict(gpc.get_prev_global_rank(ParallelMode.PIPELINE), ParallelMode.PIPELINE) # move states to output for name, _ in model.named_parameters(recurse=True): if name in state_dict: pipeline_state[name] = state_dict.pop(name) for name, _ in model.named_buffers(recurse=True): if name in state_dict: pipeline_state[name] = state_dict.pop(name) for name, _ in model.named_modules(): extra_state_key = name + "." + _EXTRA_STATE_KEY_SUFFIX if extra_state_key in state_dict: pipeline_state[extra_state_key] = state_dict.pop(extra_state_key) # send rest states to next stage if not gpc.is_last_rank(ParallelMode.PIPELINE): _send_state_dict(state_dict, gpc.get_next_global_rank(ParallelMode.PIPELINE), ParallelMode.PIPELINE) return pipeline_state def gather_pipeline_parallel_state_dict(state_dict): gathered_states = ([None for _ in range(gpc.get_world_size(ParallelMode.PIPELINE))] if gpc.get_local_rank(ParallelMode.PIPELINE) == 0 else None) dist.gather_object( state_dict, gathered_states, dst=gpc.get_ranks_in_group(ParallelMode.PIPELINE)[0], group=gpc.get_cpu_group(ParallelMode.PIPELINE), ) state_dict = (OrderedDict(chain.from_iterable(state.items() for state in gathered_states)) if gpc.get_local_rank(ParallelMode.PIPELINE) == 0 else OrderedDict()) return state_dict def save_checkpoint(file, epoch: int, model: torch.nn.Module, optimizer: torch.optim.Optimizer = None, lr_scheduler: torch.optim.lr_scheduler._LRScheduler = None, **kwargs): """Stores the checkpoint to disk. Saves all the training components' parameters or buffers, such as model, optimizer, lr_scheduler etc. into a checkpoint dictionary. Args: file: a file-like object (has to implement write and flush) or a string or os.PathLike object containing a file name. epoch (int): Epoch number (indicates how many epochs have you trained this model). model (:class:`torch.nn.Module`): Model to be saved. optimizer (Union[:class:`torch.optim.Optimizer`, :class:`colossalai.nn.optimizer`]): Optimizer to be saved. lr_scheduler (Union[:class:`torch.optim.lr_scheduler`, :class:`colossalai.nn.lr_scheduler`], optional): lr_scheduler to be saved, defaults to None. pickle_module: module used for pickling metadata and objects pickle_protocol: can be specified to override the default protocol """ # ckpt container checkpoint = {"epoch": epoch} model_state = model.state_dict() if is_using_pp() and gpc.get_local_rank(ParallelMode.TENSOR) == 0: model_state = gather_pipeline_parallel_state_dict(model_state) if gpc.get_global_rank() == 0: checkpoint["model"] = model_state # if optimizer is not None: # checkpoint['optimizer'] = optimizer.state_dict() # if lr_scheduler is not None: # checkpoint['lr_scheduler'] = lr_scheduler.state_dict() torch.save(checkpoint, file, **kwargs) def load_checkpoint( file, model: torch.nn.Module, optimizer: torch.optim.Optimizer = None, lr_scheduler: torch.optim.lr_scheduler._LRScheduler = None, strict: bool = True, ): """Loads training states from a checkpoint file. Args: file: a file-like object (has to implement read(), readline(), tell(), and seek()), or a string or os.PathLike object containing a file name. model (:class:`torch.nn.Module`): Model to load saved weights and buffers. optimizer (Union[:class:`torch.optim.Optimizer`, :class:`colossalai.nn.optimizer`]): Optimizer to recuperate. lr_scheduler (:class:`torch.optim.lr_scheduler._LRScheduler`, optional): lr_scheduler to recuperate, defaults to None. strict (bool, optional): Whether to strictly enforce that the keys in :attr:`state_dict` of the checkpoint match the names of parameters and buffers in model, defaults to True. Returns: int: The saved epoch number. Raises: RuntimeError: Raise error if the model/optimizer cannot successfully be recuperated """ state_dict = (torch.load(file, map_location=torch.device("cpu")) if gpc.get_local_rank(ParallelMode.MODEL) == 0 else None) # model states model_state = state_dict.pop("model") if state_dict is not None else dict() # pipeline if is_using_pp(): model_state = partition_pipeline_parallel_state_dict(model, model_state) try: model.load_state_dict(model_state, strict=strict) except RuntimeError as e: error_msgs = str(e) if error_msgs.startswith("Error(s) in loading state_dict for "): error_msgs = error_msgs.split("\n\t")[1:] dst_rank = gpc.get_ranks_in_group(ParallelMode.MODEL)[0] all_error_msgs = [None for _ in range(gpc.get_world_size(ParallelMode.MODEL))] dist.gather_object(error_msgs, all_error_msgs, dst=dst_rank, group=gpc.get_cpu_group(ParallelMode.MODEL)) if gpc.get_global_rank() == 0: all_error_msgs = list(chain.from_iterable(all_error_msgs)) raise RuntimeError("Error(s) in loading state_dict for {}:\n\t{}".format( model.__class__.__name__, "\n\t".join(all_error_msgs))) else: raise e # broadcast the rest states state_dict = broadcast_state_dict(state_dict, ParallelMode.MODEL) # # optimizer states # if optimizer is not None and 'optimizer' in state_dict: # optimizer.load_state_dict(state_dict['optimizer']) # # lr scheduler states # if lr_scheduler is not None and 'lr_scheduler' in state_dict: # lr_scheduler.load_state_dict(state_dict['lr_scheduler']) # last epoch last_epoch = state_dict.pop("epoch", -1) return last_epoch
from colossalai.context.singleton_meta import SingletonMeta import torch from typing import Tuple, Optional from colossalai.logging import DistributedLogger def colo_model_optimizer_usage(optim) -> Tuple[int, int]: """Trace the optimizer memory usage Args: optim (ShardedOptimV2): an instance of ShardedOptimver Returns: Tuple[int, int]: cuda/cpu memory usage in Byte """ if optim is None: return 0, 0 assert hasattr(optim, 'get_memory_usage'), f"{type(optim)} has no attr get_memory_usage()" return optim.get_memory_usage() def colo_model_mem_usage(model: torch.nn.Module) -> Tuple[int, int]: """ Trace the model memory usage. Args: model (torch.nn.Module): a torch model Returns: Tuple[int, int]: cuda memory usage in Byte, cpu memory usage in Byte """ if model is None: return 0, 0 def _get_tensor_mem_use(t: Optional[torch.Tensor]): if t is None: return 0, 0 assert isinstance(t, torch.Tensor) _cpu_mem_usage, _cuda_mem_usage = 0, 0 if t.device.type == 'cpu': _cpu_mem_usage += t.numel() * t.element_size() elif t.device.type == 'cuda': _cuda_mem_usage += t.numel() * t.element_size() return _cuda_mem_usage, _cpu_mem_usage cuda_mem_usage = 0 cpu_mem_usage = 0 for param in model.parameters(): if hasattr(param, 'colo_attr'): t_cuda, t_cpu = param.colo_attr.get_memory_usage() cuda_mem_usage += t_cuda cpu_mem_usage += t_cpu else: t_cuda, t_cpu = _get_tensor_mem_use(param.data) cuda_mem_usage += t_cuda cpu_mem_usage += t_cpu t_cuda, t_cpu = _get_tensor_mem_use(param.grad) cuda_mem_usage += t_cuda cpu_mem_usage += t_cpu return cuda_mem_usage, cpu_mem_usage class ModelDataTracer(metaclass=SingletonMeta): """ A tracer singleton to trace model data usage during runtime. You have to register a model on the singleton first. """ def __init__(self) -> None: self._logger = DistributedLogger("ModelDataTracer") self._model = None self._opitimizer = None def _get_mem_usage(self) -> Tuple[int, int]: """ get the memory usage of the model registered. Returns: Tuple[int, int]: cuda, cpu mem usage """ cuda_use_opt, cpu_use_opt = colo_model_optimizer_usage(self._opitimizer) cuda_use_model, cpu_use_model = colo_model_mem_usage(self._model) return cuda_use_opt + cuda_use_model, cpu_use_opt + cpu_use_model def register_model(self, model) -> None: if self._model is not None: self._logger.warning("ModelDataTracer has already registered a model") self._model = model def register_optimizer(self, optimizer) -> None: if self._opitimizer is not None: self._logger.warning("ModelDataTracer has already registered an optimizer") self._opitimizer = optimizer @property def cpu_usage(self): _, cpu_usage = self._get_mem_usage() return cpu_usage @property def cuda_usage(self): cuda_usage, _ = self._get_mem_usage() return cuda_usage @property def both_mem_usage(self): return self._get_mem_usage() GLOBAL_MODEL_DATA_TRACER = ModelDataTracer()
from .memory_monitor import AsyncMemoryMonitor, SyncCudaMemoryMonitor from .memstats_collector import MemStatsCollector __all__ = ['AsyncMemoryMonitor', 'SyncCudaMemoryMonitor', 'MemStatsCollector']
from abc import abstractmethod from concurrent.futures import ThreadPoolExecutor from time import sleep, time import json import torch from colossalai.utils.memory import colo_device_memory_used from colossalai.utils import get_current_device class MemoryMonitor: """Base class for all types of memory monitor. All monitors should have a list called `time_stamps` and a list called `mem_stats`. """ def __init__(self): self.time_stamps = [] self.mem_stats = [] def __len__(self): return len(self.mem_stats) @abstractmethod def start(self): pass @abstractmethod def finish(self): pass def state_dict(self): return { "time_stamps": self.time_stamps, "mem_stats": self.mem_stats, } def save(self, filename): with open(filename, "w") as f: json.dump(self.state_dict(), f) def clear(self): self.mem_stats.clear() self.time_stamps.clear() class AsyncMemoryMonitor(MemoryMonitor): """ An Async Memory Monitor runing during computing. Sampling memory usage of the current GPU at interval of `1/(10**power)` sec. The idea comes from Runtime Memory Tracer of PatrickStar `PatrickStar: Parallel Training of Pre-trained Models via Chunk-based Memory Management`_ Usage:: async_mem_monitor = AsyncMemoryMonitor() input = torch.randn(2, 20).cuda() OP1 = torch.nn.Linear(20, 30).cuda() OP2 = torch.nn.Linear(30, 40).cuda() async_mem_monitor.start() output = OP1(input) async_mem_monitor.finish() async_mem_monitor.start() output = OP2(output) async_mem_monitor.finish() async_mem_monitor.save('log.pkl') Args: power (int, optional): the power of time interva. Defaults to 10. .. _PatrickStar: Parallel Training of Pre-trained Models via Chunk-based Memory Management: https://arxiv.org/abs/2108.05818 """ def __init__(self, power: int = 10): super().__init__() self.keep_measuring = False current_device = get_current_device() def _set_cuda_device(): torch.cuda.set_device(current_device) self.executor = ThreadPoolExecutor(max_workers=1, initializer=_set_cuda_device) self.monitor_thread = None self.interval = 1 / (10**power) def set_interval(self, power: int): self.clear() self.interval = 1 / (10**power) def is_measuring(self): return self.keep_measuring def start(self): self.keep_measuring = True self.monitor_thread = self.executor.submit(self._measure_usage) def finish(self): if self.keep_measuring is False: return 0 self.keep_measuring = False max_usage = self.monitor_thread.result() self.monitor_thread = None self.time_stamps.append(time()) self.mem_stats.append(max_usage) return max_usage def _measure_usage(self): max_usage = 0 while self.keep_measuring: max_usage = max( max_usage, colo_device_memory_used(get_current_device()), ) sleep(self.interval) return max_usage class SyncCudaMemoryMonitor(MemoryMonitor): """ A synchronized cuda memory monitor. It only record the maximum allocated cuda memory from start point to finish point. """ def __init__(self, power: int = 10): super().__init__() def start(self): torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() def finish(self): torch.cuda.synchronize() self.time_stamps.append(time()) max_usage = torch.cuda.max_memory_allocated() self.mem_stats.append(max_usage) return max_usage
from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER from colossalai.utils.memory import colo_device_memory_used from colossalai.utils.memory_tracer import SyncCudaMemoryMonitor import torch import time from typing import List class MemStatsCollector: """ A Memory statistic collector. It works in two phases. Phase 1. Collection Phase: collect memory usage statistics of CPU and GPU. The first iteration of DNN training. Phase 2. Runtime Phase: use the read-only collected stats The rest iterations of DNN training. It has a Sampling counter which is reset after DNN training iteration. """ def __init__(self) -> None: self._mem_monitor = SyncCudaMemoryMonitor() self._model_data_cuda_list = [] self._overall_cuda_list = [] self._model_data_cpu_list = [] self._overall_cpu_list = [] self._non_model_data_cuda_list = [] self._non_model_data_cpu_list = [] self._sampling_time = [] self._start_flag = False self._step_idx = 0 self._step_total = 0 def overall_mem_stats(self, device_type: str) -> List[int]: if device_type == 'cuda': return self._overall_cuda_list elif device_type == 'cpu': return self._overall_cpu_list else: raise TypeError def model_data_list(self, device_type: str) -> List[int]: if device_type == 'cuda': return self._model_data_cuda_list elif device_type == 'cpu': return self._model_data_cpu_list else: raise TypeError def non_model_data_list(self, device_type: str) -> List[int]: if device_type == 'cuda': return self._non_model_data_cuda_list elif device_type == 'cpu': return self._non_model_data_cpu_list else: raise TypeError def next_period_non_model_data_usage(self, device_type: str) -> int: """Get max non model data memory usage of current sampling period Args: device_type (str): device type, can be 'cpu' or 'cuda'. Returns: int: max non model data memory usage of current sampling period """ assert not self._start_flag, 'Cannot get mem stats info during collection phase.' assert self._step_total > 0, 'Cannot get mem stats info before collection phase.' next_non_model_data = self.non_model_data_list(device_type)[self._step_idx] self._step_idx = (self._step_idx + 1) % self._step_total return next_non_model_data @property def sampling_time(self): return [t - self._sampling_time[0] for t in self._sampling_time] def start_collection(self): self._start_flag = True self._mem_monitor.start() def finish_collection(self): self.sample_overall_data() self._step_total = len(self._sampling_time) self._start_flag = False self._mem_monitor.finish() def sample_model_data(self) -> None: """Sampling model data statistics. """ if self._start_flag: cuda_mem, cpu_mem = GLOBAL_MODEL_DATA_TRACER.both_mem_usage self._model_data_cuda_list.append(cuda_mem) self._model_data_cpu_list.append(cpu_mem) def sample_overall_data(self) -> None: """Sampling non model data statistics. """ if self._start_flag: # overall data recording is after model data recording if len(self._model_data_cuda_list) == 0: return self._overall_cuda_list.append(self._mem_monitor.finish()) self._overall_cpu_list.append(colo_device_memory_used(torch.device('cpu'))) assert len(self._model_data_cuda_list) == len(self._overall_cuda_list) self._non_model_data_cuda_list.append(self._overall_cuda_list[-1] - self._model_data_cuda_list[-1]) self._non_model_data_cpu_list.append(self._overall_cpu_list[-1] - self._model_data_cpu_list[-1]) self._sampling_time.append(time.time()) self._mem_monitor.start() def sample_memstats(self) -> None: """ Sampling memory statistics. Record the current model data CUDA memory usage as well as system CUDA memory usage. Advance the sampling cnter. """ if self._start_flag: self._model_data_cuda_list.append(GLOBAL_MODEL_DATA_TRACER.cuda_usage) self._overall_cuda_list.append(self._mem_monitor.finish()) self._non_model_data_cuda_list.append(self._overall_cuda_list[-1] - self._model_data_cuda_list[-1]) self._model_data_cpu_list.append(GLOBAL_MODEL_DATA_TRACER.cpu_usage) # FIXME(jiaruifang) cpu sys used should also return from self._mem_monitor() self._overall_cpu_list.append(colo_device_memory_used(torch.device(f'cpu'))) self._non_model_data_cpu_list.append(self._overall_cpu_list[-1] - self._model_data_cpu_list[-1]) self._sampling_time.append(time.time()) self._mem_monitor.start() def clear(self) -> None: self._model_data_cuda_list = [] self._overall_cuda_list = [] self._model_data_cpu_list = [] self._overall_cpu_list = [] self._start_flag = False self._step_idx = 0 self._step_total = 0
from .multi_tensor_apply import MultiTensorApply multi_tensor_applier = MultiTensorApply(2048 * 32)
# modified from https://github.com/NVIDIA/apex/blob/master/apex/multi_tensor_apply/multi_tensor_apply.py class MultiTensorApply(object): """ Apply an operation to a list of tensors efficiently. Args: chunk_size (int): Size of a chunk. """ available = False warned = False def __init__(self, chunk_size): try: import colossal_C MultiTensorApply.available = True self.chunk_size = chunk_size except ImportError as err: MultiTensorApply.available = False MultiTensorApply.import_err = err def check_avail(self): if not MultiTensorApply.available: raise RuntimeError( "Attempted to call MultiTensorApply method, but MultiTensorApply " "is not available, possibly because Apex was installed without " "--cpp_ext --cuda_ext. Original import error message:", MultiTensorApply.import_err) def __call__(self, op, noop_flag_buffer, tensor_lists, *args): self.check_avail() return op(self.chunk_size, noop_flag_buffer, tensor_lists, *args)
import torch.nn as nn from typing import List from colossalai.engine import BaseGradientHandler from typing import Iterable from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from ._gradient_accumulation import GradAccumDataloader, GradAccumOptimizer, GradAccumLrSchedulerByStep, GradAccumGradientHandler def accumulate_gradient(model: nn.Module, optimizer: Optimizer, dataloader: Iterable, accumulate_size: int, gradient_handlers: List[BaseGradientHandler] = None, lr_scheduler: _LRScheduler = None): r"""Turning model, optimizer, dataloader into corresponding object for gradient accumulation. Args: model (:class:`torch.nn.Module`): your model object for gradient accumulation. optimizer (:class:`torch.optim.Optimizer`): your optimizer object for gradient accumulation. dataloader (:class:`torch.utils.data.DataLoader` or iterable objects): your dataloader object, would be called like iter(dataloader) accumulate_size (int): the number of steps to accumulate gradients gradient_handlers (List[:class:`colossalai.engine.BaseGradientHandler`]): list of gradient handler objects. Default is None. lr_scheduler (`torch.optim.lr_scheduler` or `colossalai.nn.lr_scheduler`): your ``lr_scheduler`` object for gradient accumulation. Defaults to None. More details about `gradient_handlers` could be found in `Gradient_handler <https://github.com/hpcaitech/ColossalAI/tree/main/colossalai/engine/gradient_handler>`_. More details about `lr_scheduler` could be found `lr_scheduler <https://github.com/hpcaitech/ColossalAI/tree/main/colossalai/nn/lr_scheduler>`_. and `how to adjust learning rate <https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate>`_. """ optimizer = GradAccumOptimizer(optimizer, accumulate_size=accumulate_size, model=model) dataloader = GradAccumDataloader(dataloader, accumulate_size=accumulate_size) if gradient_handlers is not None: gradient_handlers = [GradAccumGradientHandler(handler, accumulate_size) for handler in gradient_handlers] if lr_scheduler is not None: lr_scheduler = GradAccumLrSchedulerByStep(lr_scheduler, accumulate_size=accumulate_size) return optimizer, dataloader, gradient_handlers, lr_scheduler __all__ = ['accumulate_gradient', 'GradAccumDataloader', 'GradAccumOptimizer', 'GradAccumLrSchedulerByStep', 'GradAccumGradientHandler']
#!/usr/bin/env python # -*- encoding: utf-8 -*- import torch.nn as nn from torch import Tensor from typing import Iterable, Any from colossalai.nn.optimizer import ColossalaiOptimizer from torch.nn.parallel.distributed import DistributedDataParallel from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from torch.utils.data import DataLoader from colossalai.utils import conditional_context from colossalai.engine import BaseGradientHandler class GradAccumOptimizer(ColossalaiOptimizer): """A wrapper for the optimizer to enable gradient accumulation by skipping the steps before accumulation size is reached. Args: optim (:class:`torch.optim.Optimizer`): Your optimizer object for gradient accumulation. accumulate_size (int): The number of steps to accumulate gradients. model (:class:`torch.nn.Module`): Your model object to check if it is DistributedDataParallel for special handling of no_sync() context. """ def __init__(self, optim: Optimizer, accumulate_size: int, model: nn.Module = None): super().__init__(optim) self.accumulate_size = accumulate_size self.accumulate_step = 0 # handle pytorch ddp auto all reduce self.model = model self.is_torch_ddp = isinstance(self.model, DistributedDataParallel) def zero_grad(self, *args, **kwargs): if self.accumulate_step == 0: self.optim.zero_grad(*args, **kwargs) def step(self, *args, **kwargs): if self.accumulate_step < self.accumulate_size: return None else: self.accumulate_step = 0 return self.optim.step(*args, **kwargs) def clip_grad_norm(self, model: nn.Module, max_norm: float): if self.accumulate_step < self.accumulate_size: pass else: self.optim.clip_grad_norm(model, max_norm) def backward(self, loss: Tensor): self.accumulate_step += 1 if self.is_torch_ddp: no_sync = self.accumulate_step < self.accumulate_size with conditional_context(self.model.no_sync(), enable=no_sync): scaled_loss = loss / self.accumulate_size self.optim.backward(scaled_loss) else: scaled_loss = loss / self.accumulate_size self.optim.backward(scaled_loss) def backward_by_grad(self, tensor: Tensor, grad: Tensor): self.accumulate_step += 1 no_sync = self.is_torch_ddp and self.accumulate_step < self.accumulate_size if no_sync: with self.model.no_sync(): self.optim.backward_by_grad(tensor, grad) else: self.optim.backward_by_grad(tensor, grad) class GradAccumDataloader: """A wrapper for dataloader to enable gradient accumulation by dropping the last incomplete steps. Note: The dataloader would drop the last incomplete steps for gradient accumulation. For example, if a dataloader has 10 batches of data and accumulate size is 4. The model parameters will be updated only twice at step 4 and step 8. The last two batches of data do not form a complete 4-step cycle. Thus, they will be automatically skipped by this class. If the dataloader is not standard PyTorch dataloader, (e.g. Dali dataloader), this class will automatically consume (load data for nothing) the remaining 2 batches. Args: optim (``Iterable``): Your dataloader object for gradient accumulation. accumulate_size (int): The number of steps to accumulate gradients. """ def __init__(self, dataloader: Iterable, accumulate_size: int) -> None: self.dataloader = dataloader self.consume_remain_data = not isinstance(dataloader, DataLoader) self.steps_per_epoch = len(dataloader) - len(dataloader) % accumulate_size def __getattr__(self, __name: str) -> Any: return getattr(self.dataloader, __name) def __len__(self): return self.steps_per_epoch def __iter__(self): self._cur_step = 0 self._dataiter = iter(self.dataloader) return self def __next__(self) -> Any: if self._cur_step < self.steps_per_epoch: self._cur_step += 1 if self._cur_step == self.steps_per_epoch and self.consume_remain_data: # this is to handle non standard pytorch dataloader # such as dali dataloader while True: try: _ = next(self._dataiter) except StopIteration: break return next(self._dataiter) else: raise StopIteration class GradAccumLrSchedulerByStep(_LRScheduler): """A wrapper for the LR scheduler to enable gradient accumulation by skipping the steps before accumulation size is reached. Args: lr_scheduler (:class:`torch.optim.lr_scheduler._LRScheduler`): Your ``lr_scheduler`` object for gradient accumulation. accumulate_size (int): The number of steps to accumulate gradients. """ def __init__(self, lr_scheduler: _LRScheduler, accumulate_size: int) -> None: self.lr_scheduler = lr_scheduler self.accumulate_size = accumulate_size self.accumulate_step = 0 @staticmethod def compute_effective_steps_per_epoch(dataloader: Iterable, accumulate_size: int): return len(dataloader) // accumulate_size def __getattr__(self, __name: str) -> Any: return getattr(self.lr_scheduler, __name) def step(self, *args, **kwargs): self.accumulate_step += 1 if self.accumulate_step < self.accumulate_size: pass else: self.accumulate_step = 0 self.lr_scheduler.step(*args, **kwargs) def get_lr(self): return self.lr_scheduler.get_lr() def get_last_lr(self): return self.lr_scheduler.get_last_lr() def print_lr(self, *args, **kwargs): self.lr_scheduler.print_lr(*args, **kwargs) def state_dict(self) -> dict: return self.lr_scheduler.state_dict() def load_state_dict(self, state_dict: dict) -> None: self.lr_scheduler.load_state_dict(state_dict) class GradAccumGradientHandler: r"""A wrapper for the gradient handler to enable gradient accumulation by skipping the steps before accumulation size is reached. Args: grad_handler (:class:`colossalai.engine.BaseGradientHandler`): Your ``gradient_handler`` object for gradient accumulation, would be called when achieving `accumulate_size`. accumulate_size (int): The number of steps to accumulate gradients. More details about ``gradient_handlers`` could be found in `Gradient_handler <https://github.com/hpcaitech/ColossalAI/tree/main/colossalai/engine/gradient_handler>`_. """ def __init__(self, grad_handler: BaseGradientHandler, accumulate_size: int) -> None: assert isinstance(grad_handler, BaseGradientHandler), \ f'expected grad_handler to be type BaseGradientHandler, but got {type(grad_handler)}' self.grad_handler = grad_handler self.accumulate_size = accumulate_size self.accumulate_step = 0 def handle_gradient(self): self.accumulate_step += 1 if self.accumulate_step < self.accumulate_size: pass else: self.accumulate_step = 0 self.grad_handler.handle_gradient()
#!/usr/bin/env python # -*- encoding: utf-8 -*- from abc import ABC, abstractmethod class BaseSampler(ABC): def __init__(self, dataset, batch_size): self.dataset = dataset self.batch_size = batch_size @abstractmethod def __len__(self): pass @abstractmethod def __iter__(self): pass
from .base_sampler import BaseSampler from .data_parallel_sampler import DataParallelSampler, get_dataloader __all__ = ['BaseSampler', 'DataParallelSampler', 'get_dataloader']
#!/usr/bin/env python # -*- encoding: utf-8 -*- # adpated from torch.utils.data.DistributedSampler import math import random import numpy as np from typing import TypeVar, Iterator import torch from torch.utils.data import Sampler, Dataset, DataLoader from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.registry import DATA_SAMPLERS T_co = TypeVar('T_co', covariant=True) @DATA_SAMPLERS.register_module class DataParallelSampler(Sampler): """A data sampler for distributed data parallelism. Args: dataset (:class:`torch.utils.data.Dataset`): The Dataset for sampling. shuffle (bool, optional): Whether to shuffle data, defaults to False. seed (int, optional): The random seed used for sampling, defaults to 0. drop_last (bool, optional): Set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller, defaults to False. """ def __init__(self, dataset: Dataset, shuffle: bool = False, seed: int = 0, drop_last: bool = False) -> None: self.dataset = dataset self.num_replicas = gpc.get_world_size(ParallelMode.DATA) self.rank = gpc.get_local_rank(ParallelMode.DATA) self.epoch = 0 self.drop_last = drop_last # If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. # type: ignore[arg-type] if self.drop_last and len(self.dataset) % self.num_replicas != 0: # Split to nearest available length that is evenly divisible. # This is to ensure each rank receives the same amount of data when # using this Sampler. self.num_samples = math.ceil( # `type:ignore` is required because Dataset cannot provide a default __len__ # see NOTE in pytorch/torch/utils/data/sampler.py (len(self.dataset) - self.num_replicas) / \ self.num_replicas # type: ignore[arg-type] ) else: self.num_samples = math.ceil( len(self.dataset) / self.num_replicas) # type: ignore[arg-type] self.total_size = self.num_samples * self.num_replicas self.shuffle = shuffle self.seed = seed def __iter__(self) -> Iterator[T_co]: if self.shuffle: # deterministically shuffle based on epoch and seed g = torch.Generator() g.manual_seed(self.seed + self.epoch) # type: ignore[arg-type] indices = torch.randperm(len(self.dataset), generator=g).tolist() # update for next epoch so that there is no need to call # set_epoch manually self.epoch += 1 else: indices = list(range(len(self.dataset))) # type: ignore[arg-type] if not self.drop_last: # add extra samples to make it evenly divisible padding_size = self.total_size - len(indices) if padding_size <= len(indices): indices += indices[:padding_size] else: indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size] else: # remove tail of data to make it evenly divisible. indices = indices[:self.total_size] assert len(indices) == self.total_size # subsample indices = indices[self.rank:self.total_size:self.num_replicas] assert len(indices) == self.num_samples return iter(indices) def __len__(self) -> int: return self.num_samples def set_epoch(self, epoch: int) -> None: r"""Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas use a different random ordering for each epoch. Otherwise, the next iteration of this sampler will yield the same ordering. Args: epoch (int): Epoch number. """ self.epoch = epoch def get_dataloader(dataset, shuffle=False, seed=1024, add_sampler=True, drop_last=False, pin_memory=False, num_workers=0, **kwargs): r"""Set up a deterministic dataloader (also configure seed workers, samplers and whether shuffle or not) Note: When pipeline parallel is enabled, shuffle cannot be True as it will result in mismatch between input data on the 1st stage and label on the last stage. Args: dataset (:class:`torch.utils.data.Dataset`): The dataset to be loaded. shuffle (bool, optional): Whether to shuffle the dataset. Defaults to False. seed (int, optional): Random worker seed for sampling, defaults to 1024. add_sampler: Whether to add ``DistributedDataParallelSampler`` to the dataset. Defaults to True. drop_last (bool, optional): Set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller, defaults to False. pin_memory (bool, optional): Whether to pin memory address in CPU memory. Defaults to False. num_workers (int, optional): Number of worker threads for this dataloader. Defaults to 0. kwargs (dict): optional parameters for ``torch.utils.data.DataLoader``, more details could be found in `DataLoader <https://pytorch.org/docs/stable/_modules/torch/utils/data/dataloader.html#DataLoader>`_. Returns: :class:`torch.utils.data.DataLoader`: A DataLoader used for training or testing. """ _kwargs = kwargs.copy() if add_sampler and gpc.is_initialized(ParallelMode.DATA) and gpc.get_world_size(ParallelMode.DATA) > 1: sampler = DataParallelSampler(dataset, shuffle=shuffle) else: sampler = None # Deterministic dataloader def seed_worker(worker_id): worker_seed = seed np.random.seed(worker_seed) torch.manual_seed(worker_seed) random.seed(worker_seed) if sampler is None: return DataLoader(dataset, worker_init_fn=seed_worker, shuffle=shuffle, drop_last=drop_last, pin_memory=pin_memory, num_workers=num_workers, **_kwargs) else: return DataLoader(dataset, sampler=sampler, worker_init_fn=seed_worker, drop_last=drop_last, pin_memory=pin_memory, num_workers=num_workers, **_kwargs)
import gc import inspect import torch import torch.nn as nn from typing import Optional from collections import defaultdict LINE_WIDTH = 108 LINE = '-' * LINE_WIDTH + '\n' class TensorDetector(): def __init__(self, show_info: bool = True, log: str = None, include_cpu: bool = False, module: Optional[nn.Module] = None ): """This class is a detector to detect tensor on different devices. Args: show_info (bool, optional): whether to print the info on screen, default True. log (str, optional): the file name to save the log. Defaults to None. include_cpu (bool, optional): whether to detect tensor on cpu, default False. module (Optional[:class:`nn.Module`]): when sending an ``nn.Module`` object, the detector can name the tensors detected better. """ self.show_info = show_info self.log = log self.include_cpu = include_cpu self.tensor_info = defaultdict(list) self.saved_tensor_info = defaultdict(list) self.order = [] self.detected = [] self.devices = [] self.info = "" self.module = module if isinstance(module, nn.Module): # if module is an instance of nn.Module, we can name the parameter with its real name for name, param in module.named_parameters(): self.tensor_info[id(param)].append(name) self.tensor_info[id(param)].append(param.device) self.tensor_info[id(param)].append(param.shape) self.tensor_info[id(param)].append(param.requires_grad) self.tensor_info[id(param)].append(param.dtype) self.tensor_info[id(param)].append(self.get_tensor_mem(param)) def get_tensor_mem(self, tensor): # calculate the memory occupied by a tensor memory_size = tensor.element_size() * tensor.storage().size() if (tensor.is_leaf or tensor.retains_grad) and tensor.grad is not None: grad_memory_size = tensor.grad.element_size() * tensor.grad.storage().size() memory_size += grad_memory_size return self.mem_format(memory_size) def mem_format(self, real_memory_size): # format the tensor memory into a reasonal magnitude if real_memory_size >= 2 ** 30: return str(real_memory_size / (2 ** 30)) + ' GB' if real_memory_size >= 2 ** 20: return str(real_memory_size / (2 ** 20)) + ' MB' if real_memory_size >= 2 ** 10: return str(real_memory_size / (2 ** 10)) + ' KB' return str(real_memory_size) + ' B' def collect_tensors_state(self): for obj in gc.get_objects(): if torch.is_tensor(obj): # skip cpu tensor when include_cpu is false and the tensor we have collected before if (not self.include_cpu) and obj.device == torch.device('cpu'): continue self.detected.append(id(obj)) # skip paramters we had added in __init__ when module is an instance of nn.Module for the first epoch if id(obj) not in self.tensor_info: name = type(obj).__name__ # after backward, we want to update the records, to show you the change if isinstance(self.module, nn.Module) and name == 'Parameter': if obj.grad is not None: # with grad attached for par_name, param in self.module.named_parameters(): if param.requires_grad and param.grad.equal(obj.grad): name = par_name + ' (with grad)' else: # with no grad attached # there will be no new paramters created during running # so it must be in saved_tensor_info continue # we can also marked common tensors as tensor(with grad) if name == 'Tensor' and (obj.is_leaf or obj.retains_grad): if obj.grad is not None: name = name + ' (with grad)' # in fact, common tensor have no grad # unless you set retain_grad() if id(obj) in self.saved_tensor_info.keys() and name == self.saved_tensor_info[id(obj)][0]: continue self.tensor_info[id(obj)].append(name) self.tensor_info[id(obj)].append(obj.device) self.tensor_info[id(obj)].append(obj.shape) self.tensor_info[id(obj)].append(obj.requires_grad) self.tensor_info[id(obj)].append(obj.dtype) self.tensor_info[id(obj)].append(self.get_tensor_mem(obj)) # recorded the order we got the tensor # by this we can guess the tensor easily # it will record every tensor updated this turn self.order.append(id(obj)) # recorded all different devices if obj.device not in self.devices: self.devices.append(obj.device) def print_tensors_state(self): template_format = '{:3s}{:<30s}{:>10s}{:>20s}{:>10s}{:>20s}{:>15s}' self.info += LINE self.info += template_format.format(' ', 'Tensor', 'device', 'shape', 'grad', 'dtype', 'Mem') self.info += '\n' self.info += LINE # if a tensor updates this turn, and was recorded before # it should be updated in the saved_tensor_info as well outdated = [x for x in self.saved_tensor_info.keys() if x in self.order] minus = [x for x in self.saved_tensor_info.keys() if x not in self.detected] minus = outdated + minus if len(self.order) > 0: for tensor_id in self.order: self.info += template_format.format('+', str(self.tensor_info[tensor_id][0]), str(self.tensor_info[tensor_id][1]), str(tuple(self.tensor_info[tensor_id][2])), str(self.tensor_info[tensor_id][3]), str(self.tensor_info[tensor_id][4]), str(self.tensor_info[tensor_id][5])) self.info += '\n' if len(self.order) > 0 and len(minus) > 0: self.info += '\n' if len(minus) > 0: for tensor_id in minus: self.info += template_format.format('-', str(self.saved_tensor_info[tensor_id][0]), str(self.saved_tensor_info[tensor_id][1]), str(tuple(self.saved_tensor_info[tensor_id][2])), str(self.saved_tensor_info[tensor_id][3]), str(self.saved_tensor_info[tensor_id][4]), str(self.saved_tensor_info[tensor_id][5])) self.info += '\n' # deleted the updated tensor self.saved_tensor_info.pop(tensor_id) # trace where is the detect() locate_info = inspect.stack()[2] locate_msg = '"' + locate_info.filename + '" line ' + str(locate_info.lineno) self.info += LINE self.info += f"Detect Location: {locate_msg}\n" for device in self.devices: if device == torch.device('cpu'): continue gpu_mem_alloc = self.mem_format(torch.cuda.memory_allocated(device)) self.info += f"Totle GPU Memery Allocated on {device} is {gpu_mem_alloc}\n" self.info += LINE self.info += '\n\n' if self.show_info: print(self.info) if self.log is not None: with open(self.log + '.log', 'a') as f: f.write(self.info) def detect(self, include_cpu = False): self.include_cpu = include_cpu self.collect_tensors_state() self.print_tensors_state() self.saved_tensor_info.update(self.tensor_info) self.tensor_info.clear() self.order = [] self.detected = [] self.info = "" def close(self): self.saved_tensor_info.clear() self.module = None
from .tensor_detector import TensorDetector
from pathlib import Path from torch.autograd.profiler import profile from .prof_utils import BaseProfiler, _format_time, _format_memory, _format_bandwidth from typing import List def _get_size(dtype: str): if dtype == "fp16": return 2 elif dtype == "fp32": return 4 else: raise NotImplementedError def _get_numel(my_list: List[int]) -> int: from functools import reduce from operator import mul return reduce(mul, my_list) def _reduce_location(locations: List[str]) -> str: ret = [] for lo in locations: ret.append(lo) ret.append("\n") ret = ret[:-1] return ''.join(ret) class PcieEvent(object): """Pcie Event. """ def __init__(self, count: int = 0, pcie_vol: int = 0, cuda_time: int = 0): self.count = count self.pcie_vol = pcie_vol self.cuda_time = cuda_time def add(self, rhs): self.count += rhs.count self.pcie_vol += rhs.pcie_vol self.cuda_time += rhs.cuda_time class PcieProfiler(BaseProfiler): """Pcie profiler. Records all data transmission between CPU and GPU. TODO: Merge pcie profiler into communication profiler """ def __init__(self, dtype: str = "fp32", depth: int = 1): super().__init__(profiler_name="Pcie", priority=10) self.depth = depth self.data_size = _get_size(dtype) self.h2d_count = 0 self.h2d_time = 0 self.d2h_count = 0 self.d2h_time = 0 self.ops_record = dict() self.profiler = None def reset(self): self.h2d_count = 0 self.h2d_time = 0 self.d2h_count = 0 self.d2h_time = 0 self.ops_record = dict() self.profiler = None def enable(self): self.profiler = profile(enabled=True, use_cuda=True, use_cpu=True, use_kineto=True, record_shapes=True, with_stack=True) self.profiler.__enter__() def disable(self): self.profiler.__exit__(None, None, None) if self.profiler.enabled: events = self.profiler.function_events for event in events: if event.name == "aten::copy_": t_shape = event.input_shapes[0] if len(t_shape) == 0 or event.cuda_time_total == 0 or len(event.stack) == 0: continue current_comm_event = PcieEvent(1, self.data_size * _get_numel(t_shape), event.cuda_time_total) code_location = _reduce_location(event.stack[:self.depth]) if code_location in self.ops_record: self.ops_record[code_location].add(current_comm_event) else: self.ops_record[code_location] = current_comm_event elif 'Memcpy HtoD' in event.name: self.h2d_count += 1 self.h2d_time += event.cuda_time_total elif 'Memcpy DtoH' in event.name: self.d2h_count += 1 self.d2h_time += event.cuda_time_total self.profiler = None def to_tensorboard(self, writer): writer.add_text(tag="Data Transmission", text_string=self.result_str("\n\n")) def to_file(self, filename: Path): with open(filename, "w") as f: f.write(self.result_str()) def show(self): print(self.result_str()) def result_str(self, sep: str = "\n"): res = [] def append(s: str = None): if s is not None: res.append(s) res.append(sep) append("Pcie profiling result:") append("time of data transmission (CPU -> GPU): {}".format(_format_time(self.h2d_time))) append("number of transmission (CPU -> GPU): {}".format(self.h2d_count)) append("time of data transmission (GPU -> CPU): {}".format(_format_time(self.d2h_time))) append("number of transmission (GPU -> CPU): {}".format(self.d2h_count)) append("Possible data transmission events in PCIE:") seperation = '-' * 62 row_format = '{:^10}' + '{:^12}' + '{:^16}' + '{:^12}' * 2 append(seperation) append(row_format.format('Location', 'GPU time', 'Trans volume', 'Bandwidth', 'Num of calls')) append(seperation) show_list = sorted(self.ops_record.items(), key=lambda kv: -kv[1].cuda_time) for location, event in show_list: append(location) append( row_format.format('', _format_time(event.cuda_time), _format_memory(event.pcie_vol), _format_bandwidth(event.pcie_vol, event.cuda_time), event.count)) append() return ''.join(res)
import inspect from pathlib import Path from functools import partial import torch from torch.autograd.profiler import profile import torch.distributed as dist from torch.distributed import ReduceOp from colossalai.utils import get_current_device from .prof_utils import BaseProfiler, _format_time, _format_memory, _format_bandwidth from typing import List, Optional def _get_code_location(depth: int): ret = [] length = min(len(inspect.stack()), depth + 1) for i in range(3, length): upper_frame = inspect.stack()[i] function_name = inspect.stack()[i - 1].function ret.append(upper_frame.filename) ret.append('(') ret.append(str(upper_frame.lineno)) ret.append('): ') ret.append(function_name) if i != length - 1: ret.append('\n') return ''.join(ret) torch_all_reduce = dist.all_reduce torch_all_gather = dist.all_gather torch_reduce_scatter = dist.reduce_scatter torch_broadcast = dist.broadcast torch_reduce = dist.reduce class CommEvent(object): """Communication Event. Used for communication time and communication volume recording. """ def __init__(self, count: int = 0, comm_vol: float = 0., cuda_time: int = 0): self.self_count = count self.self_comm_vol = comm_vol self.self_cuda_time = cuda_time def add(self, rhs): self.self_count += rhs.self_count self.self_comm_vol += rhs.self_comm_vol self.self_cuda_time += rhs.self_cuda_time class CommProfiler(BaseProfiler): """Communication profiler. Records all communication events. """ def __init__(self, depth: int = 0, total_count: int = 0, total_comm_vol: float = 0, total_cuda_time: int = 0): super().__init__(profiler_name="Collective_Communication", priority=0) self.depth = 3 + depth self.total_count = total_count self.total_comm_vol = total_comm_vol self.total_cuda_time = total_cuda_time self.ops_record = dict() self.profiler = None self.pending_op = None self.pending_metadata = None self.warn_flag = False def reset(self): self.total_count = 0 self.total_comm_vol = 0 self.total_cuda_time = 0 self.ops_record = dict() self.profiler = None self.pending_op = None self.pending_metadata = None self.warn_flag = False def enable(self): dist.all_reduce = partial(all_reduce, profiler=self) dist.all_gather = partial(all_gather, profiler=self) dist.reduce_scatter = partial(reduce_scatter, profiler=self) dist.broadcast = partial(broadcast, profiler=self) dist.reduce = partial(reduce, profiler=self) def disable(self): dist.all_reduce = torch_all_reduce dist.all_gather = torch_all_gather dist.reduce_scatter = torch_reduce_scatter dist.broadcast = torch_broadcast dist.reduce = torch_reduce def to_tensorboard(self, writer): writer.add_text(tag="Collective Communication", text_string=self.result_str("\n\n")) def to_file(self, filename: Path): with open(filename, "w") as f: f.write(self.result_str()) def show(self): print(self.result_str()) def result_str(self, sep: str = "\n"): res = [] def append(s: str = None): if s is not None: res.append(s) res.append(sep) if self.warn_flag: append("Warnning: there exists multiple communication operations in the same time. As a result, " "the profiling result is not accurate.") if self.total_cuda_time == 0: return "No collective communication has been called yet!" append("Collective communication profiling result:") append("total cuda time: {}".format(_format_time(self.total_cuda_time))) append("average bandwidth: {}".format(_format_bandwidth(self.total_comm_vol, self.total_cuda_time))) append("total number of calls: {}".format(self.total_count)) append("All events:") seperation = '-' * 74 row_format = '{:^10}' + '{:^12}' * 2 + '{:^16}' + '{:^12}' * 2 append(seperation) append(row_format.format('Location', 'GPU time', 'Percentage', 'Comm volume', 'Bandwidth', 'Num of calls')) append(seperation) show_list = sorted(self.ops_record.items(), key=lambda kv: -kv[1].self_cuda_time) for location, event in show_list: append(location) append( row_format.format('', _format_time(event.self_cuda_time), '{:.1f}%'.format(event.self_cuda_time / self.total_cuda_time * 100.0), _format_memory(event.self_comm_vol), _format_bandwidth(event.self_comm_vol, event.self_cuda_time), event.self_count)) append() return ''.join(res) @property def has_aync_op(self): return self.pending_op is not None def activate_profiler(self, kn: str, vol: float): self.pending_metadata = (kn, _get_code_location(self.depth), vol) self.profiler = profile(enabled=True, use_cuda=True, use_cpu=True, use_kineto=True) self.profiler.__enter__() def close_profiler(self, group=None): assert self.profiler is not None, "There is no running dist op" kernel_name, code_location, vol = self.pending_metadata self.profiler.__exit__(None, None, None) if self.profiler.enabled and dist.get_world_size(group) > 1: assert_flag = 0 current_comm_event = None events = self.profiler.function_events for event in events: if kernel_name in event.name: assert assert_flag == 0, "Multiple dist ops has been called " current_comm_event = CommEvent(1, vol, event.self_cuda_time_total) assert_flag += 1 assert current_comm_event is not None, "dist op has not been found" buffer = torch.tensor([current_comm_event.self_cuda_time], device=get_current_device()) torch_all_reduce(buffer, op=ReduceOp.MIN, group=group) current_comm_event.self_cuda_time = buffer.item() self.total_count += current_comm_event.self_count self.total_comm_vol += current_comm_event.self_comm_vol self.total_cuda_time += current_comm_event.self_cuda_time if code_location in self.ops_record: self.ops_record[code_location].add(current_comm_event) else: self.ops_record[code_location] = current_comm_event self.profiler = None self.pending_op = None self.pending_metadata = None def wait_async_op(self): if self.pending_op is not None: op = self.pending_op op.wait() self.close_profiler() class CommHandler(object): """Communication handler. A dummy handler to wait aync operations. """ def __init__(self, profiler: CommProfiler): super().__init__() self.prof = profiler def wait(self): self.prof.wait_async_op() def async_check(profiler: CommProfiler): if profiler.pending_op is not None: profiler.warn_flag = True profiler.wait_async_op() def all_reduce(tensor: torch.Tensor, op: ReduceOp = ReduceOp.SUM, group=None, async_op: bool = False, profiler: CommProfiler = None) -> Optional[CommHandler]: async_check(profiler) comm_size = dist.get_world_size(group) correction = 2 * (comm_size - 1) / comm_size comm_vol = correction * tensor.element_size() * tensor.numel() profiler.activate_profiler("ncclKernel_AllReduce_", comm_vol) profiler.pending_op = torch_all_reduce(tensor, op, group, async_op) if async_op: return CommHandler(profiler) profiler.close_profiler(group) def reduce_scatter(output: torch.Tensor, input_list: List[torch.Tensor], op: ReduceOp = ReduceOp.SUM, group=None, async_op: bool = False, profiler: CommProfiler = None) -> Optional[CommHandler]: async_check(profiler) comm_size = dist.get_world_size(group) correction = (comm_size - 1) / comm_size comm_vol = 0 for tensor in input_list: comm_vol += tensor.element_size() * tensor.numel() comm_vol *= correction profiler.activate_profiler("ncclKernel_ReduceScatter_", comm_vol) profiler.pending_op = torch_reduce_scatter(output, input_list, op, group, async_op) if async_op: return CommHandler(profiler) profiler.close_profiler(group) def all_gather(tensor_list: List[torch.Tensor], tensor: torch.Tensor, group=None, async_op: bool = False, profiler: CommProfiler = None) -> Optional[CommHandler]: async_check(profiler) comm_size = dist.get_world_size(group) correction = (comm_size - 1) / comm_size comm_vol = 0 for ten in tensor_list: comm_vol += ten.element_size() * ten.numel() comm_vol *= correction profiler.activate_profiler("ncclKernel_AllGather_", comm_vol) profiler.pending_op = torch_all_gather(tensor_list, tensor, group, async_op) if async_op: return CommHandler(profiler) profiler.close_profiler(group) def broadcast(tensor: torch.Tensor, src: int, group=None, async_op: bool = False, profiler: CommProfiler = None) -> Optional[CommHandler]: async_check(profiler) comm_vol = 1.0 * tensor.element_size() * tensor.numel() profiler.activate_profiler("ncclKernel_Broadcast_", comm_vol) profiler.pending_op = torch_broadcast(tensor, src, group, async_op) if async_op: return CommHandler(profiler) profiler.close_profiler(group) def reduce(tensor: torch.Tensor, dst: int, op: ReduceOp = ReduceOp.SUM, group=None, async_op: bool = False, profiler: CommProfiler = None) -> Optional[CommHandler]: async_check(profiler) comm_vol = 1.0 * tensor.element_size() * tensor.numel() profiler.activate_profiler("ncclKernel_Reduce_", comm_vol) profiler.pending_op = torch_reduce(tensor, dst, op, group, async_op) if async_op: return CommHandler(profiler) profiler.close_profiler(group)
from .comm_profiler import CommProfiler from .pcie_profiler import PcieProfiler from .prof_utils import ProfilerContext, BaseProfiler from .mem_profiler import MemProfiler __all__ = ['BaseProfiler', 'CommProfiler', 'PcieProfiler', 'MemProfiler', 'ProfilerContext']
from pathlib import Path from typing import Union from colossalai.engine import Engine from torch.utils.tensorboard import SummaryWriter from colossalai.engine.ophooks import MemTracerOpHook from colossalai.utils.profiler import BaseProfiler class MemProfiler(BaseProfiler): """Wraper of MemOpHook, used to show GPU memory usage through each iteration To use this profiler, you need to pass an `engine` instance. And the usage is same like CommProfiler. Usage:: mm_prof = MemProfiler(engine) with ProfilerContext([mm_prof]) as prof: writer = SummaryWriter("mem") engine.train() ... prof.to_file("./log") prof.to_tensorboard(writer) """ def __init__(self, engine: Engine, warmup: int = 50, refreshrate: int = 10) -> None: super().__init__(profiler_name="MemoryProfiler", priority=0) self._mem_tracer = MemTracerOpHook(warmup=warmup, refreshrate=refreshrate) self._engine = engine def enable(self) -> None: self._engine.add_hook(self._mem_tracer) def disable(self) -> None: self._engine.remove_hook(self._mem_tracer) def to_tensorboard(self, writer: SummaryWriter) -> None: stats = self._mem_tracer.async_mem_monitor.state_dict['mem_stats'] for info, i in enumerate(stats): writer.add_scalar("memory_usage/GPU", info, i) def to_file(self, data_file: Path) -> None: self._mem_tracer.save_results(data_file) def show(self) -> None: stats = self._mem_tracer.async_mem_monitor.state_dict['mem_stats'] print(stats)
from abc import ABC, abstractmethod from pathlib import Path from typing import Union, List from colossalai.core import global_context as gpc # copied from high version pytorch to support low version def _format_time(time_us): """Defines how to format time in FunctionEvent""" US_IN_SECOND = 1000.0 * 1000.0 US_IN_MS = 1000.0 if time_us >= US_IN_SECOND: return '{:.3f}s'.format(time_us / US_IN_SECOND) if time_us >= US_IN_MS: return '{:.3f}ms'.format(time_us / US_IN_MS) return '{:.3f}us'.format(time_us) # copied from high version pytorch to support low version def _format_memory(nbytes): """Returns a formatted memory size string""" KB = 1024 MB = 1024 * KB GB = 1024 * MB if (abs(nbytes) >= GB): return '{:.2f} GB'.format(nbytes * 1.0 / GB) elif (abs(nbytes) >= MB): return '{:.2f} MB'.format(nbytes * 1.0 / MB) elif (abs(nbytes) >= KB): return '{:.2f} KB'.format(nbytes * 1.0 / KB) else: return str(nbytes) + ' B' def _format_bandwidth(volme: float or int, time_us: int): sec_div_mb = (1000.0 / 1024.0)**2 mb_per_sec = volme / time_us * sec_div_mb if mb_per_sec >= 1024.0: return '{:.3f} GB/s'.format(mb_per_sec / 1024.0) else: return '{:.3f} MB/s'.format(mb_per_sec) class BaseProfiler(ABC): def __init__(self, profiler_name: str, priority: int): self.name = profiler_name self.priority = priority @abstractmethod def enable(self): pass @abstractmethod def disable(self): pass @abstractmethod def to_tensorboard(self, writer): pass @abstractmethod def to_file(self, filename: Path): pass @abstractmethod def show(self): pass class ProfilerContext(object): """Profiler context manager Usage:: world_size = 4 inputs = torch.randn(10, 10, dtype=torch.float32, device=get_current_device()) outputs = torch.empty(world_size, 10, 10, dtype=torch.float32, device=get_current_device()) outputs_list = list(torch.chunk(outputs, chunks=world_size, dim=0)) cc_prof = CommProfiler() with ProfilerContext([cc_prof]) as prof: op = dist.all_reduce(inputs, async_op=True) dist.all_gather(outputs_list, inputs) op.wait() dist.reduce_scatter(inputs, outputs_list) dist.broadcast(inputs, 0) dist.reduce(inputs, 0) prof.show() """ def __init__(self, profilers: List[BaseProfiler] = None, enable: bool = True): self.enable = enable self.profilers = sorted(profilers, key=lambda prof: prof.priority) def __enter__(self): if self.enable: for prof in self.profilers: prof.enable() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.enable: for prof in self.profilers: prof.disable() def to_tensorboard(self, writer): from torch.utils.tensorboard import SummaryWriter assert isinstance(writer, SummaryWriter), \ f'torch.utils.tensorboard.SummaryWriter is required, but found {type(writer)}.' for prof in self.profilers: prof.to_tensorboard(writer) def to_file(self, log_dir: Union[str, Path]): if isinstance(log_dir, str): log_dir = Path(log_dir) if not log_dir.exists(): log_dir.mkdir(parents=True, exist_ok=True) for prof in self.profilers: log_file = log_dir.joinpath(f'{prof.name}_rank_{gpc.get_global_rank()}.log') prof.to_file(log_file) def show(self): for prof in self.profilers: prof.show()
from .comparison import assert_equal, assert_not_equal, assert_close, assert_close_loose, assert_equal_in_group from .utils import parameterize, rerun_on_exception, rerun_if_address_is_in_use __all__ = [ 'assert_equal', 'assert_not_equal', 'assert_close', 'assert_close_loose', 'assert_equal_in_group', 'parameterize', 'rerun_on_exception', 'rerun_if_address_is_in_use' ]
import torch import torch.distributed as dist from torch import Tensor from torch.distributed import ProcessGroup def assert_equal(a: Tensor, b: Tensor): assert torch.all(a == b), f'expected a and b to be equal but they are not, {a} vs {b}' def assert_not_equal(a: Tensor, b: Tensor): assert not torch.all(a == b), f'expected a and b to be not equal but they are, {a} vs {b}' def assert_close(a: Tensor, b: Tensor, rtol: float = 1e-5, atol: float = 1e-8): assert torch.allclose(a, b, rtol=rtol, atol=atol), f'expected a and b to be close but they are not, {a} vs {b}' def assert_close_loose(a: Tensor, b: Tensor, rtol: float = 1e-3, atol: float = 1e-3): assert_close(a, b, rtol, atol) def assert_equal_in_group(tensor: Tensor, process_group: ProcessGroup = None): # all gather tensors from different ranks world_size = dist.get_world_size(process_group) tensor_list = [torch.empty_like(tensor) for _ in range(world_size)] dist.all_gather(tensor_list, tensor, group=process_group) # check if they are equal one by one for i in range(world_size - 1): a = tensor_list[i] b = tensor_list[i+1] assert torch.all(a == b), f'expected tensors on rank {i} and {i+1} to be equal but they are not, {a} vs {b}'
import re import torch from typing import Callable, List, Any from functools import partial from inspect import signature from packaging import version def parameterize(argument: str, values: List[Any]) -> Callable: """ This function is to simulate the same behavior as pytest.mark.parameterize. As we want to avoid the number of distributed network initialization, we need to have this extra decorator on the function launched by torch.multiprocessing. If a function is wrapped with this wrapper, non-paramterized arguments must be keyword arguments, positioanl arguments are not allowed. Usgae:: # Example 1: @parameterize('person', ['xavier', 'davis']) def say_something(person, msg): print(f'{person}: {msg}') say_something(msg='hello') # This will generate output: # > xavier: hello # > davis: hello # Exampel 2: @parameterize('person', ['xavier', 'davis']) @parameterize('msg', ['hello', 'bye', 'stop']) def say_something(person, msg): print(f'{person}: {msg}') say_something() # This will generate output: # > xavier: hello # > xavier: bye # > xavier: stop # > davis: hello # > davis: bye # > davis: stop Args: argument (str): the name of the argument to parameterize values (List[Any]): a list of values to iterate for this argument """ def _wrapper(func): def _execute_function_by_param(**kwargs): for val in values: arg_map = {argument: val} partial_func = partial(func, **arg_map) partial_func(**kwargs) return _execute_function_by_param return _wrapper def rerun_on_exception(exception_type: Exception = Exception, pattern: str = None, max_try: int = 5) -> Callable: """ A decorator on a function to re-run when an exception occurs. Usage:: # rerun for all kinds of exception @rerun_on_exception() def test_method(): print('hey') raise RuntimeError('Address already in use') # rerun for RuntimeError only @rerun_on_exception(exception_type=RuntimeError) def test_method(): print('hey') raise RuntimeError('Address already in use') # rerun for maximum 10 times if Runtime error occurs @rerun_on_exception(exception_type=RuntimeError, max_try=10) def test_method(): print('hey') raise RuntimeError('Address already in use') # rerun for infinite times if Runtime error occurs @rerun_on_exception(exception_type=RuntimeError, max_try=None) def test_method(): print('hey') raise RuntimeError('Address already in use') # rerun only the exception message is matched with pattern # for infinite times if Runtime error occurs @rerun_on_exception(exception_type=RuntimeError, pattern="^Address.*$") def test_method(): print('hey') raise RuntimeError('Address already in use') Args: exception_type (Exception, Optional): The type of exception to detect for rerun pattern (str, Optional): The pattern to match the exception message. If the pattern is not None and matches the exception message, the exception will be detected for rerun max_try (int, Optional): Maximum reruns for this function. The default value is 5. If max_try is None, it will rerun foreven if exception keeps occurings """ def _match_lines(lines, pattern): for line in lines: if re.match(pattern, line): return True return False def _wrapper(func): def _run_until_success(*args, **kwargs): try_count = 0 assert max_try is None or isinstance(max_try, int), \ f'Expected max_try to be None or int, but got {type(max_try)}' while max_try is None or try_count < max_try: try: try_count += 1 ret = func(*args, **kwargs) return ret except exception_type as e: error_lines = str(e).split('\n') if try_count < max_try and (pattern is None or _match_lines(error_lines, pattern)): print('Exception is caught, retrying...') # when pattern is not specified, we always skip the exception # when pattern is specified, we only skip when pattern is matched continue else: print('Maximum number of attempts is reached or pattern is not matched, no more retrying...') raise e # Override signature # otherwise pytest.mark.parameterize will raise the following error: # function does not use argumetn xxx sig = signature(func) _run_until_success.__signature__ = sig return _run_until_success return _wrapper def rerun_if_address_is_in_use(): """ This function reruns a wrapped function if "address already in use" occurs in testing spawned with torch.multiprocessing Usage:: @rerun_if_address_is_in_use() def test_something(): ... """ # check version torch_version = version.parse(torch.__version__) assert torch_version.major == 1 # only torch >= 1.8 has ProcessRaisedException if torch_version.minor >= 8: exception = torch.multiprocessing.ProcessRaisedException else: exception = Exception func_wrapper = rerun_on_exception(exception_type=exception, pattern=".*Address already in use.*") return func_wrapper
from typing import Tuple import torch import torch.nn as nn from colossalai.logging import get_dist_logger from colossalai.zero.sharded_model.sharded_model_v2 import ShardedModelV2 from colossalai.zero.sharded_optim.sharded_optim_v2 import ShardedOptimizerV2 def convert_to_zero_v2(model: nn.Module, optimizer: torch.optim.Optimizer, model_config, optimizer_config) -> Tuple[ShardedModelV2, ShardedOptimizerV2]: """ A helper function to integrate the model and optimizer with ZeRO optimizer and off-loading :param model: Your model object :type model: :class:`torch.nn.Module` :param optimizer_config: Your optimizer object :type optimizer_config: :class:`dict` :return: (model, optimizer) :rtype: Tuple """ logger = get_dist_logger('convert_to_zero_v2') logger.info(f'optimizer_config is {optimizer_config}') if optimizer_config is None: optimizer_config = dict() logger.info(f'model_config is {model_config}') if model_config is None: model_config = dict() zero_model = ShardedModelV2(model, **model_config) zero_optimizer = ShardedOptimizerV2(zero_model, optimizer, **optimizer_config) return zero_model, zero_optimizer __all__ = ['convert_to_zerov2', 'ShardedModelV2', 'ShardedOptimizerV2']
from .init_context import ZeroInitContext, no_shard_zero_context, no_shard_zero_decrator __all__ = ['ZeroInitContext', 'no_shard_zero_context', 'no_shard_zero_decrator']
import contextlib import functools from typing import Optional import torch import torch.nn as nn import torch.distributed as dist from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.context.singleton_meta import SingletonMeta from colossalai.logging import get_dist_logger from colossalai.zero.shard_utils import BaseShardStrategy from colossalai.zero.sharded_model._utils import cast_tensor_to_fp16 from colossalai.zero.sharded_param import ShardedParamV2 from contextlib import AbstractContextManager def _substitute_init_recursively(cls, func): for subcls in cls.__subclasses__(): _substitute_init_recursively(subcls, func) func(subcls) 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. _substitute_init_recursively(torch.nn.modules.module.Module, _enable_class) # 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 _substitute_init_recursively(torch.nn.modules.module.Module, _disable_class) # 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 class ZeroContextConfig(object): """The configuration used to control zero context initialization. Args: target_device (torch.device): The device where param data are after exiting the context. replicated (bool, optional): Whether the param is replicated across data parallel group. Some parameters are not replicated, e.g. parameters in MOE experts. shard_param (bool, optional): Is param sharded after exiting the context. Defaults to False. """ def __init__(self, target_device: torch.device, replicated: bool = True, shard_param: bool = False): super().__init__() if shard_param: assert replicated, "Non-replicated parameters can't be sharded." # replicated no-shard parameters should locate in cuda, since we will broadcast them soon if replicated and not shard_param: assert target_device.type == 'cuda', "Replicated no-shard paramters should locate in cuda." self.target_device = target_device self.is_replicated: bool = replicated self.shard_param: bool = shard_param class ZeroInitContext(InsertPostInitMethodToModuleSubClasses): """A context to initialize model. 1. Convert the model to fp16. 2. The paramaters of the module are adapted to type ShardedParameter. 3. Shard the param and grad according to flags. Args: target_device (torch.device): The device where param data are after exiting the context. shard_strategy (BaseShardStrategy): Shard strategy instance. seed (int, optional): Random seed for weight initialization shard_param (bool, optional): Is param sharded after exiting the context. 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). """ def __init__(self, target_device: torch.device, shard_strategy: BaseShardStrategy, seed: int = 2**10 - 1, shard_param: bool = False, model_numel_tensor: torch.Tensor = torch.zeros(1, dtype=torch.long)): super().__init__() self.shard_strategy = shard_strategy self.param_list = [] self.model_numel_tensor = model_numel_tensor self.seed = seed self.dp_process_group = gpc.get_group(ParallelMode.DATA) self.config = ZeroContextConfig(target_device=target_device, replicated=True, shard_param=shard_param) ZeroContextMgr().current_context = self @property def target_device(self): return self.config.target_device @property def is_replicated(self): return self.config.is_replicated @property def shard_param(self): return self.config.shard_param @staticmethod def calc_fanin_fanout(tensor: torch.Tensor): """We use this function to substitute fan-in and fan-out calculation in torch.nn.init. This can help us get correct fan-in and fan-out for sharded tensor. """ assert isinstance(tensor, nn.Parameter), "Sharded tensor initilization is only allowed for paramters" # get correct shape of input tensor if not hasattr(tensor, 'colo_attr') or not tensor.colo_attr.param_is_sharded: tensor_shape = tensor.shape else: tensor_shape = tensor.colo_attr.sharded_data_tensor.origin_shape dimensions = len(tensor_shape) if dimensions < 2: raise ValueError("Fan in and fan out can not be computed for tensor with fewer than 2 dimensions") num_input_fmaps = tensor_shape[1] num_output_fmaps = tensor_shape[0] receptive_field_size = 1 if dimensions > 2: # math.prod is not always available, accumulate the product manually # we could use functools.reduce but that is not supported by TorchScript for s in tensor_shape[2:]: receptive_field_size *= s fan_in = num_input_fmaps * receptive_field_size fan_out = num_output_fmaps * receptive_field_size return fan_in, fan_out def _pre_context_exec(self): """ The Callback function when entering the context """ self.logger = get_dist_logger("ZeroInitContext") # substitute fan-in and fan-out calculation self.nn_fanin_fanout = nn.init._calculate_fan_in_and_fan_out nn.init._calculate_fan_in_and_fan_out = self.calc_fanin_fanout # reserve rng states self.cpu_rng_state = torch.get_rng_state() self.cuda_rng_state = torch.cuda.get_rng_state() # set new seed for initialization, since we initialize sharded tensor separately # we don't want all processes have the same seed # otherwise all sharded tensors are same after init offset = self.seed + 1 # we want to have more 1 in binary format seed torch.manual_seed(self.seed + offset * dist.get_rank()) def _post_context_exec(self): """The callback function when exiting context. """ # broadcast replicated no-shard parameters src_rank = gpc.get_ranks_in_group(ParallelMode.DATA)[0] for param in self.param_list: assert hasattr(param, 'colo_attr') if not param.colo_attr.param_is_sharded and param.colo_attr.is_replicated: dist.broadcast(tensor=param.data, src=src_rank, group=self.dp_process_group) param.colo_attr.set_data_none() del self.param_list nn.init._calculate_fan_in_and_fan_out = self.nn_fanin_fanout torch.set_rng_state(self.cpu_rng_state) torch.cuda.set_rng_state(self.cuda_rng_state) 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. """ def half_fn(t: torch.Tensor): return t.half() if t.is_floating_point() else t for param in module.parameters(recurse=False): # avoid adapting a param to ShardedParam twice if hasattr(param, 'colo_attr'): continue self.model_numel_tensor += param.numel() # convert parameters to half param_half = half_fn(param) param.data = param_half if param.grad is not None: grad_half = half_fn(param.grad) param.grad.data = grad_half # move torch parameters to the target device target_device = self.target_device param.data = param.data.to(target_device) if param.grad is not None: param.grad = param.grad.to(target_device) param.colo_attr = ShardedParamV2(param, set_data_none=False) if self.shard_param: self.shard_strategy.shard([param.colo_attr.sharded_data_tensor], self.dp_process_group) param.data = param.colo_attr.data_payload # set param.data to payload # mark whether the param is replicated param.colo_attr.is_replicated = self.is_replicated # mark whether the param should keep not sharded # if True, the param is used as Zero stage 2 param.colo_attr.keep_not_shard = not self.shard_param self.param_list.append(param) # We must cast buffers # If we use BN, buffers may be on CPU and Float # We must cast them for buffer in module.buffers(recurse=False): buffer.data = buffer.data.to(device=torch.cuda.current_device()) buffer.data = cast_tensor_to_fp16(buffer.data) 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 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, shard_param=False) def no_shard_zero_decrator(is_replicated: bool = True): def _wrapper(init_func): def _no_shard(*args, **kwargs): with no_shard_zero_context(is_replicated): init_func(*args, **kwargs) return _no_shard return _wrapper
from .sharded_optim_v2 import ShardedOptimizerV2 __all__ = ['ShardedOptimizerV2']
from enum import Enum from os import stat from typing import Dict, Optional, Tuple import torch import torch.distributed as dist import torch.nn as nn from colossalai.amp.naive_amp.grad_scaler import DynamicGradScaler from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.logging import get_dist_logger from colossalai.nn.optimizer import ColossalaiOptimizer from colossalai.utils.memory_tracer.model_data_memtracer import \ GLOBAL_MODEL_DATA_TRACER from colossalai.zero.sharded_param.tensor_utils import (colo_model_data_tensor_move_inline, colo_model_tensor_clone, colo_tensor_mem_usage) from colossalai.zero.sharded_model import ShardedModelV2 from colossalai.zero.sharded_model._utils import cast_tensor_to_fp32 from colossalai.zero.sharded_param.tensorful_state import (StatefulTensor, TensorState) from torch import Tensor from torch.distributed import ProcessGroup from torch.nn.parameter import Parameter from torch.optim import Optimizer from colossalai.gemini.tensor_placement_policy import AutoTensorPlacementPolicy class OptimState(Enum): SCALED = 1 UNSCALED = 2 class ShardedOptimizerV2(ColossalaiOptimizer): """A wrapper for optimizer. ``ShardedOptimizerV2`` and ``ShardedModelV2`` implement Zero Redundancy Optimizer (ZeRO). By default the ZeRO optimizer stage 3 offload Optimizer States on CPU. We apply the Device-aware Operator Placement technique for OS placement from the following paper. `PatrickStar: Parallel Training of Pre-trained Models via Chunk-based Memory Management`_ GPU margin space is the remaining space after removing peak non-model data from the overall GPU memory, which is detected by a runtime memory tracer. We place as many OS chunks in the margin space as possible. The size of margin space can be controlled by ``gpu_margin_mem_ratio``. If it is set as ``0.0``, it is the same as classical ZeRO optimizer. Note: You must use ``ShardedOptimizerV2`` with ``ShardedModelV2``. Note: Make sure you set ``tensor_placement_policy`` in ``ShardedModelV2`` to `"auto"`, if you set ``gpu_margin_mem_ratio > 0``. Args: sharded_model (ShardedModelV2): A sharded model initialized by class ShardedModelV2. The optimizer will use the shard strategy provided by sharded model to shard param fp32 tensors. optimizer (Optimizer): An Optimizer instance. gpu_margin_mem_ratio (float, optional): The ratio of GPU remaining memory (after the first forward-backward) which will be used when using hybrid CPU optimizer. This argument is meaningless when `tensor_placement_policy` of `ShardedModelV2` is not "auto". Defaults to 0.0. initial_scale (float, optional): Initial scale used by DynamicGradScaler. Defaults to 2**32. min_scale (float, optional): Min scale used by DynamicGradScaler. Defaults to 1. growth_factor (float, optional): growth_factor used by DynamicGradScaler. Defaults to 2. backoff_factor (float, optional): backoff_factor used by DynamicGradScaler. Defaults to 0.5. growth_interval (float, optional): growth_interval used by DynamicGradScaler. Defaults to 1000. hysteresis (float, optional): hysteresis used by DynamicGradScaler. Defaults to 2. max_scale (int, optional): max_scale used by DynamicGradScaler. Defaults to 2**32. dp_process_group (Optional[ProcessGroup], optional): data paralle process group. Defaults to None. mp_process_group (Optional[ProcessGroup], optional): model paralle process group. Defaults to None. .. _PatrickStar\: Parallel Training of Pre-trained Models via Chunk-based Memory Management: https://arxiv.org/abs/2108.05818 """ def __init__(self, sharded_model: ShardedModelV2, optimizer: Optimizer, gpu_margin_mem_ratio: float = 0.0, initial_scale: float = 2**32, min_scale: float = 1, growth_factor: float = 2, backoff_factor: float = 0.5, growth_interval: int = 1000, hysteresis: int = 2, max_scale: float = 2**32, dp_process_group: Optional[ProcessGroup] = None, mp_process_group: Optional[ProcessGroup] = None, verbose: bool = False) -> None: assert isinstance(sharded_model, ShardedModelV2), 'model must be wrapped with ShardedModel' super().__init__(optimizer) self.shard_strategy = sharded_model.shard_strategy self.model: ShardedModelV2 = sharded_model self.gpu_margin_mem_ratio: float = float(gpu_margin_mem_ratio) assert 0.0 <= self.gpu_margin_mem_ratio <= 1.0, f'gpu_margin_mem_ratio must >=0.0 and <=1.0' # Only move fp32 shards from CPU to GPU when user allows and inner optimizer is valid # Inner optimizer must support optimizing hybrid (CPU and CUDA) tensors, # and it must set `num_fp32_shards_per_param` correctly self._should_move_fp32_shards_h2d: bool = sharded_model.cpu_offload and self.gpu_margin_mem_ratio > 0.0 and getattr( optimizer, 'num_fp32_shards_per_param', 0) >= 2 self.device = sharded_model._tensor_placement_policy.device or torch.device('cpu') self.optim_state: OptimState = OptimState.UNSCALED self.dp_process_group = dp_process_group or gpc.get_group(ParallelMode.DATA) self.mp_process_group = mp_process_group or gpc.get_group(ParallelMode.MODEL) # Grad scaler self.grad_scaler = DynamicGradScaler(initial_scale=initial_scale, min_scale=min_scale, growth_factor=growth_factor, backoff_factor=backoff_factor, growth_interval=growth_interval, hysteresis=hysteresis, max_scale=max_scale) self._found_overflow: Tensor = torch.IntTensor([0]).to(torch.cuda.current_device()) self._logger = get_dist_logger("ShardedOptimizerV2") self._verbose = verbose # Store fp32 param shards self._register_master_weight() if self.gpu_margin_mem_ratio != 0.0 and not isinstance(sharded_model._tensor_placement_policy, AutoTensorPlacementPolicy): self._logger.warning(f'gpu_margin_mem_ratio is meaningless when tensor_placement_policy is not "auto"') if self._verbose: self._logger.debug( f"After init ShardedOptimizerV2 consumes {self.get_memory_usage()[0] / 1e6} MB CUDA Memory!", ranks=[0]) self._use_memory_tracer = self.model.use_memory_tracer if self._use_memory_tracer: GLOBAL_MODEL_DATA_TRACER.register_optimizer(self) @property def loss_scale(self): return self.grad_scaler.scale.item() def get_memory_usage(self) -> Tuple[int, int]: """ Get the memory usage of the optimizer. Including master_params (param fp32), momentum (``self.state[p]['exp_avg']``) variance (``self.state[p]['exp_avg_sq']``) Returns: Tuple[int, int]: cuda/cpu memory usage in Byte. """ cuda_use = 0 cpu_use = 0 def update_mem_use(t): nonlocal cuda_use nonlocal cpu_use t_cuda_use, t_cpu_use = colo_tensor_mem_usage(t) cuda_use += t_cuda_use cpu_use += t_cpu_use for _, p_fp32 in self.master_params.items(): update_mem_use(p_fp32) for group in self.optim.param_groups: for p in group['params']: state = self.optim.state[p] for k, v in state.items(): update_mem_use(v) return cuda_use, cpu_use def zero_grad(self, *args, **kwargs): self._zero_grad() def backward(self, loss: Tensor) -> None: loss = self.loss_scale * loss self.optim_state = OptimState.SCALED self.model.backward(loss) def backward_by_grad(self, tensor: Tensor, grad: Tensor) -> None: self.model.backward_by_grad(tensor, grad) def clip_grad_norm(self, model: nn.Module, max_norm: float): if self.optim_state == OptimState.SCALED: self._unscale_grads() return super().clip_grad_norm(model, max_norm) def step(self, *args, **kwargs): self._prepare_grads() self._maybe_move_fp32_shards() # unscale grads if scaled if self.optim_state == OptimState.SCALED: self._unscale_grads() found_inf = self._check_overflow() self.grad_scaler.update(found_inf) if found_inf: self._logger.warning('found inf during ShardedOptimV2 step') self._zero_grad(recover_data=True) return self._point_param_fp16_to_master_param() if self._verbose: gpu_mem, cpu_mem = self.get_memory_usage() self._logger.debug( f"Before step ShardedOptimizerV2 consumes {gpu_mem / 1e6} MB CUDA Memory, {cpu_mem / 1e6} MB CUDA Memory!", ranks=[0]) ret = self.optim.step(*args, **kwargs) if self._verbose: gpu_mem, cpu_mem = self.get_memory_usage() self._logger.debug( f"After step ShardedOptimizerV2 consumes {gpu_mem / 1e6} MB CUDA Memory, {cpu_mem / 1e6} MB CUDA Memory!", ranks=[0]) self._copy_master_model_to_model_fp16() return ret def _check_overflow(self): # clear previous overflow record self._found_overflow.fill_(self.model.overflow_counter) # all-reduce across dp group dist.all_reduce(self._found_overflow, group=self.dp_process_group) # all-reduce over model parallel group dist.all_reduce(self._found_overflow, group=self.mp_process_group) return self._found_overflow.item() > 0 def _unscale_grads(self): assert self.optim_state == OptimState.SCALED for group in self.optim.param_groups: for p in group['params']: if p.grad is not None: p.grad.data.div_(self.loss_scale) self.optim_state = OptimState.UNSCALED def _zero_grad(self, recover_data: bool = False): """zero grad and maybe recover fp16 params When `reuse_fp16_shard` is enabled, p.colo_attr.sharded_data_tensor stores grad here. We have to recover them from fp32 params. Args: recover_data (bool, optional): Whether to recover fp16 param from fp32 param. Defaults to False. """ # We must set grad to None # Because grad here is sharded # But next backward pass will create a full grad first # Which leads to wrong accumulation self.optim.zero_grad(set_to_none=True) for group in self.optim.param_groups: for p in group['params']: # p.colo_attr.sharded_data_tensor stores grad now # we have to recover fp16 param reuse_fp16_shard = p.colo_attr.saved_grad.data_ptr() == p.colo_attr.sharded_data_tensor.data_ptr() if recover_data and reuse_fp16_shard: self._copy_master_param_to_param_fp16(p) else: # release saved gradient p.colo_attr.saved_grad.set_null() self.model.overflow_counter = 0 # set overflow counter to zero def sync_grad(self): pass def _register_master_weight(self): self.master_params: Dict[Parameter, StatefulTensor] = {} for group in self.optim.param_groups: for p in group['params']: assert hasattr(p, 'colo_attr'), 'The parameter must be wrapped with ShardedParam' shard_flag = not p.colo_attr.sharded_data_tensor.is_sharded and p.colo_attr.is_replicated if shard_flag: # we always shard replicated paramters self.shard_strategy.shard([p.colo_attr.sharded_data_tensor], self.dp_process_group) self.master_params[p] = StatefulTensor(cast_tensor_to_fp32(p.colo_attr.data_payload.to(self.device))) if shard_flag: # In this branch, there's no need to shard param # So we gather here self.shard_strategy.gather([p.colo_attr.sharded_data_tensor], self.dp_process_group) def _maybe_move_fp32_shards(self): if self._should_move_fp32_shards_h2d: self._should_move_fp32_shards_h2d = False available_cuda_margin_mem = self.model.cuda_margin_space * self.gpu_margin_mem_ratio fp32_shards_available_cuda_margin_mem = available_cuda_margin_mem / self.optim.num_fp32_shards_per_param fp32_shards_used_cuda_margin_mem = 0 for group in self.optim.param_groups: for p in group['params']: shard_mem = self.master_params[p].payload.numel() * self.master_params[p].payload.element_size() if fp32_shards_used_cuda_margin_mem + shard_mem < fp32_shards_available_cuda_margin_mem: colo_model_data_tensor_move_inline(self.master_params[p], torch.cuda.current_device()) p.grad.data = p.grad.data.to(torch.cuda.current_device()) p.colo_attr.offload_grad = False fp32_shards_used_cuda_margin_mem += shard_mem def _prepare_grads(self): for group in self.optim.param_groups: for p in group['params']: if p.colo_attr.saved_grad.is_null(): continue p.colo_attr.saved_grad.trans_state(TensorState.COMPUTE) # If reuse_fp16_shard, grad fp16 which wasn't be offloaded may be evicted to CPU if not p.colo_attr.offload_grad: colo_model_data_tensor_move_inline(p.colo_attr.grad_payload, torch.cuda.current_device()) # FIXME(ver217): p.data here is an empty tensor on CUDA and has no useful infomation # If we change p.grad directly # it may raise error because of different shape/dtype/device of p.data and p.grad # We just set p.data = p.colo_attr.saved_grad.payload here p.data = p.colo_attr.grad_payload p.grad = p.colo_attr.grad_payload # Set p.data to empty tensor, in case of memory leaking p.colo_attr.set_data_none() def _point_param_fp16_to_master_param(self): # assign master param pointers to p.data. # We will not trigger data copy here. for group in self.optim.param_groups: for p in group['params']: self.master_params[p].trans_state(TensorState.COMPUTE) p.data = self.master_params[p].payload # Now p.data is sharded # So optimizer states are sharded naturally def _copy_master_model_to_model_fp16(self): # Copy master param data (fp32) to payload of colo_attr (fp16) # TODO() improve efficiency by gathering tensors into a chunk and transfering # a chunk. for group in self.optim.param_groups: for p in group['params']: self._copy_master_param_to_param_fp16(p) def _copy_master_param_to_param_fp16(self, p): # flush gradient p.colo_attr.saved_grad.set_null() # TODO() optimize this line CPU (fp32) -> GPU (fp16) p.data = self.master_params[p].payload p.colo_attr.reset_data_payload( colo_model_tensor_clone(p.half().detach(), p.colo_attr.sharded_data_tensor.device)) p.colo_attr.set_data_none() if p.colo_attr.keep_not_shard and p.colo_attr.is_replicated: # We gather full fp16 param here p.colo_attr.sharded_data_tensor.is_sharded = True # since only gradient is sharded, we should set to True self.shard_strategy.gather([p.colo_attr.sharded_data_tensor], self.dp_process_group) self.master_params[p].trans_state(TensorState.HOLD)
import math import torch from torch._six import inf from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from colossalai.core import global_context as gpc from colossalai.context import ParallelMode from colossalai.utils import is_model_parallel_parameter import torch.distributed as dist def flatten(input_): return _flatten_dense_tensors(input_) def unflatten(flat, tensors): return _unflatten_dense_tensors(flat, tensors) def count_numel(tensor_list): res = 0 for tensor in tensor_list: res += tensor.numel() return res def calculate_padding(numel, unit_size): remainder = numel % unit_size return unit_size - remainder if remainder else remainder def shuffle_by_round_robin(tensor_list, num_partitions): partitions = dict() for tensor_idx, tensor in enumerate(tensor_list): partition_to_go = tensor_idx % num_partitions if partition_to_go not in partitions: partitions[partition_to_go] = [] partitions[partition_to_go].append(dict(tensor=tensor, index=tensor_idx)) partitions_count = len(partitions) new_tensor_list = [] tensor_index_mapping = dict() for partition_id in range(partitions_count): partition_tensors = partitions[partition_id] for item in partition_tensors: tensor_index_mapping[item['index']] = len(new_tensor_list) new_tensor_list.append(item['tensor']) return new_tensor_list, tensor_index_mapping # create a flat tensor aligned at the alignment boundary def flatten_dense_tensors_with_padding(tensor_list, unit_size): num_elements = count_numel(tensor_list) padding = calculate_padding(num_elements, unit_size=unit_size) if padding > 0: pad_tensor = torch.zeros(padding, device=tensor_list[0].device, dtype=tensor_list[0].dtype) padded_tensor_list = tensor_list + [pad_tensor] else: padded_tensor_list = tensor_list return flatten(padded_tensor_list) def is_nccl_aligned(tensor): return tensor.data_ptr() % 4 == 0 def get_grad_accumulate_object(tensor): """ Return the AccumulateGrad of the input tensor """ # grad_fn reference: # https://discuss.pytorch.org/t/in-the-grad-fn-i-find-a-next-functions-but-i-dont-understand-the-meaning-of-the-attribute/24463 # expand_as reference: https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html#torch.Tensor.expand # # `next_functions` will return the backward graph where # the first element is the AccumulateGrad of the leaf nodes. # we want to get the AccumulateGrad of the input tensor instead of the leaf # node in the whole computation graph. # Therefore, we call expand_as to create a dummy graph # where tensor_tmp and tensor indeed point to the same object. # You can check this by print(tensor.data_ptr() == tensor_tmp.data_ptr()) tensor_tmp = tensor.expand_as(tensor) grad_acc_obj = tensor_tmp.grad_fn.next_functions[0][0] return grad_acc_obj def split_half_float_double(tensor_list): dtypes = ["torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor", "torch.cuda.BFloat16Tensor"] buckets = [] for i, dtype in enumerate(dtypes): bucket = [t for t in tensor_list if t.type() == dtype] if bucket: buckets.append(bucket) return buckets def reduce_tensor(tensor, dtype, dst_rank=None, parallel_mode=ParallelMode.DATA): """ Reduce the tensor in the data parallel process group :param tensor: A tensor object to reduce/all-reduce :param dtype: The data type used in communication :param dst_rank: The source rank for reduce. If dst_rank is None, all-reduce will be used instead of reduce. Default is None. :type tensor: torch.Tensor :type dtype: torch.dtype :type dst_rank: int, optional """ # cast the data to specified dtype for reduce/all-reduce if tensor.dtype != dtype: tensor_to_reduce = tensor.to(dtype) else: tensor_to_reduce = tensor world_size = gpc.get_world_size(parallel_mode) group = gpc.get_group(parallel_mode) tensor_to_reduce.div_(world_size) # if rank is None, all reduce will be used # else, reduce is used use_all_reduce = dst_rank is None if use_all_reduce: dist.all_reduce(tensor_to_reduce, group=group) else: ranks_in_group = gpc.get_ranks_in_group(parallel_mode) global_rank = ranks_in_group[dst_rank] dist.reduce(tensor=tensor_to_reduce, dst=global_rank, group=group) # recover the original dtype if tensor.dtype != dtype and tensor is not tensor_to_reduce: local_rank = gpc.get_local_rank(parallel_mode) if use_all_reduce or dst_rank == local_rank: tensor.copy_(tensor_to_reduce) return tensor def has_inf_or_nan(tensor): try: # if tensor is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as tensor # (which is true for some recent version of pytorch). tensor_sum = float(tensor.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # tensor_sum = float(tensor.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if tensor_sum == float('inf') or tensor_sum == -float('inf') or tensor_sum != tensor_sum: return True return False def release_param_grad(tensor_list): for tensor in tensor_list: tensor.grad = None def calculate_global_norm_from_list(norm_list): """ Compute total from a list of norms """ total_norm = 0.0 for norm in norm_list: total_norm += norm**2.0 return math.sqrt(total_norm) def compute_norm(gradients, params, dp_group, mp_group, norm_type=2): """Clips gradient norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Arguments: parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a single Tensor that will have gradients normalized max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the parameters (viewed as a single vector). """ if mp_group is None: mp_rank = 0 else: mp_rank = dist.get_rank(mp_group) norm_type = float(norm_type) if norm_type == inf: total_norm = max(g.data.abs().max() for g in gradients) total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]) dist.all_reduce(total_norm_cuda, op=torch.distributed.ReduceOp.MAX, group=dp_group) # Take max across all GPUs. if mp_group is not None: dist.all_reduce(tensor=total_norm_cuda, op=torch.distributed.ReduceOp.MAX) total_norm = total_norm_cuda[0].item() else: total_norm = 0.0 # if dist.get_rank() == 0: # logger.info(f"Total Norm beginning {total_norm}") for g, p in zip(gradients, params): # Pipeline parallelism may replicate parameters. Avoid multi-counting. if is_model_parallel_parameter(p) or mp_rank == 0: param_norm = g.data.double().norm(2) total_norm += param_norm.item()**2 # Sum across all model parallel GPUs. total_norm_cuda = torch.cuda.FloatTensor([float(total_norm)]) torch.distributed.all_reduce(total_norm_cuda, op=torch.distributed.ReduceOp.SUM, group=dp_group) if mp_group is not None: dist.all_reduce(tensor=total_norm_cuda, op=torch.distributed.ReduceOp.SUM) total_norm = total_norm_cuda[0].item()**(1. / norm_type) if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm: total_norm = -1 return total_norm def sync_param(flat_tensor, tensor_list): """ Synchronize the flattened tensor and unflattened tensor list. When a list of tensor are flattened with `torch._utils._unflatten_dense_tensors`, a new tensor is created. Thus, the flat tensor and original tensor list do not share the same memory space. This function will update the tensor list so that they point to the same value. :param flat_tensor: A flat tensor obtained by calling `torch._utils._unflatten_dense_tensors` on a tensor lsit :param tensor_list: A list of tensors corresponding to the flattened tensor :type flat_tensor: torch.Tensor :type tensor_list: List[torch.Tensor] """ updated_params = unflatten(flat_tensor, tensor_list) # update the tensor data for p, q in zip(tensor_list, updated_params): p.data = q.data
from typing import Optional import torch import torch.distributed as dist from colossalai.registry import OPHOOKS from colossalai.utils import get_current_device from colossalai.utils.memory_tracer.memstats_collector import MemStatsCollector from colossalai.zero.shard_utils import BaseShardStrategy from colossalai.zero.sharded_param.tensorful_state import TensorState from colossalai.gemini.stateful_tensor_mgr import StatefulTensorMgr from colossalai.engine.ophooks import BaseOpHook @OPHOOKS.register_module class ZeroHook(BaseOpHook): """ A hook to process sharded param for ZeRO method. """ def __init__(self, shard_strategy: BaseShardStrategy, memstarts_collector: Optional[MemStatsCollector] = None, stateful_tensor_mgr: Optional[StatefulTensorMgr] = None, process_group: Optional[dist.ProcessGroup] = None): super().__init__() self.shard_strategy = shard_strategy self.process_group = process_group # NOTE(jiaruifang) Now the computing device of FWD and BWD is always on GPU self.computing_device = get_current_device() self._memstarts_collector = memstarts_collector self._stateful_tensor_mgr = stateful_tensor_mgr def gather_parameters(self, module: torch.nn.Module): # gather sharded parameters if module.param_is_sharded: tensor_list = [] for param in module.parameters(recurse=False): assert hasattr(param, 'colo_attr') tensor_list.append(param.colo_attr.sharded_data_tensor) self.shard_strategy.gather(tensor_list, self.process_group) def shard_parameters(self, module: torch.nn.Module): # shard gathered parameters if module.param_is_sharded: tensor_list = [] for param in module.parameters(recurse=False): assert hasattr(param, 'colo_attr') tensor_list.append(param.colo_attr.sharded_data_tensor) self.shard_strategy.shard(tensor_list, self.process_group) def adjust_module_data(self, module: torch.nn.Module): # record overall data statistics if self._memstarts_collector: self._memstarts_collector.sample_overall_data() for param in module.parameters(recurse=False): param.colo_attr.sharded_data_tensor.trans_state(TensorState.COMPUTE) # adjust stateful tensor to get enough CUDA memory self._stateful_tensor_mgr.adjust_layout() # record model data statistics if self._memstarts_collector: self._memstarts_collector.sample_model_data() def pre_fwd_exec(self, module: torch.nn.Module, *args): self.adjust_module_data(module) self.gather_parameters(module) for param in module.parameters(recurse=False): param.data = param.colo_attr.data_payload assert param.data.device.type == 'cuda', f"PRE FWD param.data must be on CUDA" def post_fwd_exec(self, module: torch.nn.Module, *args): # change tensor state to HOLD_AFTER_FWD for param in module.parameters(recurse=False): param.colo_attr.sharded_data_tensor.trans_state(TensorState.HOLD_AFTER_FWD) self.shard_parameters(module) # remove torch payload for param in module.parameters(recurse=False): param.colo_attr.set_data_none() def pre_bwd_exec(self, module: torch.nn.Module, input, output): self.adjust_module_data(module) self.gather_parameters(module) for param in module.parameters(recurse=False): param.data = param.colo_attr.data_payload assert param.data.device.type == 'cuda', f"PRE BWD param.data must be on CUDA" def post_bwd_exec(self, module: torch.nn.Module, input): # change tensor state to HOLD_AFTER_BWD for param in module.parameters(recurse=False): param.colo_attr.sharded_data_tensor.trans_state(TensorState.HOLD_AFTER_BWD) self.shard_parameters(module) # remove torch payload for param in module.parameters(recurse=False): param.colo_attr.set_data_none() def pre_iter(self): pass def post_iter(self): if self._stateful_tensor_mgr: self._stateful_tensor_mgr.reset()
from .zero_hook import ZeroHook __all__ = ['ZeroHook']
import torch from colossalai.zero.sharded_param.tensorful_state import StatefulTensor, TensorState from typing import Optional class ShardedTensor(StatefulTensor): def __init__(self, tensor: torch.Tensor, state: TensorState = TensorState.HOLD) -> None: r""" A tensor sharded in multiple processes. Constructed from an existing torch.Tensor instance. """ assert tensor.requires_grad is False super().__init__(tensor, state) # kept the shape, numel and dtype of the init tensor. self._origin_shape = tensor.shape self._origin_numel = tensor.numel() self._origin_dtype = tensor.dtype self._is_sharded = False @property def dtype(self) -> torch.dtype: assert self._payload.dtype == self._origin_dtype return self._payload.dtype @property def origin_numel(self) -> int: return self._origin_numel @property def origin_shape(self) -> int: return self._origin_shape @property def is_sharded(self): return self._is_sharded @is_sharded.setter def is_sharded(self, flag: bool): self._is_sharded = flag
import torch from colossalai.zero.sharded_param import ShardedTensor from typing import Optional, Tuple from colossalai.zero.sharded_param.tensor_utils import colo_tensor_mem_usage from .tensorful_state import StatefulTensor, TensorState from typing import List EMPTY_TENSOR_DICT = {} def get_empty_tensor(device: torch.device, dtype: torch.dtype): key = (device, dtype) if key not in EMPTY_TENSOR_DICT: EMPTY_TENSOR_DICT[key] = torch.empty(0, dtype=dtype, device=device) return EMPTY_TENSOR_DICT[key] class ShardedParamV2(object): def __init__(self, param: torch.nn.Parameter, set_data_none: bool = False) -> None: self._sharded_data_tensor: ShardedTensor = ShardedTensor(param.data) self.saved_grad: StatefulTensor = StatefulTensor(None, TensorState.FREE) # This attribute must be initialized in ShardedModel self.offload_grad: bool = False # make sure the shared param is the only owner of payload # The param.data maybe used to init the other part of the model. # For example: File "resnet.py", line 190, in __init__ # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') # So we can not empty the .data at this time self.param = param if set_data_none: self.set_data_none() def get_payload_tensors(self) -> List[StatefulTensor]: """returns stateful tensors kept by this class. """ return [self._sharded_data_tensor] def set_data_none(self): self.param.data = get_empty_tensor(self.sharded_data_tensor.device, self.sharded_data_tensor.dtype) def set_grad_none(self): self.saved_grad.set_null() @property def sharded_data_tensor(self): return self._sharded_data_tensor @property def data_payload(self): return self.sharded_data_tensor.payload @property def grad_payload(self): assert not self.saved_grad.is_null() return self.saved_grad.payload @property def param_is_sharded(self): return self.sharded_data_tensor.is_sharded def reset_data_payload(self, tensor: torch.Tensor): assert type(tensor) is torch.Tensor assert tensor.requires_grad is False self.sharded_data_tensor.reset_payload(tensor) def reset_grad_payload(self, tensor: torch.Tensor): assert type(tensor) is torch.Tensor assert tensor.requires_grad is False self.saved_grad.reset_payload(tensor) def get_memory_usage(self) -> Tuple[int, int]: """ get the memory usage of the param, including data and grad Returns: Tuple[int, int]: cuda mem usage in Byte, cpu memory usage in Byte """ cuda_mem_use, cpu_mem_use = 0, 0 def _update_mem_use(t: Optional[torch.Tensor]): if t is None: return assert isinstance(t, torch.Tensor) nonlocal cuda_mem_use nonlocal cpu_mem_use t_cuda, t_cpu = colo_tensor_mem_usage(t) cuda_mem_use += t_cuda cpu_mem_use += t_cpu address_set = set() _update_mem_use(self.data_payload) address_set.add(self.data_payload.data_ptr()) if not self.saved_grad.is_null() and self.saved_grad.data_ptr() not in address_set: _update_mem_use(self.grad_payload) address_set.add(self.saved_grad.data_ptr()) if self.param.data is not None and self.param.data.data_ptr() not in address_set: _update_mem_use(self.param.data) address_set.add(self.param.data.data_ptr()) if self.param.grad is not None and self.param.grad.data_ptr() not in address_set: _update_mem_use(self.param.grad) return cuda_mem_use, cpu_mem_use
from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor from colossalai.zero.sharded_param.sharded_param import ShardedParamV2 from colossalai.zero.sharded_param.tensor_utils import (colo_model_data_tensor_move, colo_model_data_tensor_move_inline, colo_model_data_move_to_cpu, colo_model_tensor_clone, colo_tensor_mem_usage) from colossalai.zero.sharded_param.tensorful_state import TensorState, StatefulTensor __all__ = [ 'ShardedTensor', 'ShardedParamV2', 'colo_model_data_tensor_move', 'colo_model_data_tensor_move_inline', 'colo_model_data_move_to_cpu', 'colo_model_tensor_clone', 'colo_tensor_mem_usage', 'TensorState', 'StatefulTensor' ]
import torch from colossalai.zero.sharded_param.tensorful_state import StatefulTensor from typing import Union, Tuple def colo_tensor_mem_usage(tensor: Union[torch.Tensor, StatefulTensor]) -> Tuple[int, int]: if issubclass(type(tensor), StatefulTensor): t = tensor.payload elif isinstance(tensor, torch.Tensor): t = tensor else: return 0, 0 cuda_use, cpu_use = 0, 0 mem_use = t.storage().size() * t.element_size() if t.device.type == 'cuda': cuda_use += mem_use elif t.device.type == 'cpu': cpu_use += mem_use return cuda_use, cpu_use def colo_model_data_tensor_move(src_t: Union[StatefulTensor, torch.Tensor], tgt_t: Union[StatefulTensor, torch.Tensor]) -> None: """ A colossal API for model data tensor move. The src and target tensors could be resident on both CPU and GPU. NOTE() The source tensor payload will be removed after this function. The function will record the communication volume between CPU and GPU. Args: t_src (Union[StatefulTensor, torch.Tensor]): source tensor tgt_t (Union[StatefulTensor, torch.Tensor]): target tensor """ if issubclass(type(src_t), StatefulTensor): src_t_payload = src_t.payload else: src_t_payload = src_t.data src_dev = src_t_payload.device if issubclass(type(tgt_t), StatefulTensor): tgt_t_payload = tgt_t.payload else: tgt_t_payload = tgt_t.data tgt_t_payload.copy_(src_t_payload) # remove payload of src_t if issubclass(type(src_t), StatefulTensor): src_t.reset_payload(torch.tensor([], device=src_dev, dtype=src_t_payload.dtype)) else: src_t.data = torch.tensor([], device=src_dev, dtype=src_t_payload.dtype) def colo_model_data_tensor_move_inline(t: Union[StatefulTensor, torch.Tensor], target_device: Union[torch.device, int]) -> None: """ move a tensor to the target_device Args: t (Union[StatefulTensor, torch.Tensor]): the tensor be moved target_device: a traget device, if type is int, it the index of cuda card. """ if isinstance(t, torch.Tensor): t_payload = t elif issubclass(type(t), StatefulTensor): t_payload = t.payload else: raise TypeError('colo_model_data_move_to_cpu dose not accept type {type(t)}') if not isinstance(target_device, torch.device): target_device = torch.device(f'cuda:{target_device}') # deal with torch.device('cpu') and torch.device('cpu:0) if t_payload.device.type == target_device.type: return t_payload.data = t_payload.data.to(target_device) def colo_model_data_move_to_cpu(t: Union[StatefulTensor, torch.Tensor]) -> None: """colo_model_data_move_to_cpu move a model data tensor from gpu to cpu Args: t (Union[StatefulTensor, torch.Tensor]): _description_ """ if issubclass(type(t), StatefulTensor): t_payload = t.payload elif isinstance(t, torch.Tensor): t_payload = t else: raise TypeError('colo_model_data_move_to_cpu dose not accept type {type(t)}') if t_payload.device.type == 'cpu': return # TODO() optimize the tensor moving with non-blocking t_payload.data = t_payload.data.cpu() def colo_model_tensor_clone(t: Union[StatefulTensor, torch.Tensor], target_device: torch.device) -> torch.Tensor: """ Clone a model data tensor Args: t (Union[StatefulTensor, torch.Tensor]): a model data tensor target_device (torch.device): the target device Returns: torch.Tensor: a cloned torch tensor """ t_payload = t.payload if issubclass(type(t), StatefulTensor) else t ret = t_payload.to(target_device) return ret
from enum import Enum from typing import Optional import torch class TensorState(Enum): FREE = 0 HOLD = 1 HOLD_AFTER_FWD = 2 HOLD_AFTER_BWD = 3 COMPUTE = 4 class StatefulTensor(object): """A Structure stores a Torch Tensor and labeled states. Inspired from the paper: PatrickStar: Parallel Training of Pre-trained Models via Chunk-based Memory Management https://arxiv.org/abs/2108.05818 """ def __init__(self, tensor: Optional[torch.Tensor], state: Optional[TensorState] = TensorState.HOLD) -> None: self._state = state self._payload = tensor if self._state == TensorState.FREE: assert self._payload is None, f"payload has to None if state is {self._state}" def data_ptr(self): if self._payload is None: return None return self._payload.data_ptr() @property def state(self) -> TensorState: return self._state def set_null(self) -> None: self._state = TensorState.FREE self._payload = None def is_null(self) -> bool: if self._state == TensorState.FREE: assert self._payload is None return True return False def trans_state(self, state: TensorState) -> None: self._state = state if state == TensorState.FREE: self._payload = None @property def payload(self) -> Optional[torch.Tensor]: return self._payload def copy_payload(self, tensor) -> None: self._payload.view(-1).copy_(tensor.view(-1)) def reset_payload(self, tensor) -> None: del self._payload self._payload = tensor self.trans_state(TensorState.HOLD) @property def device(self) -> torch.device: return self._payload.device @property def dtype(self) -> torch.dtype: return self._payload.dtype @property def shape(self): return self._payload.shape def to(self, device: torch.device): raise RuntimeError("Use colo_model_tensor_move install of call .to() on ShardedTensor") def to_(self, device: torch.device): raise RuntimeError("Use colo_model_tensor_move install of call .to_() on ShardedTensor")
from typing import List, Optional import torch import torch.distributed as dist from colossalai.utils import get_current_device from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor from torch._utils import _flatten_dense_tensors as flatten from .tensor_shard_strategy import TensorShardStrategy class BucketTensorShardStrategy(TensorShardStrategy): """Use the same shard scheme as `TensorShardStrategy`'s, but it gathers tensors of a sub-module together, which will fully utilize network bandwidth. It is especially useful when sub-module contains bias, since we cannot utilize network bandwidth well if we only gather a bias tensor (bias is usaully small). """ def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): tensor_list: List[ShardedTensor] = [t for t in tensor_list if t.is_sharded] if len(tensor_list) == 0: return target_device = tensor_list[0].device dtype = tensor_list[0].dtype buffer_list: List[torch.Tensor] = [] tensor_numels = [t.payload.numel() for t in tensor_list] buffer_size = sum(tensor_numels) world_size = dist.get_world_size(process_group) rank = dist.get_rank(process_group) for i in range(world_size): if i == rank: buffer_list.append(flatten([t.payload for t in tensor_list]).cuda(get_current_device())) # Release payload here, to decrease peak memory usage for t in tensor_list: t.reset_payload(None) else: buffer_list.append(torch.zeros(buffer_size, dtype=dtype, device=get_current_device())) dist.all_gather(buffer_list, buffer_list[rank], group=process_group) # Move to target device before splitting buffer # Ensure we utilize maximum PCIE bandwidth buffer_list = [buffer.to(target_device) for buffer in buffer_list] offset = 0 for i, t in enumerate(tensor_list): gathered_payload = [buffer[offset:offset + tensor_numels[i]] for buffer in buffer_list] gathered_payload = torch.cat(gathered_payload)[:t.origin_numel].view(t.origin_shape) t.reset_payload(gathered_payload) t.is_sharded = False offset += tensor_numels[i]
from .base_shard_strategy import BaseShardStrategy from .bucket_tensor_shard_strategy import BucketTensorShardStrategy from .tensor_shard_strategy import TensorShardStrategy __all__ = ['BaseShardStrategy', 'TensorShardStrategy', 'BucketTensorShardStrategy']
from abc import ABC, abstractmethod from typing import List, Optional import torch.distributed as dist from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor class BaseShardStrategy(ABC): def __init__(self) -> None: """Abstract Shard Strategy. Use to shard a tensors on multiple GPUs. """ super().__init__() @abstractmethod def shard(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): pass @abstractmethod def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): pass
import torch import torch.nn.functional as F from typing import Tuple def get_shard(tensor: torch.Tensor, rank: int, world_size: int) -> Tuple[torch.Tensor, int]: """Return the local shard of a full tensor.""" # Shard using torch.chunk to match all-gather/reduce-scatter. chunks = list(torch.flatten(tensor).chunk(world_size)) while len(chunks) < world_size: chunks.append(chunks[0].new_empty(0)) # Determine number of padding elements. num_to_pad = chunks[0].numel() - chunks[rank].numel() assert num_to_pad >= 0, num_to_pad shard = torch.zeros_like(chunks[0]) length = chunks[rank].size(0) shard_temp = shard[:length] shard_temp.copy_(chunks[rank]) return shard, num_to_pad
from typing import List, Optional import torch import torch.distributed as dist from colossalai.utils import get_current_device from colossalai.zero.sharded_param.tensor_utils import colo_model_data_tensor_move_inline from colossalai.zero.shard_utils import BaseShardStrategy from colossalai.zero.shard_utils.commons import get_shard from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor class TensorShardStrategy(BaseShardStrategy): """ A naive implementation which shard each tensor evenly over all ranks """ def shard(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): for t in tensor_list: self._shard_tensor(t, process_group) def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): for t in tensor_list: self._gather_tensor(t, process_group) def _shard_tensor(self, t: ShardedTensor, process_group: Optional[dist.ProcessGroup] = None): """ Shard tensor among processes. Args: t (ShardedTensor): a tensor to be sharded. process_group (Optional[dist.ProcessGroup], optional): the process group among which tensor shards. Defaults to None. """ if t.is_sharded: return if t.payload.device.type == 'cuda': assert t.payload.device == get_current_device(), f"shard tensor on cuda device index {t.payload.device.index},"\ f" but current cuda device is {get_current_device()}" sharded_payload, _ = get_shard(t.payload, dist.get_rank(process_group), dist.get_world_size(process_group)) t.reset_payload(sharded_payload) t.is_sharded = True def _gather_tensor(self, t: ShardedTensor, process_group: Optional[dist.ProcessGroup] = None): if not t.is_sharded: return target_device = t.device payload_numel = t.payload.numel() world_size = dist.get_world_size(process_group) rank = dist.get_rank(process_group) buffer = torch.empty(payload_numel * world_size, dtype=t.payload.dtype, device=get_current_device()) buffer_list = list(torch.chunk(buffer, chunks=world_size, dim=0)) buffer_list[rank].copy_(t.payload) dist.all_gather(buffer_list, buffer_list[rank], group=process_group, async_op=False) gathered_payload = torch.narrow(buffer, 0, 0, t.origin_numel).reshape(t.origin_shape) t.reset_payload(gathered_payload) colo_model_data_tensor_move_inline(t, target_device) t.is_sharded = False