layers.py 49.4 KB
Newer Older
zbian's avatar
zbian committed
1
import math
2
from collections import OrderedDict
アマデウス's avatar
アマデウス committed
3
from typing import Callable
zbian's avatar
zbian committed
4
5

import torch
アマデウス's avatar
アマデウス committed
6
7
import torch.nn as nn
import torch.nn.functional as F
8
9
10
from torch import Tensor
from torch.nn import Parameter

アマデウス's avatar
アマデウス committed
11
12
from colossalai.communication import broadcast
from colossalai.context import ParallelMode, seed
zbian's avatar
zbian committed
13
from colossalai.core import global_context as gpc
14
from colossalai.global_variables import tensor_parallel_env as env
15
from colossalai.legacy.registry import LAYERS
アマデウス's avatar
アマデウス committed
16
from colossalai.nn import init as init
17
from colossalai.utils.checkpointing import gather_tensor_parallel_state_dict, partition_tensor_parallel_state_dict
18
from colossalai.utils.cuda import get_current_device
アマデウス's avatar
アマデウス committed
19

zbian's avatar
zbian committed
20
from ..base_layer import ParallelLayer
21
from ..utils import divide, set_tensor_parallel_attribute_by_partition, to_2tuple
22
23
24
25
26
27
28
29
30
31
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,
)
アマデウス's avatar
アマデウス committed
32
from ._utils import assert_summa_initialization, get_summa_dim_from_env
zbian's avatar
zbian committed
33
34
35
36


@LAYERS.register_module
class Linear2D(ParallelLayer):
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    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>`_.
zbian's avatar
zbian committed
53
    """
54

zbian's avatar
zbian committed
55
56
57
58
    def __init__(self,
                 in_features: int,
                 out_features: int,
                 bias: bool = True,
59
                 dtype: torch.dtype = None,
Frank Lee's avatar
Frank Lee committed
60
                 skip_bias_add: bool = False,
アマデウス's avatar
アマデウス committed
61
62
                 weight_initializer: Callable = init.kaiming_uniform_(a=math.sqrt(5)),
                 bias_initializer: Callable = init.xavier_uniform_(a=1, scale=1)):
zbian's avatar
zbian committed
63
64
65
66
67
68
69
70
71
72
73
74
75
        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
アマデウス's avatar
アマデウス committed
76
77
        self.input_size_per_partition = divide(self.in_features, self.summa_dim)
        self.hidden_size_per_partition = divide(self.out_features, self.summa_dim)
zbian's avatar
zbian committed
78
79
80

        # create weight, shape: [k/q, h/q]
        factory_kwargs = {'device': get_current_device(), 'dtype': dtype}
アマデウス's avatar
アマデウス committed
81
82
        self.weight = Parameter(
            torch.empty(self.input_size_per_partition, self.hidden_size_per_partition, **factory_kwargs))
zbian's avatar
zbian committed
83
84
85

        # create bias, shape: [h/q]
        if bias:
アマデウス's avatar
アマデウス committed
86
            self.bias = Parameter(torch.empty(divide(self.out_features, self.summa_dim**2), **factory_kwargs))
zbian's avatar
zbian committed
87
88
89
90
        else:
            self.register_parameter('bias', None)

        # initialize parameters
Frank Lee's avatar
Frank Lee committed
91
        with seed(ParallelMode.TENSOR):
アマデウス's avatar
アマデウス committed
92
            self.reset_parameters(weight_initializer, bias_initializer)
zbian's avatar
zbian committed
93
94
95
        self._set_tensor_parallel_attributes()

    def _set_tensor_parallel_attributes(self):
アマデウス's avatar
アマデウス committed
96
        set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2)
zbian's avatar
zbian committed
97
        if self.bias is not None:
アマデウス's avatar
アマデウス committed
98
            set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2)
zbian's avatar
zbian committed
99

アマデウス's avatar
アマデウス committed
100
    def reset_parameters(self, weight_initializer, bias_initializer) -> None:
Frank Lee's avatar
Frank Lee committed
101
        fan_in, fan_out = self.in_features, self.out_features
アマデウス's avatar
アマデウス committed
102
        weight_initializer(self.weight, fan_in=fan_in, fan_out=fan_out)
zbian's avatar
zbian committed
103
        if self.bias is not None:
アマデウス's avatar
アマデウス committed
104
            bias_initializer(self.bias, fan_in=fan_in)
zbian's avatar
zbian committed
105

106
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        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
            },
        )

149
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
150

151
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        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)

zbian's avatar
zbian committed
191
192
193
    def forward(self, x: Tensor) -> Tensor:
        # input: [m/q, n/q, k/q]
        # output: [m/q, n/q, h/q]
194
        out_shape = x.shape[:-1] + (self.hidden_size_per_partition,)
アマデウス's avatar
アマデウス committed
195
196
197
198

        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)
zbian's avatar
zbian committed
199
200
201

        if self.bias is not None:
            if self.skip_bias_add:
202
203
204
205
                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)
zbian's avatar
zbian committed
206
207
                return output, bias
            else:
208
209
210
211
                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)
zbian's avatar
zbian committed
212
213
214
215
216
217
218
                return output
        else:
            return output


@LAYERS.register_module
class LayerNorm2D(ParallelLayer):
219
220
221
222
223
224
225
226
227
    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.
228
        bias (bool, optional): Whether to add a bias, defaults to ``True``.
229
        dtype (:class:`torch.dtype`, optional): The dtype of parameters, defaults to None.
zbian's avatar
zbian committed
230
    """
231

232
    def __init__(self, normalized_shape: int, eps: float = 1e-05, bias=True, dtype=None):
zbian's avatar
zbian committed
233
234
235
236
237
238
239
240
241
242
243
244
245
        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
アマデウス's avatar
アマデウス committed
246
        self.partitioned_partition = divide(normalized_shape, self.summa_dim**2)
zbian's avatar
zbian committed
247
248
249
250

        # create parameters
        factory_kwargs = {'device': get_current_device(), 'dtype': dtype}

251
        self.weight = Parameter(torch.ones(self.partitioned_partition, **factory_kwargs))
252
253
254
255
        if bias:
            self.bias = Parameter(torch.zeros(self.partitioned_partition, **factory_kwargs))
        else:
            self.bias = None
zbian's avatar
zbian committed
256
257
258
259

        self._set_tensor_parallel_attributes()

    def _set_tensor_parallel_attributes(self):
260
        set_tensor_parallel_attribute_by_partition(self.weight, self.summa_dim**2)
261
262
        if self.bias is not None:
            set_tensor_parallel_attribute_by_partition(self.bias, self.summa_dim**2)
263

264
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        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
            },
        )

306
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
307

308
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
309
310
        weight_key = prefix + 'weight'
        bias_key = prefix + 'bias'
311
312
313
        local_state = OrderedDict({weight_key: self.weight})
        if self.bias is not None:
            local_state[bias_key] = self.bias
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

        # 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)
zbian's avatar
zbian committed
346
347
348

    def forward(self, x: Tensor) -> Tensor:
        with torch.no_grad():
349
            E_x = torch.sum(x, dim=-1, keepdim=True)    # [b/q, s, 1]
アマデウス's avatar
アマデウス committed
350
            torch.distributed.all_reduce(E_x, group=gpc.get_group(ParallelMode.PARALLEL_2D_ROW))
zbian's avatar
zbian committed
351
352
353
            E_x /= self.normalized_shape

            # Var_x in the block below is the sum of input^2
354
            Var_x = torch.sum(x * x, dim=-1, keepdim=True)    # [b/q, s, 1]
アマデウス's avatar
アマデウス committed
355
            torch.distributed.all_reduce(Var_x, group=gpc.get_group(ParallelMode.PARALLEL_2D_ROW))
zbian's avatar
zbian committed
356
357
            Var_x /= self.normalized_shape

358
            Var_x = Var_x - E_x * E_x    # variance of x [b/q, s, 1]
zbian's avatar
zbian committed
359
360
361
            # this time 1/sqrt(Var_x + epsilon)
            Var_x = 1.0 / torch.sqrt(Var_x + self.variance_epsilon)

362
363
        output = layernorm_2d(x, E_x, Var_x, self.normalized_shape, ParallelMode.PARALLEL_2D_ROW,
                              ParallelMode.PARALLEL_2D_COL)
364
        scale = add_bias_2d(None, self.weight, self.partitioned_partition, self.row_rank, self.col_rank,
365
366
                            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)
367
368
369
370
371
372
373
374
        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)
zbian's avatar
zbian committed
375
        return output
アマデウス's avatar
アマデウス committed
376
377
378
379


@LAYERS.register_module
class PatchEmbedding2D(ParallelLayer):
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    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>`_.
アマデウス's avatar
アマデウス committed
398
    """
399

アマデウス's avatar
アマデウス committed
400
401
402
403
404
405
    def __init__(self,
                 img_size: int,
                 patch_size: int,
                 in_chans: int,
                 embed_size: int,
                 flatten: bool = True,
406
                 dtype: torch.dtype = None,
アマデウス's avatar
アマデウス committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
                 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)

455
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
        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
            },
        )

515
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
516

517
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        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)

アマデウス's avatar
アマデウス committed
569
    def forward(self, input_: Tensor) -> Tensor:
570
        input_ = split_batch_2d(input_)
571

アマデウス's avatar
アマデウス committed
572
573
574
575
        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]})."

576
577
        weight = all_gather_tensor_2d(self.weight, 0, ParallelMode.PARALLEL_2D_COL)
        bias = all_gather_tensor_2d(self.bias, 0, ParallelMode.PARALLEL_2D_COL)
アマデウス's avatar
アマデウス committed
578
579
580

        output = F.conv2d(input_, weight, bias, stride=self.patch_size)
        if self.flatten:
581
            output = output.flatten(2).transpose(1, 2)    # BCHW -> BNC
アマデウス's avatar
アマデウス committed
582

583
584
        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)
アマデウス's avatar
アマデウス committed
585
586
587
588
589
590
591
592
593
        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):
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    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>`_
621
    """
622

アマデウス's avatar
アマデウス committed
623
624
625
626
    def __init__(self,
                 num_embeddings: int,
                 embedding_dim: int,
                 padding_idx: int = None,
627
                 dtype: torch.dtype = None,
アマデウス's avatar
アマデウス committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
                 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)

663
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
        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},
        )

688
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
689

690
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        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)

アマデウス's avatar
アマデウス committed
714
    def forward(self, input_: Tensor) -> Tensor:
715
        input_ = split_batch_2d(input_)
アマデウス's avatar
アマデウス committed
716

717
        weight = all_gather_tensor_2d(self.weight, -1, ParallelMode.PARALLEL_2D_COL)
アマデウス's avatar
アマデウス committed
718
719
720
721
722
        output = F.embedding(input_, weight, self.padding_idx, *self.embed_args, **self.embed_kwargs)

        return output


723
@LAYERS.register_module
724
class VocabParallelEmbedding2D(ParallelLayer):
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
    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>`_.
752
    """
753

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
    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:
796
        if self.padding_idx is not None and \
797
                self.padding_idx >= self.vocab_start_index and self.padding_idx < self.vocab_end_index:
798
            with torch.no_grad():
799
                self.weight[self.padding_idx - self.vocab_start_index].fill_(0)
800

801
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
        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},
        )

826
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
827

828
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
        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)

852
853
854
855
856
857
858
859
860
861
862
863
864
    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


アマデウス's avatar
アマデウス committed
865
866
@LAYERS.register_module
class Classifier2D(ParallelLayer):
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
    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>`_.
882
    """
883

アマデウス's avatar
アマデウス committed
884
885
886
887
888
    def __init__(self,
                 in_features: int,
                 num_classes: int,
                 weight: Parameter = None,
                 bias: bool = True,
889
                 dtype: torch.dtype = None,
アマデウス's avatar
アマデウス committed
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
                 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)

936
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
        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
            },
        )

980
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
981

982
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        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)

アマデウス's avatar
アマデウス committed
1023
    def forward(self, input_: Tensor) -> Tensor:
1024
        out_shape = input_.shape[:-1] + (self.num_classes,)
アマデウス's avatar
アマデウス committed
1025

1026
1027
1028
1029
1030
1031
1032
        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):
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
    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>`_.
1048
    """
1049

1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
    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)

1107
    def _load_from_global_state_dict(self, state_dict, prefix, *args, **kwargs):
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
        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
            },
        )

1151
        super()._load_from_global_state_dict(local_state, prefix, *args, **kwargs)
1152

1153
    def _save_to_global_state_dict(self, destination, prefix, keep_vars):
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
        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)

1195
1196
1197
    def forward(self, x: Tensor) -> Tensor:
        # input: [m/q, n/q, k/q]
        # output: [m/q, n/q, h/q]
1198
        out_shape = x.shape[:-1] + (self.output_size_per_partition,)
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

        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