gshard_gate.py 1.26 KB
Newer Older
Rick Ho's avatar
Rick Ho committed
1
2
3
r"""
Balanced gate with GShard's policy (Google, 2020)
"""
Rick Ho's avatar
Rick Ho committed
4
import math
Rick Ho's avatar
Rick Ho committed
5
6
7
import torch
import torch.nn.functional as F
from .naive_gate import NaiveGate
Rich Ho's avatar
Rich Ho committed
8
from .utils import limit_by_capacity
Rick Ho's avatar
Rick Ho committed
9
10
11
12
13
14
15
16


class GShardGate(NaiveGate):
    def __init__(self, d_model, num_expert, world_size, capacity=(1.2, 2.4)):
        super().__init__(d_model, num_expert, world_size, top_k=2)
        self.capacity = capacity

    def forward(self, x):
Rich Ho's avatar
Rich Ho committed
17
18
        naive_outs = super().forward(x, return_all_scores=True)
        topk_idx, topk_val, gate_score = naive_outs
Rick Ho's avatar
Rick Ho committed
19
20
21
22
23

        S = gate_score.shape[0]
        top_k = topk_idx.shape[0] // gate_score.shape[0]
        top1_idx = topk_idx.view((-1, top_k))[:, 0]
        c_e = torch.scatter_add(
Rick Ho's avatar
Rick Ho committed
24
                torch.zeros(self.tot_expert, device=top1_idx.device),
Rick Ho's avatar
Rick Ho committed
25
26
27
28
29
30
31
32
                0,
                top1_idx,
                torch.ones_like(top1_idx, dtype=torch.float),
                ) / S
        m_e = torch.mean(F.softmax(gate_score, dim=1), dim=0)
        loss = torch.mean(c_e * m_e) * (self.num_expert ** 2)
        self.set_loss(loss)

Rick Ho's avatar
Rick Ho committed
33
        cap_rate = self.capacity[0 if self.training else 1]
Rich Ho's avatar
Rich Ho committed
34
35
        capacity = math.ceil(cap_rate * x.shape[0])
        limit_by_capacity(topk_idx, self.num_expert, self.world_size, capacity)
Rick Ho's avatar
Rick Ho committed
36
37

        return topk_idx, topk_val