# 2D 张量并行

## 引言​

1D张量并行没有对 activations 进行划分，就大规模模型而言，这也会消耗大量的内存。 为了平均分配计算和内存负荷，在 SUMMA（可扩展的通用矩阵乘法算法）的基础上， 2D张量并行 被引入。

$\left[\begin{matrix} X_{10} & X_{11} \\ X_{00} & X_{01} \end{matrix} \right] \text{~and~} \left[\begin{matrix} A_{10} & A_{11} \\ A_{00} & A_{01} \end{matrix} \right]。$

$\left[\begin{matrix} X_{10},A_{00} & X_{10},A_{01} \\ X_{00},A_{00} & X_{00},A_{01} \end{matrix} \right]。$

$\left[\begin{matrix} X_{10}A_{00} & X_{10}A_{01} \\ X_{00}A_{00} & X_{00}A_{01} \end{matrix} \right] (1)。$

$\left[\begin{matrix} X_{11}A_{10} & X_{11}A_{11} \\ X_{01}A_{10} & X_{01}A_{11} \end{matrix} \right] (2)。$

$Y = XA = \left[\begin{matrix} X_{10}A_{00}+X_{11}A_{10} & X_{10}A_{01}+X_{11}A_{11} \\ X_{00}A_{00}+X_{01}A_{10} & X_{00}A_{01}+X_{01}A_{11} \end{matrix} \right]。$

## 效率​

$O(1/q^2)$$O(1/q^2)$$O(1/q^2)$$O(6(q-1)/q)$$O(6(q-1))$

## 使用​

CONFIG = dict(parallel=dict(    data=1,    pipeline=1,    tensor=dict(size=4, mode='2d'),))

import colossalaiimport colossalai.nn as col_nnimport torchfrom colossalai.utils import print_rank_0class MLP(torch.nn.Module):    def __init__(self, dim: int = 256):        super().__init__()        intermediate_dim = dim * 4        self.dense_1 = col_nn.Linear(dim, intermediate_dim)        print_rank_0(f'Weight of the first linear layer: {self.dense_1.weight.shape}')        self.activation = torch.nn.GELU()        self.dense_2 = col_nn.Linear(intermediate_dim, dim)        print_rank_0(f'Weight of the second linear layer: {self.dense_2.weight.shape}')        self.dropout = col_nn.Dropout(0.1)    def forward(self, x):        x = self.dense_1(x)        print_rank_0(f'Output of the first linear layer: {x.shape}')        x = self.activation(x)        x = self.dense_2(x)        print_rank_0(f'Output of the second linear layer: {x.shape}')        x = self.dropout(x)        return x

parser = colossalai.get_default_parser()colossalai.launch(config=CONFIG,                  rank=args.rank,                  world_size=args.world_size,                  local_rank=args.local_rank,                  host=args.host,                  port=args.port)m = MLP()

Weight of the first linear layer: torch.Size([128, 512])Weight of the second linear layer: torch.Size([512, 128])

from colossalai.context import ParallelModefrom colossalai.core import global_context as gpcfrom colossalai.utils import get_current_devicex = torch.randn((16, 256), device=get_current_device())# partition inputtorch.distributed.broadcast(x, src=0)x = torch.chunk(x, 2, dim=0)[gpc.get_local_rank(ParallelMode.PARALLEL_2D_COL)]x = torch.chunk(x, 2, dim=-1)[gpc.get_local_rank(ParallelMode.PARALLEL_2D_ROW)]print_rank_0(f'Input: {x.shape}')x = m(x)

Input: torch.Size([8, 128])Output of the first linear layer: torch.Size([8, 512])Output of the second linear layer: torch.Size([8, 128])

2D并行中的 activation 张量都是同时在行和列分割的。例如，第一个线性层的输出是 [8, 512], 而第二层的输出为 [8, 128]