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:
```
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
```
```
# 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
```
```
# 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
```
```
def compute_metrics(model, eval_iters, get_batch, device='cpu'):
    model.eval()
    total_loss = 0.0
    correct_predictions = 0
    total_tokens = 0

    with torch.no_grad():
        for _ in range(eval_iters):
            inputs, targets = get_batch('val')
            inputs = inputs.to(device)
            targets = targets.to(device)
            
            logits, loss = model(inputs, targets)
            total_loss += loss.item()
            
            # Assuming logits shape: (batch_size, seq_length, vocab_size)
            predictions = torch.argmax(logits.view(-1, logits.size(-1)), dim=-1)
            targets_flat = targets.view(-1)
            
            correct_predictions += (predictions == targets_flat).sum().item()
            total_tokens += targets_flat.numel()

    avg_loss = total_loss / eval_iters
    perplexity = math.exp(avg_loss)
    accuracy = correct_predictions / total_tokens
    return {'perplexity': perplexity, 'accuracy': accuracy}
```