-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Add MoE layers * Add count_parameters util * Add experiment links in README.md
- Loading branch information
Showing
10 changed files
with
203 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
from typing import List | ||
import torch | ||
|
||
|
||
class MoE(torch.nn.Module): | ||
def __init__( | ||
self, | ||
hidden_dim: int, | ||
experts: List, | ||
c: int = 2, | ||
): | ||
"""Mixture of Expert - expert choice routing layer | ||
See https://arxiv.org/pdf/2202.09368.pdf for more details. | ||
Args: | ||
hidden_dim (int): hidden dimension | ||
c (int, optional): Capacity of each expert. The capacity factor c denotes on average how | ||
many experts are utilized by a token. Defaults to 2. | ||
experts (List, optional): List of experts. Each expert is a torch.nn.Module. | ||
""" | ||
super(MoE, self).__init__() | ||
self.hidden_dim = hidden_dim | ||
self.c = c | ||
self.experts = torch.nn.ModuleList(experts) | ||
self.num_experts = len(self.experts) | ||
self.gate = torch.nn.Linear( | ||
hidden_dim, | ||
self.num_experts, | ||
bias=False | ||
) | ||
|
||
def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
"""Forward pass | ||
Args: | ||
x (torch.Tensor): Input tensor of shape (batch_size, seq_len, hidden_dim) | ||
Returns: | ||
torch.Tensor: Output tensor of shape (batch_size, seq_len, hidden_dim) | ||
""" | ||
b, l, *_ = x.shape | ||
k = self._compute_k(l) | ||
S = torch.softmax(self.gate(x), dim=-1) | ||
S = S.transpose(1, 2) # (batch_size, num_experts, tokens) | ||
G, I = torch.topk(S, k, dim=-1) | ||
# I - (batch_size, num_experts, top_k_tokens) - indices | ||
# G - (batch_size, num_experts, top_k_tokens) - weights | ||
new_x = torch.zeros_like(x) | ||
for i, expert in enumerate(self.experts): | ||
indices = I[:, i] | ||
scores = G[:, i] | ||
batch_indices = (torch | ||
.arange(b) | ||
.view(-1, 1) | ||
.expand_as(indices) | ||
) | ||
# (batch_size, top_k_tokens, hidden_dim) - tokens for expert i | ||
ex = x[batch_indices, indices] | ||
ex_pred = scores[:, :, None] * expert(ex) | ||
new_x[batch_indices, indices] += ex_pred | ||
return x | ||
|
||
def _compute_k(self, l: int) -> int: | ||
k = int((l * self.c) / self.num_experts) | ||
k = min(max(k, 1), l) | ||
return k |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
def get_moe_gpt_config( | ||
vcb_size, | ||
hdn_dim, | ||
blk_size, | ||
num_experts, | ||
c | ||
): | ||
|
||
return f""" | ||
type: 'GPT' | ||
params: | ||
dropout: 0.5 | ||
hidden_dim: {hdn_dim} | ||
num_heads: 4 | ||
dropout: 0.5 | ||
embedder: | ||
type: 'MultiEmbedder' | ||
params: | ||
embedders: | ||
- type: 'TokenEmbedder' | ||
params: | ||
dictionary_size: {vcb_size} | ||
hidden_dim: {hdn_dim} | ||
- type: 'PositionEmbedder' | ||
params: | ||
num_positions: {blk_size} | ||
hidden_dim: {hdn_dim} | ||
layers: | ||
- num: 2 | ||
type: 'TransformerLayer' | ||
params: | ||
hidden_dim: {hdn_dim} | ||
attn: | ||
type: 'Attention' | ||
params: | ||
hidden_dim: {hdn_dim} | ||
num_heads: 4 | ||
dropout: 0.5 | ||
mlp: | ||
type: 'MoE' | ||
params: | ||
hidden_dim: {hdn_dim} | ||
c: {c} | ||
experts: | ||
- num: {num_experts} | ||
type: 'MLP' | ||
params: | ||
hidden_dim: {hdn_dim} | ||
intermediate_dim: {hdn_dim} | ||
dropout: 0.5 | ||
head: | ||
type: 'ClassificationHead' | ||
params: | ||
hidden_dim: {hdn_dim} | ||
vocab_size: {vcb_size} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from pytfex.utils import set_seed | ||
from tests.basic_model import get_basic_gpt_config | ||
from tests.moe_model import get_moe_gpt_config | ||
from pytfex.transformer.make_model import init_from_yml_string | ||
|
||
import pytest | ||
|
||
|
||
@pytest.mark.parametrize('vcb_size,hdn_dim,blk_size,k,num_experts,model_type', [ | ||
(32, 12, 11, None, None, 'gpt-basic'), | ||
(32, 12, 11, 2, 4, 'gpt-moe') | ||
]) | ||
def test_train(vcb_size, hdn_dim, blk_size, k, num_experts, model_type): | ||
set_seed(0) | ||
config = { | ||
'gpt-basic': get_basic_gpt_config(vcb_size, hdn_dim, blk_size), | ||
'gpt-moe': get_moe_gpt_config(vcb_size, hdn_dim, blk_size, k, num_experts) | ||
}[model_type] | ||
model = init_from_yml_string(config) | ||
print(model) | ||
assert model |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters