I would like to compare three different models, however I would like to ensure the core are the same for fairness. Assume hyperparameters are same:
code
Assistant
class Head(nn.Module):
""" one head of self-attention """
def __init__(self, head_size):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# input of size (batch, time-step, channels)
# output of size (batch, time-step, head size)
B,T,C = x.shape
k = self.key(x) # (B,T,hs)
q = self.query(x) # (B,T,hs)
# compute attention scores ("affinities")
wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
wei = F.softmax(wei, dim=-1) # (B, T, T)
wei = self.dropout(wei)
# perform the weighted aggregation of the values
v = self.value(x) # (B,T,hs)
out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
return out
class MultiHeadAttention(nn.Module):
""" multiple heads of self-attention in parallel """
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(head_size * num_heads, n_embd)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out
class FeedFoward(nn.Module):
""" a simple linear layer followed by a non-linearity """
def __init__(self, n_embd):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)
class Block(nn.Module):
""" Transformer block: communication followed by computation """
def __init__(self, n_embd, n_head):
# n_embd: embedding dimension, n_head: the number of heads we'd like
super().__init__()
head_size = n_embd // n_head
self.sa = MultiHeadAttention(n_head, head_size)
self.ffwd = FeedFoward(n_embd)
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.sa(self.ln1(x))
x = x + self.ffwd(self.ln2(x))
return x
class GPTLanguageModel(nn.Module):
def __init__(self):
super().__init__()
# each token directly reads off the logits for the next token from a lookup table
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
self.position_embedding_table = nn.Embedding(block_size, n_embd)
self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd) # final layer norm
self.lm_head = nn.Linear(n_embd, vocab_size)
# better init, not covered in the original GPT video, but important, will cover in followup video
self.apply(self._init_weights)
def _init_weights(self, module):
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, idx, targets=None):
B, T = idx.shape
# idx and targets are both (B,T) tensor of integers
tok_emb = self.token_embedding_table(idx) # (B,T,C)
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
x = tok_emb + pos_emb # (B,T,C)
x = self.blocks(x) # (B,T,C)
x = self.ln_f(x) # (B,T,C)
logits = self.lm_head(x) # (B,T,vocab_size)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets)
return logits, loss
def generate(self, idx, max_new_tokens):
# idx is (B, T) array of indices in the current context
for _ in range(max_new_tokens):
# crop idx to the last block_size tokens
idx_cond = idx[:, -block_size:]
# get the predictions
logits, loss = self(idx_cond)
# focus only on the last time step
logits = logits[:, -1, :] # becomes (B, C)
# apply softmax to get probabilities
probs = F.softmax(logits, dim=-1) # (B, C)
# sample from the distribution
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
# append sampled index to the running sequence
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
return idx
code
# Define the SwitchFeedForward layer (Mixture of Experts)
class SwitchFeedForward(nn.Module):
def __init__(self, n_experts, d_model, d_ff):
super(SwitchFeedForward, self).__init__()
# Create a list of expert networks, each a simple feedforward network
self.experts = nn.ModuleList([nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Linear(d_ff, d_model),
) for _ in range(n_experts)])
# Gate network to decide which expert to use
self.gate = nn.Linear(d_model, n_experts)
def forward(self, x):
gate_values = self.gate(x) # Get gating values for each token
top1_expert = torch.argmax(gate_values, dim=-1) # Choose the top expert for each token
loss_aux = F.cross_entropy(gate_values.view(-1, gate_values.size(-1)), top1_expert.view(-1)) # Auxiliary loss from gating
output = torch.zeros_like(x)
# Route each token to its chosen expert
for i, expert in enumerate(self.experts):
mask = top1_expert == i
if mask.sum() > 0:
output[mask] = expert(x[mask])
return output, loss_aux
# Define a single attention head
class Head(nn.Module):
def __init__(self, head_size):
super().__init__()
# Linear layers to compute key, query, and value vectors
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size))) # Lower triangular mask for causal attention
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
k = self.key(x) # Compute keys
q = self.query(x) # Compute queries
wei = q @ k.transpose(-2, -1) * C**-0.5 # Compute attention scores
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # Apply causal mask
wei = F.softmax(wei, dim=-1) # Normalize attention scores
wei = self.dropout(wei)
v = self.value(x) # Compute values
out = wei @ v # Weighted sum of values
return out
# Define multi-head attention
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(n_embd, n_embd) # Linear layer to project concatenated output
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1) # Concatenate outputs of all heads
out = self.dropout(self.proj(out)) # Apply final linear projection and dropout
return out
# Define a transformer block
class Block(nn.Module):
def __init__(self, n_embd, n_head, n_experts, d_ff):
super().__init__()
head_size = n_embd // n_head # Size of each attention head
self.sa = MultiHeadAttention(n_head, head_size) # Multi-head self-attention
self.ffwd = SwitchFeedForward(n_experts, n_embd, d_ff) # Mixture of Experts feedforward network
self.ln1 = nn.LayerNorm(n_embd) # Layer normalization
self.ln2 = nn.LayerNorm(n_embd) # Layer normalization
def forward(self, x):
x = x + self.sa(self.ln1(x)) # Apply self-attention with residual connection
ffwd_out, loss_aux = self.ffwd(self.ln2(x)) # Apply feedforward network
x = x + ffwd_out # Residual connection
return x, loss_aux # Return output and auxiliary loss
# Define the Switch Transformer model
class SwitchTransformer(nn.Module):
def __init__(self):
super().__init__()
self.token_embedding_table = nn.Embedding(vocab_size, n_embd) # Embedding layer for token embeddings
self.position_embedding_table = nn.Embedding(block_size, n_embd) # Embedding layer for positional embeddings
self.blocks = nn.ModuleList([Block(n_embd, n_head, n_experts, 4 * n_embd) for _ in range(n_layer)]) # Stacked transformer blocks
self.ln_f = nn.LayerNorm(n_embd) # Final layer normalization
self.lm_head = nn.Linear(n_embd, vocab_size) # Linear layer to map to vocabulary size
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx) # Get token embeddings
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # Get positional embeddings
x = tok_emb + pos_emb # Combine token and positional embeddings
aux_loss = 0.0
for block in self.blocks:
x, loss_aux = block(x) # Pass through each transformer block
aux_loss += loss_aux # Accumulate auxiliary loss
x = self.ln_f(x) # Apply final layer normalization
logits = self.lm_head(x) # Compute logits for each token
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets) + aux_loss_weight * aux_loss # Compute loss with auxiliary loss
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:] # Get last block_size tokens
logits, loss = self(idx_cond) # Forward pass
logits = logits[:, -1, :] # Get logits for the last token
probs = F.softmax(logits, dim=-1) # Convert logits to probabilities
idx_next = torch.multinomial(probs, num_samples=1) # Sample the next token
idx = torch.cat((idx, idx_next), dim=1) # Append the next token to the sequence
return idx
code
# Define Clustered SwitchFeedForward layer
class ClusteredSwitchFeedForward(nn.Module):
def __init__(self, n_clusters, experts_per_cluster, d_model, d_ff):
super(ClusteredSwitchFeedForward, self).__init__()
self.n_clusters = n_clusters
self.experts_per_cluster = experts_per_cluster
self.experts = nn.ModuleList([
nn.ModuleList([nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Linear(d_ff, d_model),
) for _ in range(experts_per_cluster)])
for _ in range(n_clusters)
])
self.cluster_gate = nn.Linear(d_model, n_clusters)
self.expert_gate = nn.ModuleList([
nn.Linear(d_model, experts_per_cluster) for _ in range(n_clusters)
])
def forward(self, x):
cluster_logits = self.cluster_gate(x) # Shape: (B, T, n_clusters)
cluster_probs = F.softmax(cluster_logits, dim=-1) # Shape: (B, T, n_clusters)
cluster_loss_aux = F.cross_entropy(
cluster_logits.view(-1, cluster_logits.size(-1)),
torch.argmax(cluster_logits, dim=-1).view(-1)
)
output = torch.zeros_like(x) # Shape: (B, T, D)
expert_loss_aux = 0.0
for cluster_idx in range(self.n_clusters):
cluster_mask = cluster_probs[..., cluster_idx] > 0
cluster_output = torch.zeros_like(x) # Shape: (B, T, D)
if cluster_mask.any():
cluster_experts = self.experts[cluster_idx]
expert_logits = self.expert_gate[cluster_idx](x[cluster_mask]) # Shape: (N, experts_per_cluster)
expert_probs = F.softmax(expert_logits, dim=-1).unsqueeze(-1) # Shape: (N, experts_per_cluster, 1)
expert_loss_aux += F.cross_entropy(
expert_logits.view(-1, expert_logits.size(-1)),
torch.argmax(expert_logits, dim=-1).view(-1)
)
for expert_idx, expert in enumerate(cluster_experts):
expert_output = expert(x[cluster_mask]) # Shape: (N, D)
cluster_output[cluster_mask] += expert_probs[:, expert_idx] * expert_output # Broadcasting over D
# Correctly compute cluster weights for masked positions
cluster_weight = cluster_probs[..., cluster_idx] # Shape: (B, T)
cluster_weight_selected = cluster_weight[cluster_mask].unsqueeze(-1) # Shape: (N, 1)
output[cluster_mask] += cluster_weight_selected * cluster_output[cluster_mask]
total_aux_loss = cluster_loss_aux + expert_loss_aux
return output, total_aux_loss
# Define a single attention head
class Head(nn.Module):
def __init__(self, head_size):
super().__init__()
# Linear layers to compute key, query, and value vectors
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size))) # Lower triangular mask for causal attention
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
k = self.key(x) # Compute keys
q = self.query(x) # Compute queries
wei = q @ k.transpose(-2, -1) * C**-0.5 # Compute attention scores
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # Apply causal mask
wei = F.softmax(wei, dim=-1) # Normalize attention scores
wei = self.dropout(wei)
v = self.value(x) # Compute values
out = wei @ v # Weighted sum of values
return out
# Define multi-head attention
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(n_embd, n_embd) # Linear layer to project concatenated output
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1) # Concatenate outputs of all heads
out = self.dropout(self.proj(out)) # Apply final linear projection and dropout
return out
# Define a transformer block
class Block(nn.Module):
def __init__(self, n_embd, n_head, n_clusters, experts_per_cluster, d_ff):
super().__init__()
head_size = n_embd // n_head
self.sa = MultiHeadAttention(n_head, head_size)
self.ffwd = ClusteredSwitchFeedForward(n_clusters, experts_per_cluster, n_embd, d_ff)
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.sa(self.ln1(x))
ffwd_out, loss_aux = self.ffwd(self.ln2(x))
x = x + ffwd_out
return x, loss_aux
# Define the Clustered Experts Switch Transformer model
class Clustered_ST(nn.Module):
def __init__(self, n_clusters, experts_per_cluster):
super().__init__()
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
self.position_embedding_table = nn.Embedding(block_size, n_embd)
self.blocks = nn.ModuleList([Block(n_embd, n_head, n_clusters, experts_per_cluster, 4 * n_embd) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd)
self.lm_head = nn.Linear(n_embd, vocab_size)
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(torch.arange(T, device=device))
x = tok_emb + pos_emb
aux_loss = 0.0
for block in self.blocks:
x, loss_aux = block(x)
aux_loss += loss_aux
x = self.ln_f(x)
logits = self.lm_head(x)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets) + aux_loss_weight * aux_loss
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
return idx
To compare the three different Transformer-based models you've provided—GPTLanguageModel, SwitchTransformer, and Clustered_ST—while ensuring fairness and consistency across their cores, follow these comprehensive steps:
Ensure Consistent Core Components
Standardize Hyperparameters and Initialization
Implement Training and Evaluation Pipelines
Compare Performance Metrics
Below is a detailed guide for each step, including code snippets to help you set up a fair comparison.
1. Ensure Consistent Core Components
All three models share a common architecture with differences primarily in the feedforward layers. To maintain fairness:
Shared Components: Token embeddings, positional embeddings, multi-head self-attention, layer normalization, and output heads should be identical across models.
Differing Components: The feedforward layers—standard FeedFoward, SwitchFeedForward, and ClusteredSwitchFeedForward.
Action Steps:
Base Transformer Block: Create a base TransformerBlock class that includes shared components.
Modular FeedForward Layers: Allow the feedforward layer to be injected, enabling easy swapping between standard and Mixture-of-Experts (MoE) layers.
Example Implementation
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.utils.data import DataLoader
import random
# Set a fixed random seed for reproducibility
def set_seed(seed):
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
set_seed(42)
# Shared Base Classes
class Head(nn.Module):
"""One head of self-attention."""
def __init__(self, head_size, n_embd, block_size, dropout):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
k = self.key(x) # (B, T, hs)
q = self.query(x) # (B, T, hs)
wei = q @ k.transpose(-2, -1) * C**-0.5 # (B, T, T)
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # Causal Mask
wei = F.softmax(wei, dim=-1)
wei = self.dropout(wei)
v = self.value(x) # (B, T, hs)
out = wei @ v # (B, T, hs)
return out
class MultiHeadAttention(nn.Module):
"""Multiple heads of self-attention in parallel."""
def __init__(self, num_heads, head_size, n_embd, dropout):
super().__init__()
self.heads = nn.ModuleList([Head(head_size, n_embd, block_size=512, dropout=dropout) for _ in range(num_heads)])
self.proj = nn.Linear(head_size * num_heads, n_embd)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out
class FeedForward(nn.Module):
"""A simple linear layer followed by a non-linearity."""
def __init__(self, n_embd, dropout):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)
class TransformerBlock(nn.Module):
"""Transformer block: communication followed by computation."""
def __init__(self, n_embd, n_head, feedforward_layer, dropout):
super().__init__()
head_size = n_embd // n_head
self.attention = MultiHeadAttention(n_head, head_size, n_embd, dropout)
self.ffwd = feedforward_layer
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.attention(self.ln1(x))
x = x + self.ffwd(self.ln2(x))
return x
2. Standardize Hyperparameters and Initialization
To ensure fairness:
Hyperparameters: Use identical values for embedding size (n_embd), number of layers (n_layer), number of heads (n_head), dropout rates, etc.
Initialization: Apply the same weight initialization across all models.
Action Steps:
Define a configuration object or dictionary to store hyperparameters.
Modify each model to accept the configuration and pass shared parameters accordingly.
Ensure all models use the same _init_weights method.
Example Implementation
python
# Configuration
class Config:
vocab_size = 30522 # Example vocab size
block_size = 512
n_embd = 768
n_layer = 12
n_head = 12
dropout = 0.1
device = 'cuda' if torch.cuda.is_available() else 'cpu'
aux_loss_weight = 1.0
n_experts = 4 # Example value
n_clusters = 2 # Example value
experts_per_cluster = 2 # Example value
config = Config()
# Base GPT Model
class GPTLanguageModel(nn.Module):
def __init__(self, config):
super().__init__()
self.token_embedding_table = nn.Embedding(config.vocab_size, config.n_embd)
self.position_embedding_table = nn.Embedding(config.block_size, config.n_embd)
self.blocks = nn.Sequential(*[
TransformerBlock(
n_embd=config.n_embd,
n_head=config.n_head,
feedforward_layer=FeedForward(config.n_embd, config.dropout),
dropout=config.dropout
) for _ in range(config.n_layer)
])
self.ln_f = nn.LayerNorm(config.n_embd)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
self.apply(self._init_weights)
def _init_weights(self, module):
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(torch.arange(T, device=config.device))
x = tok_emb + pos_emb
x = self.blocks(x)
x = self.ln_f(x)
logits = self.lm_head(x)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets)
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -config.block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
return idx
3. Implement the Mixture-of-Experts (MoE) Layers
a. SwitchTransformer: SwitchFeedForward
This model replaces the standard feedforward layer with a SwitchFeedForward that routes tokens to different experts based on gating.
4. Define Models with Different FeedForward Layers
a. SwitchTransformer Model
python
class SwitchTransformer(nn.Module):
def __init__(self, config):
super().__init__()
self.token_embedding_table = nn.Embedding(config.vocab_size, config.n_embd)
self.position_embedding_table = nn.Embedding(config.block_size, config.n_embd)
self.blocks = nn.Sequential(*[
TransformerBlock(
n_embd=config.n_embd,
n_head=config.n_head,
feedforward_layer=SwitchFeedForward(
n_experts=config.n_experts,
d_model=config.n_embd,
d_ff=4 * config.n_embd,
dropout=config.dropout
),
dropout=config.dropout
) for _ in range(config.n_layer)
])
self.ln_f = nn.LayerNorm(config.n_embd)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
self.apply(self._init_weights)
def _init_weights(self, module):
# Same as GPTLanguageModel
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(torch.arange(T, device=config.device))
x = tok_emb + pos_emb
aux_loss = 0.0
for block in self.blocks:
x, loss_aux = block(x)
aux_loss += loss_aux
x = self.ln_f(x)
logits = self.lm_head(x)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets) + config.aux_loss_weight * aux_loss
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -config.block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
return idx
b. Clustered Switch Transformer (Clustered_ST) Model
python
class Clustered_ST(nn.Module):
def __init__(self, config):
super().__init__()
self.token_embedding_table = nn.Embedding(config.vocab_size, config.n_embd)
self.position_embedding_table = nn.Embedding(config.block_size, config.n_embd)
self.blocks = nn.Sequential(*[
TransformerBlock(
n_embd=config.n_embd,
n_head=config.n_head,
feedforward_layer=ClusteredSwitchFeedForward(
n_clusters=config.n_clusters,
experts_per_cluster=config.experts_per_cluster,
d_model=config.n_embd,
d_ff=4 * config.n_embd,
dropout=config.dropout
),
dropout=config.dropout
) for _ in range(config.n_layer)
])
self.ln_f = nn.LayerNorm(config.n_embd)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
self.apply(self._init_weights)
def _init_weights(self, module):
# Same as GPTLanguageModel
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(torch.arange(T, device=config.device))
x = tok_emb + pos_emb
aux_loss = 0.0
for block in self.blocks:
x, loss_aux = block(x)
aux_loss += loss_aux
x = self.ln_f(x)
logits = self.lm_head(x)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets) + config.aux_loss_weight * aux_loss
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -config.block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
return idx
5. Training and Evaluation Pipeline
a. Data Preparation
Ensure all models are trained and evaluated on the same dataset splits.
python
# Placeholder for data loading
def get_batch(split):
# Implement your data loading logic here
# Return a tuple (inputs, targets)
# Both should be tensors of shape (batch_size, block_size)
pass
b. Compute Metrics
Use the provided compute_metrics function to evaluate perplexity and accuracy.
Random Seed: Initialize all models with the same random seed to ensure similar weight initialization.
python
set_seed(42)
Data Shuffling: Ensure that data is shuffled identically across all models if shuffling is part of your data loader.
Batch Size: Use the same batch size for all models to ensure consistent memory usage and gradient updates.
Optimizer State: Initialize optimizers in the same state if required, although minor differences might occur due to architecture changes.
Hardware: Train all models on the same hardware to avoid performance biases.
Auxiliary Loss Weight: Ensure aux_loss_weight is set consistently across all models that utilize auxiliary losses.
8. Analyzing Results
After training and evaluation, analyze the performance metrics to compare:
Perplexity: Lower perplexity indicates better language modeling performance.
Accuracy: Higher accuracy denotes better prediction of the next token.
Training Time: Compare the computational efficiency and resources consumed by each model.
Auxiliary Loss: For MoE models, monitor auxiliary losses to ensure proper gating.
Example Analysis
python
def analyze_results(gpt_metrics, switch_metrics, clustered_switch_metrics):
print("=== Model Comparison ===")
print(f"{'Model':<20} {'Perplexity':<15} {'Accuracy':<10}")
print(f"{'-'*45}")
print(f"{'GPTLanguageModel':<20} {gpt_metrics['perplexity']:<15.4f} {gpt_metrics['accuracy']:<10.4f}")
print(f"{'SwitchTransformer':<20} {switch_metrics['perplexity']:<15.4f} {switch_metrics['accuracy']:<10.4f}")
print(f"{'Clustered_ST':<20} {clustered_switch_metrics['perplexity']:<15.4f} {clustered_switch_metrics['accuracy']:<10.4f}")
# Further analysis can include plotting, statistical significance tests, etc.
9. Additional Recommendations
Logging: Use logging libraries like TensorBoard or Weights & Biases to visualize training progress.
python
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir='runs/model_comparison')
# During training
writer.add_scalar('Loss/GPT', gpt_loss, epoch)
writer.add_scalar('Loss/Switch', switch_loss, epoch)
writer.add_scalar('Loss/Clustered_ST', clustered_switch_loss, epoch)
Validation Frequency: Decide how often to evaluate on the validation set to balance between training speed and monitoring.
Early Stopping: Implement early stopping based on validation metrics to prevent overfitting.
Hyperparameter Tuning: While hyperparameters are kept the same for fairness, consider running separate hyperparameter tuning for each model for optimal performance individually.
Resource Allocation: MoE models can be resource-intensive; ensure your hardware can handle the additional computational requirements.
By following this structured approach, you'll ensure a fair and comprehensive comparison of the three models, allowing you to evaluate the impact of incorporating Mixture-of-Experts and clustering mechanisms into the Transformer architecture.
Let me know if you need further assistance with specific parts of the implementation or have additional questions!