PyTorch
Adria / module /transformers /moe /transformer_block.py
Nebulon33's picture
Upload 84 files
bd992b7 verified
Raw History Blame Contribute Delete
2.7 kB
from typing import Optional
import torch
import torch.nn as nn
from module.transformers.vanilla.multi_head_attention import VanillaMultiHeadAttention
from module.transformers.moe.moe import MoE
"""
A standard 'vanilla' transformer block with pre-norm, multi-head attention, and MoE.
"""
class MoEVanillaTransformerBlock(nn.Module):
def __init__(
self,
d_model: int = 512,
head_amount: int = 8,
d_ffn: int = 2048,
d_experts: int = 8,
top_k: int = 2
):
"""
d_model (int): The dimension of the model (embedding dimension size).
head_amount (int): The number of attention heads.
d_ffn (int): The dimension of the FFN used in the transformer block ()
"""
super().__init__()
# Norm -> Attention -> Norm -> FFN 1 -> FFN Func -> FFN 2 -> Out
self.norm1 = nn.LayerNorm(d_model)
self.attention = VanillaMultiHeadAttention(d_model, head_amount)
self.norm2 = nn.LayerNorm(d_model)
# Literally just swap out the original FFN
self.ffn = MoE(
dim_model=d_model,
dim_hidden_layer=d_ffn,
num_experts=d_experts,
top_k=top_k
)
"""
I think in this case it would be more convenient to have aux loss calcuated in the MoE module itself so then
you wouldn't have to make a whole new trainer just for an arch change.
It's also apparently normal practice for MoE modules because it needs the logit and selected expert data while training,
and that's just easier to access internally.
"""
def forward(
self,
x: torch.Tensor,
kv_cache: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
return_aux_loss: bool = False,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]] | tuple[
torch.Tensor, tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""
A forward pass with residual connections.
Norm -> Attention (+ Residual) -> Norm -> FFN 1 -> FFN Func -> FFN 2 (+ Residual) -> Out
x (torch.Tensor): Input tensor
kv_cache (tuple[torch.Tensor, torch.Tensor]): The kv cache.
Should not be passed in as anything but the returned kv cache from a previous forward call.
"""
attention_out, new_kv = self.attention(self.norm1(x), kv_cache)
x = x + attention_out
if return_aux_loss:
ffn_out, aux_loss = self.ffn(self.norm2(x), return_aux_loss=True)
x = x + ffn_out
return x, new_kv, aux_loss
x = x + self.ffn(self.norm2(x), return_aux_loss=False)
return x, new_kv