PyTorch
File size: 4,843 Bytes
bd992b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A standard implementation of Mixture of Experts (MoE), which can be used in the transformer block (to replace MLP)
This implementation features a Linear classifier router ith 8 identical experts by default.
"""


class MoE(nn.Module):

    def __init__(self, dim_model, dim_hidden_layer, num_experts: int = 8, top_k: int = 2):

        """
        num_experts (int): The number of experts.
        top_k (int): The number of top-scoring experts to be chosen by the router.
        router (torch.Linear): The router, which is a Linear classifier.
        experts (torch.ModuleList): A list of individual expert FFNs, creates exactly num_experts of them upon initialization
        """
        super().__init__()

        self.num_experts = num_experts
        self.top_k = top_k
        self.router = nn.Linear(dim_model, num_experts, bias=False)

        # Pytorch has a thing where you can hold a list of modules, like NNs, so this is a list 
        # that holds all the expert FFNs, and creates exactly num_experts of them

        #                            |<----------------------------- Expert network ------------------------------->|
        self.experts = nn.ModuleList(
            [nn.Sequential(nn.Linear(dim_model, dim_hidden_layer), nn.GELU(), nn.Linear(dim_hidden_layer, dim_model))
             for _ in range(num_experts)])

    def forward(self, x, return_aux_loss: bool = False):

        """
        x (torch.tensor): The input, of dim (B, T, C) where...
        
        B (int): Batch size
        T (int): Time (Sequence Length)
        C (int): Channels (dim_model)
        """
        B, T, C = x.size()

        """
        The input vector is flattened into a size ((B * T) * C) because that makes it easier to work with
        (grabbing tokens you would need to assign to an expert is easier with a flat list rather than a multi-dimensional one)
        """
        x_flat = x.view(B * T, C)

        # Classify the top scorers
        router_logits = self.router(x_flat)

        """
        Find the top experts (top_k) for each token
        
        routing_weights (torch.Tensor, float): The actual values inside of the logits list
        selected_experts (torch.Tensor, int): The indices of those values (Like the expert at index 6 or 7)
        final_output (torch.Tensor): The final values placed after calculating the top_k experts' outputs
        """
        routing_weights, selected_experts = torch.topk(router_logits, self.top_k, dim=-1)

        # Put the top scorers through softmax so they sum up to 1.0
        routing_weights = F.softmax(routing_weights, dim=-1)

        """
        Gonna kinda half treat this as triples of (token_idx, expert_idx, routing_weight).
        Flattened out to B*T*top_k
        """
        token_indexes = torch.repeat_interleave(torch.arange(B*T, device=x.device),self.top_k)
        selected_experts_flat = selected_experts.view(B*T*self.top_k)
        routing_weights_flat = routing_weights.view(B*T*self.top_k)

        # Sort by the expert indexes, so that we have each expert's tokens and weights in a row
        sorted_experts, order = torch.sort(selected_experts_flat)
        sorted_tokens = token_indexes[order]
        sorted_routing_weights = routing_weights_flat[order]

        # Simple counting for how many tokens each expert gets
        expert_counts = torch.bincount(sorted_experts, minlength=self.num_experts)
        expert_counts_cpu = expert_counts.cpu()
        expert_ends = torch.cumsum(expert_counts_cpu, dim=0)
        expert_starts = expert_ends - expert_counts_cpu

        final_output = torch.zeros_like(x_flat)


        # Loop over experts
        for i in range(self.num_experts):

            start = expert_starts[i].item()
            end = expert_ends[i].item()
            # Pass if expert has no tokens
            if start == end:
                continue

            # Get the tokens and weights for this specific expert
            token_ids = sorted_tokens[start:end]
            weights = sorted_routing_weights[start:end].unsqueeze(-1)

            # Get expert output
            expert_out = self.experts[i](x_flat[token_ids])
            # Scatter add (B*T, C). token_ids is (B*T), so we unsqueeze it to (B*T, 1)
            # and then expand_as to get it to (B*T, C).
            final_output.scatter_add_(0, token_ids.unsqueeze(-1).expand_as(expert_out), expert_out * weights)

        # Reshape
        final_output = final_output.view(B, T, C)

        if return_aux_loss:

            f_i = expert_counts.float() / (B * T * self.top_k)
            p_i = F.softmax(router_logits, dim=-1).mean(dim=0)
            aux_loss = self.num_experts * (f_i * p_i).sum()
            return final_output, aux_loss

        return final_output