layers.py 4.59 KB
Newer Older
Rick Ho's avatar
Rick Ho committed
1
from .functions import *
Rick Ho's avatar
Rick Ho committed
2
import torch.nn as nn
Rick Ho's avatar
Rick Ho committed
3
import torch.nn.functional as F
Rick Ho's avatar
Rick Ho committed
4
5
6
7


class FMoELinear(nn.Module):
    def __init__(self, num_expert=32, in_feat=1024, out_feat=1024):
Rick Ho's avatar
Rick Ho committed
8
        super(FMoELinear, self).__init__()
Rick Ho's avatar
Rick Ho committed
9
10
11
        self.num_expert = num_expert
        self.in_feat = in_feat
        self.out_feat = out_feat
12
        self.weight = nn.Parameter(torch.Tensor(num_expert, out_feat, in_feat))
Rick Ho's avatar
Rick Ho committed
13
14
15
16
17
18
19
20
21
22
23
        self.reset_parameters()

    def reset_parameters(self):
        for i in range(self.num_expert):
            linear = nn.Linear(in_features=self.in_feat, out_features=self.out_feat)
            self.weight.data[i] = linear.weight.data

    def forward(self, inp, fwd_expert_count):
        return MOELinear.apply(inp, self.weight, fwd_expert_count)


Rick Ho's avatar
Rick Ho committed
24
25
class FMoENaiveGate(nn.Module):
    def __init__(self, d_model, num_expert, world_size, top_k=2):
Rick Ho's avatar
Rick Ho committed
26
27
        super(FMoENaiveGate, self).__init__()
        self.gate = nn.Linear(d_model, num_expert * world_size)
Rick Ho's avatar
Rick Ho committed
28
        self.top_k = top_k
Rick Ho's avatar
Rick Ho committed
29
30
31

    def forward(self, inp):
        gate = self.gate(inp)
32
33
34
        gate_top_k_val, gate_top_k_idx = torch.topk(
            gate, k=self.top_k, dim=-1, largest=True, sorted=False
        )  # [.. x top_k]
Rick Ho's avatar
Rick Ho committed
35
36
        gate_top_k_val = gate_top_k_val.view(-1, self.top_k)

37
38
39
        # (BxL) x 1 x top_k
        gate_score = F.softmax(gate_top_k_val, dim=-1).unsqueeze(1)
        gate_top_k_idx = gate_top_k_idx.view(-1)  # (BxLxtop_k)
Rick Ho's avatar
Rick Ho committed
40
41
42
43
44

        return gate_top_k_idx, gate_score


def _fmoe_full_forward(inp, gate, linears, activation, num_expert, world_size):
45
46
47
48
49
50
51
52
53
54
    (
        pos,
        local_expert_count,
        global_expert_count,
        fwd_expert_count,
        fwd_batch_size,
    ) = moe_prepare_forward(gate, num_expert, world_size)
    x = MOEScatter.apply(
        inp, pos, local_expert_count, global_expert_count, fwd_batch_size, world_size
    )
Rick Ho's avatar
Rick Ho committed
55
56
57
    for i, l in enumerate(linears):
        if i:
            x = activation(x)
58
        x = l(x, fwd_expert_count)
59
60
61
    x = MOEGather.apply(
        x, pos, local_expert_count, global_expert_count, inp.shape[0], world_size
    )
Rick Ho's avatar
Rick Ho committed
62
63
64
    return x


Rick Ho's avatar
Rick Ho committed
65
class FMoETransformerMLP(nn.Module):
66
67
68
69
70
71
    def __init__(
        self,
        num_expert=32,
        d_model=1024,
        d_hidden=4096,
        world_size=1,
Rick Ho's avatar
fmoefy  
Rick Ho committed
72
        mp_group=None,
73
74
75
76
        activation=torch.nn.functional.gelu,
        top_k=2,
        pre_lnorm=False,
    ):
Rick Ho's avatar
Rick Ho committed
77
78
79
80
81
        super(FMoETransformerMLP, self).__init__()
        self.num_expert = num_expert
        self.d_model = d_model
        self.d_hidden = d_hidden
        self.world_size = world_size
Rick Ho's avatar
fmoefy  
Rick Ho committed
82
        self.mp_group = mp_group
Rick Ho's avatar
Rick Ho committed
83
84
85
86
87
88
        if mp_group is None:
            self.mp_size = 1
            self.mp_rank = 0
        else:
            self.mp_size = mp_group.size()
            self.mp_rank = mp_group.rank()
Rick Ho's avatar
Rick Ho committed
89
90
        self.activation = activation
        self.pre_lnorm = pre_lnorm
Rick Ho's avatar
Rick Ho committed
91
        self.top_k = top_k
Rick Ho's avatar
Rick Ho committed
92
93

        self.htoh4 = FMoELinear(num_expert, d_model, d_hidden)
94
        self.h4toh = FMoELinear(num_expert, d_hidden, d_model)
Rick Ho's avatar
Rick Ho committed
95

Rick Ho's avatar
Rick Ho committed
96
        self.gate = FMoENaiveGate(d_model, num_expert, world_size, top_k)
Rick Ho's avatar
Rick Ho committed
97
98
        for p in self.gate.parameters():
            setattr(p, 'dp_comm', 'world')
Rick Ho's avatar
Rick Ho committed
99
100

        self.layer_norm = nn.LayerNorm(d_model)
101
102
103
        self.bias = torch.nn.parameter.Parameter(
            torch.zeros(d_model, dtype=torch.float32)
        )
Rick Ho's avatar
Rick Ho committed
104

Sengxian's avatar
Sengxian committed
105
    def forward(self, inp: torch.Tensor):
106
107
108
        original_shape = inp.shape
        inp = inp.reshape(-1, self.d_model)

Rick Ho's avatar
Rick Ho committed
109
        if self.mp_size > 1:
110
            B: int = inp.shape[0]
Rick Ho's avatar
Rick Ho committed
111
112
            local_batch_size = B // self.mp_size
            batch_start = local_batch_size * self.mp_rank
Sengxian's avatar
Sengxian committed
113
            batch_end = min(batch_start + local_batch_size, B)
114
            inp = inp[batch_start:batch_end]
Sengxian's avatar
Sengxian committed
115

Rick Ho's avatar
Rick Ho committed
116
117
118
119
120
121
        residual = inp
        if self.pre_lnorm:
            inp = self.layer_norm(inp)

        gate_top_k_idx, gate_score = self.gate(inp)

122
123
124
        # to: (BxLxtop_k) x d_model
        inp = inp.repeat_interleave(repeats=self.top_k, dim=0)

125
126
127
128
129
130
131
132
133
        x = _fmoe_full_forward(
            inp,
            gate_top_k_idx,
            [self.htoh4, self.h4toh],
            self.activation,
            self.num_expert,
            self.world_size,
        )

134
135
136
137
        # to: (BxL) x top_k x d_model
        core_out = x.view(-1, self.top_k, self.d_model)
        # to: (BxL) x 1 x d_model
        core_out = torch.bmm(gate_score, core_out)
Rick Ho's avatar
Rick Ho committed
138
        output = core_out.reshape(residual.shape) + residual
Rick Ho's avatar
Rick Ho committed
139
140
141

        if not self.pre_lnorm:
            output = self.layer_norm(output)
Sengxian's avatar
Sengxian committed
142

Rick Ho's avatar
Rick Ho committed
143
144
145
        if self.mp_size > 1:
            output = AllGather.apply(output, 
                    self.mp_rank, self.mp_size, self.mp_group)
Sengxian's avatar
Sengxian committed
146

147
        return output.reshape(original_shape), self.bias