Mixture Of Experts Architecture with PyTorch & ONNX Pt. 1: The Model | ML Engineering & MLOps
Hi All
Mixture of Experts is a ML technique where multiple expert networks (learners) are used to divide a problem space into homogeneous regions. MoE represents a form of ensemble learning. They were also called committee machines.
Both the experts and the weighting function are trained by minimizing some loss function, generally via gradient descent. There is much freedom in choosing the precise form of experts, the weighting function, and the loss function.
This model uses BERT's transformer architecture as the base (BERT LARGE around 350M params), and implements a Mixture of Experts architecture with 8 experts by default.
The model.py source and architecture detailed below. The full PyTorch, ONNX MoE application source code can be found here.
1. Expert Network (`Expert` class)
class Expert(nn.Module):
"""A single expert network (feed-forward network)"""
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.1):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, output_dim),
nn.Dropout(dropout)
)
def forward(self, x):
return self.net(x)
Defines a single expert (a small feed-forward network)
Components:
* `nn.Linear` layers: Two linear transformations with a GELU activation in between.
* Dropout: Applied after each linear layer for regularization.
* Forward pass: Simple sequential execution of the network.
2. Mixture of Experts Layer (`MoE` class)
class MoE(nn.Module):
"""Mixture of Experts layer"""
def __init__(self, num_experts, input_dim, expert_hidden_dim, expert_output_dim,
top_k=2, noisy_gating=True, dropout=0.1):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
self.noisy_gating = noisy_gating
# Experts
self.experts = nn.ModuleList([
Expert(input_dim, expert_hidden_dim, expert_output_dim, dropout)
for _ in range(num_experts)
])
# Gating network
self.gate = nn.Linear(input_dim, num_experts)
if noisy_gating:
self.w_noise = nn.Linear(input_dim, num_experts)
self.w_gate = nn.Linear(input_dim, num_experts)
# Initialization
self.reset_parameters()
def reset_parameters(self):
for expert in self.experts:
nn.init.xavier_uniform_(expert.net[0].weight)
nn.init.xavier_uniform_(expert.net[3].weight)
nn.init.xavier_uniform_(self.gate.weight)
if self.noisy_gating:
nn.init.xavier_uniform_(self.w_noise.weight)
nn.init.xavier_uniform_(self.w_gate.weight)
Implements the core MOE logic with gating and export selction.
Components:
* Experts: A list of `Expert` instances (initialized in `nn.ModuleList`)
* Gating Network: A linear layer (`self.gate`) that computes weights for each expert.
* Noisy Gating: Adds noise to the gating logits during training for better load balancing (this is optional)
* Initialization: Uses Xavier uniform initialization for stable training.
3. Noisy Top-K Gating (noisy_top_k_gating method)
def noisy_top_k_gating(self, x, train=True):
"""Noisy top-k gating as described in the paper"""
clean_logits = self.gate(x)
if train:
raw_noise = torch.randn_like(clean_logits)
noise = self.w_noise(x) * raw_noise
noisy_logits = clean_logits + noise
else:
noisy_logits = clean_logits
# Softmax to get probabilities
probs = F.softmax(noisy_logits, dim=-1)
# Top-k
top_k_probs, top_k_indices = probs.topk(self.top_k, dim=-1)
top_k_gates = top_k_probs
# Normalize
top_k_gates = top_k_gates / top_k_gates.sum(dim=-1, keepdim=True)
# Expert indices
expert_indices = top_k_indices
return top_k_gates, expert_indices
Implements the gating mechanism to select th etop-k experts.
Key Steps:
* Noisy Gating: Adds Gaussian noise to logits during training (improves load balancing).
* Softmax: Converts logits to probabilities.
* Top-K Selection: Selects the top-k experts based on probabilities.
* Normalization: Ensures the selected gates sum to 1.
4. Forward Pass (`forward` method)
def forward(self, x):
if self.top_k == 1:
# Simple case - just use one expert
expert_outputs = torch.stack([expert(x) for expert in self.experts], dim=1)
expert_output = expert_outputs[:, 0, :]
return expert_output
else:
# Noisy top-k gating
gates, expert_indices = self.noisy_top_k_gating(x)
# Expert outputs
expert_outputs = torch.stack([expert(x) for expert in self.experts], dim=1)
# Select experts based on indices
selected_experts = expert_outputs.gather(
1,
expert_indices.unsqueeze(-1).expand(-1, -1, expert_outputs.size(-1))
)
# Weight outputs by gates
output = (gates.unsqueeze(-1) * selected_experts).sum(dim=1)
return output
Computes the final output by combining expert best expert outputs.
* Top-1 Routing: if `top_k=1`, selects the single best expert.
* Top-K Routing: For `top_k>1`, selects the top-k experts and combines their outputs weighted by gating probabilities.
* Gather Operation: Efficiently selects the outputs of the chosen experts.
5. BERT MoE Model (`BertMoE` class)
class BertMoE(nn.Module):
"""BERT-based Mixture of Experts model"""
def __init__(self, config):
super().__init__()
self.config = config
# BERT encoder
self.bert = BertModel(config)
# MOE layer
self.moe = MoE(
num_experts=config.num_experts,
input_dim=config.hidden_size,
expert_hidden_dim=config.moe_expert_hidden_size,
expert_output_dim=config.hidden_size,
top_k=config.moe_top_k,
noisy_gating=config.moe_noisy_gating,
dropout=config.hidden_dropout_prob
)
# Output layer
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, input_ids, attention_mask=None, token_type_ids=None, labels=None):
# BERT encoder
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
sequence_output = outputs.last_hidden_state
# MOE layer (applied to each token)
moe_output = self.moe(sequence_output)
# Pooling (CLS token)
pooled_output = moe_output[:, 0, :]
# Classifier
logits = self.classifier(pooled_output)
return logits
Combines BERT with the MOE layer for a full model.
Components:
* BERT Encoder: Uses HuggingFace's `BertModel` for transformer-based feature extraction.
* MOE Layer: Applies the MOE logic the BERT outputs.
* Classifier: A linear layer for task-specific predictions (eg. classification)
6. Configuration (`BertMoEConfig` class)
class BertMoEConfig:
def __init__(self):
# BERT base configuration
self.vocab_size = 30522
self.hidden_size = 768
self.num_hidden_layers = 12
self.num_attention_heads = 12
self.intermediate_size = 3072
self.hidden_act = "gelu"
self.hidden_dropout_prob = 0.1
self.attention_probs_dropout_prob = 0.1
self.max_position_embeddings = 512
self.type_vocab_size = 2
self.initializer_range = 0.02
self.layer_norm_eps = 1e-12
# MOE specific
self.num_experts = 8
self.moe_expert_hidden_size = 3072
self.moe_top_k = 2
self.moe_noisy_gating = True
# Task specific
self.num_labels = 2
Defines hyperparameters for the model.
Parameters:
* BERT Config: Standard BERT hyperparameters (hidden size, layers, etc.)
* MOE Config: Number of experts, expert hidden size, top-k routing, etc.
*Task Config: Number of output labels (eg. for classification).
7. Model Initialization and Example Usage
# Create model
config = BertMoEConfig()
model = BertMoE(config)
# Example input
input_ids = torch.randint(0, config.vocab_size, (2, 128)) # batch_size=2, seq_len=128
attention_mask = torch.ones_like(input_ids)
token_type_ids = torch.zeros_like(input_ids)
# Forward pass
outputs = model(input_ids, attention_mask)
print("Model output shape:", outputs.shape)
Demonstrates how to initialize and use the model.
* Initialize Model: Creates a `BertMoE` instance with the givven config.
* Dummy Input: Generates random input tensors for testing.
* Forward Pass: Computes the model's output.
8. ONNX Export
# Export to ONNX
dummy_input = {
"input_ids": torch.zeros((1, 128), dtype=torch.long),
"attention_mask": torch.ones((1, 128), dtype=torch.long),
"token_type_ids": torch.zeros((1, 128), dtype=torch.long)
}
torch.onnx.export(
model,
(dummy_input["input_ids"], dummy_input["attention_mask"], dummy_input["token_type_ids"]),
"bert_moe.onnx",
input_names=["input_ids", "attention_mask", "token_type_ids"],
output_names=["output"],
dynamic_axes={
"input_ids": {0: "batch_size", 1: "sequence_length"},
"attention_mask": {0: "batch_size", 1: "sequence_length"},
"token_type_ids": {0: "batch_size", 1: "sequence_length"},
"output": {0: "batch_size"}
},
opset_version=13
)
print("Model exported to ONNX format")
Key Steps:
* Dummy Input: Defines a sample input for tracing.
* `torch.onnx.export`: Exports the model with dynamic axes for variable-length inputs.
* Outputs: Saves the model as `bert_moe.onnx`
Summary of Flow
1. Input --> BERT encoder --> MOE layer --> Classifier --> Output
2. MOE Layer: Experts process inputs, gating network selects top-k experts and outputs are combined.
3. ONNX Export: Model is converted to ONNX for deployment.
Moving an MoE architecture from PyTorch training to ONNX deployment is a critical step in operationalizing sparse models. While the routing logic introduces unique challenges, the resulting ONNX graph enables significant optimizations in memory bandwidth and throughput.
As the industry moves toward larger, more specialized models, mastering this deployment path ensures you can deliver state-of-the-art performance without sacrificing the stability and speed required for real-world applications. Please find the full source available here and stay tuned for part two where we'll deploy this model on k8s and GKE.
Later
- Ed (lightspeed001)

.png)
.png)
Comments
Post a Comment