fused_layer_norm.py 3.65 KB
Newer Older
Jared Casper's avatar
Jared Casper committed
1
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
3
4

"""This code is copied fron NVIDIA apex:
      https://github.com/NVIDIA/apex
5
   with some changes. """
6

xingjinliang's avatar
xingjinliang committed
7
import inspect
8
import numbers
9
import torch
10
11
12
13
from torch.nn.parameter import Parameter
from torch.nn import init
import importlib

14
from megatron.core.utils import make_viewless_tensor
Lawrence McAfee's avatar
fixed.  
Lawrence McAfee committed
15

16
17
try:
    from apex.contrib.layer_norm.layer_norm import FastLayerNormFN
xingjinliang's avatar
xingjinliang committed
18
19
    HAVE_PERSIST_LAYER_NORM = True
except ImportError:
liangjj's avatar
update  
liangjj committed
20
    HAVE_PERSIST_LAYER_NORM = False
21

xingjinliang's avatar
xingjinliang committed
22
23
24
25
try:
    from apex.normalization.fused_layer_norm import fused_layer_norm_affine
except ImportError:
    fused_layer_norm_affine = None
26

27
28
global fused_layer_norm_cuda
fused_layer_norm_cuda = None
29
30
31


class MixedFusedLayerNorm(torch.nn.Module):
32

33
34
  def __init__(self, normalized_shape, eps=1e-5,
               no_persist_layer_norm=True,
Mostofa Patwary's avatar
Mostofa Patwary committed
35
36
               sequence_parallel=False,
               apply_layernorm_1p=False):
37
38
        super(MixedFusedLayerNorm, self).__init__()

Jared Casper's avatar
Jared Casper committed
39
        self.apply_layernorm_1p = apply_layernorm_1p
Mostofa Patwary's avatar
Mostofa Patwary committed
40

41
42
        global fused_layer_norm_cuda
        fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda")
43

Sangkug Lym's avatar
Sangkug Lym committed
44
45
46
47
48
49
        # List of hiddens sizes supported in the persistent layer norm kernel
        # If the hidden size is not supported, fall back to the non-persistent
        # kernel.
        persist_ln_hidden_sizes = [1024, 1536, 2048, 2304, 3072, 3840, 4096,
            5120, 6144, 8192, 10240, 12288, 12800, 15360, 16384, 18432, 20480,
            24576, 25600, 30720, 32768, 40960, 49152, 65536]
50
51
        if normalized_shape not in persist_ln_hidden_sizes or \
                not HAVE_PERSIST_LAYER_NORM:
Sangkug Lym's avatar
Sangkug Lym committed
52
53
            no_persist_layer_norm = True

54
55
56
57
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = (normalized_shape,)
        self.normalized_shape = torch.Size(normalized_shape)
        self.eps = eps
58
59
        self.weight = Parameter(torch.Tensor(*normalized_shape))
        self.bias = Parameter(torch.Tensor(*normalized_shape))
60
        self.reset_parameters()
Sangkug Lym's avatar
Sangkug Lym committed
61
        self.no_persist_layer_norm = no_persist_layer_norm
62
        self.sequence_parallel = sequence_parallel
63

64
        # set sequence parallelism flag on weight and bias parameters
65
66
        setattr(self.weight, 'sequence_parallel', self.sequence_parallel)
        setattr(self.bias, 'sequence_parallel', self.sequence_parallel)
Mostofa Patwary's avatar
Mostofa Patwary committed
67

68
69
70

  def reset_parameters(self):

Mostofa Patwary's avatar
Mostofa Patwary committed
71
72
73
    if self.apply_layernorm_1p:
        init.zeros_(self.weight)
        init.zeros_(self.bias)
Mostofa Patwary's avatar
Mostofa Patwary committed
74
    else:
Mostofa Patwary's avatar
Mostofa Patwary committed
75
76
        init.ones_(self.weight)
        init.zeros_(self.bias)
77
78
79

  def forward(self, input):

Jared Casper's avatar
Jared Casper committed
80
81
    weight = self.weight + 1 if self.apply_layernorm_1p else self.weight

Sangkug Lym's avatar
Sangkug Lym committed
82
    if self.no_persist_layer_norm:
xingjinliang's avatar
xingjinliang committed
83
84
85
        assert fused_layer_norm_affine is not None, \
            "fused_layer_norm_affine is not available, please install apex from https://github.com/NVIDIA/apex"
        return fused_layer_norm_affine(input, weight, self.bias, self.normalized_shape, eps=self.eps)
Sangkug Lym's avatar
Sangkug Lym committed
86
    else:
xingjinliang's avatar
xingjinliang committed
87
88
89
90
        if 'memory_efficient' in inspect.getfullargspec(FastLayerNormFN.forward).args:
            output = FastLayerNormFN.apply(input, weight, self.bias, self.eps, False)
        else:
            output = FastLayerNormFN.apply(input, weight, self.bias, self.eps)
Lawrence McAfee's avatar
fixed.  
Lawrence McAfee committed
91
92
93
94
95
96
97
98
99
        # Apex's fast layer norm function outputs a 'view' tensor (i.e., has
        # a populated '_base' field). This will result in schedule.py's
        # deallocate_output_tensor() throwing an error, so a viewless tensor is
        # created to prevent this.
        output = make_viewless_tensor(inp = output,
                                      requires_grad = input.requires_grad,
                                      keep_graph = True)

        return output