moe.py 1.28 KB
Newer Older
Jiezhong Qiu's avatar
update  
Jiezhong Qiu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import math
from torch import nn
from torch.autograd import Function
import torch

import moe_cuda

torch.manual_seed(42)


class MOEFunction(Function):
    @staticmethod
    def forward(ctx, input, gate, weight):
        output = moe_cuda.forward(input, gate, weight)
        variables = [input, gate, weight]
        ctx.save_for_backward(*variables)

        return output[0]

    @staticmethod
    def backward(ctx, grad_out):
        grad_input, grad_weight = moe_cuda.backward(
Jiezhong Qiu's avatar
update  
Jiezhong Qiu committed
23
24
            grad_out.contiguous(), *ctx.saved_tensors)
        return grad_input, None, grad_weight
Jiezhong Qiu's avatar
update  
Jiezhong Qiu committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48


class MOELayer(nn.Module):
    def __init__(self, num_expert=32, in_feat=1024, out_feat=4096):
        super(MOELayer, self).__init__()
        self.weight = nn.Parameter(
            torch.Tensor(num_expert, out_feat, in_feat))
        self.reset_parameters()

    def reset_parameters(self):
        pass

    def forward(self, input, gate):
        return MOEFunction.apply(input, gate, self.weight)


batch_size = 64
num_expert = 32
in_feat = 512
out_feat = 512

moe = MOELayer(num_expert, in_feat, out_feat).cuda()

input = torch.rand(batch_size, in_feat).cuda()
Jiezhong Qiu's avatar
update  
Jiezhong Qiu committed
49
gate = torch.randint(low=0, high=num_expert, size=(batch_size, ), requires_grad=False).int().cuda()
Jiezhong Qiu's avatar
update  
Jiezhong Qiu committed
50
51

output = moe(input, gate)
Jiezhong Qiu's avatar
fix  
Jiezhong Qiu committed
52
53
54
55


y = output.mean()
y.backward()