Assess the code below for any infinite loops: [code]
- User
Assess the code below for any infinite loops:
# Imports import math import time import torch import torch.nn as nn import torch.optim as optim from torch.nn import functional as F # Define hyperparameters batch_size = 64 block_size = 256 max_iters = 5001 eval_interval = 500 learning_rate = 3e-4 device = 'cuda' if torch.cuda.is_available() else 'cpu' eval_iters = 200 n_embd = 384 n_head = 6 n_layer = 6 dropout = 0.2 n_clusters = 4 total_experts = 8 # Total number of experts in the global pool weight_decay = 0.1 aux_loss_weight = 0.01 # Set random seed for reproducibility torch.manual_seed(1337) # Load data and define data processing functions with open('input.txt', 'r', encoding='utf-8') as f: text = f.read() # Create a character-level vocabulary chars = sorted(list(set(text))) vocab_size = len(chars) # Create mappings from characters to indices and vice versa stoi = {ch: i for i, ch in enumerate(chars)} itos = {i: ch for i, ch in enumerate(chars)} # Encode and decode functions to convert between text and indices encode = lambda s: [stoi[c] for c in s] decode = lambda l: ''.join([itos[i] for i in l]) # Convert entire text into a tensor of indices data = torch.tensor(encode(text), dtype=torch.long) # Split the data into training and validation sets n = int(0.9 * len(data)) train_data = data[:n] val_data = data[n:] # Function to generate a batch of data for training or validation def get_batch(split): data = train_data if split == 'train' else val_data ix = torch.randint(len(data) - block_size, (batch_size,)) x = torch.stack([data[i:i+block_size] for i in ix]) y = torch.stack([data[i+1:i+block_size+1] for i in ix]) x, y = x.to(device), y.to(device) return x, y # Function to estimate the model's loss on training and validation data @torch.no_grad() def estimate_loss(): out = {} model.eval() # Set model to evaluation mode for split in ['train', 'val']: losses = torch.zeros(eval_iters) for k in range(eval_iters): X, Y = get_batch(split) logits, loss = model(X, Y) losses[k] = loss.item() out[split] = losses.mean() model.train() # Set model back to training mode return out def compute_metrics(model): 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} # Define the ClusteredSwitchFeedForward class with dynamic expert allocation class ClusteredSwitchFeedForward(nn.Module): """ Clustered Mixture-of-Experts (MoE) FeedForward layer with dynamic expert allocation. Each cluster dynamically selects a subset of experts from the global pool. The total number of experts used across all clusters is fixed. """ def __init__(self, top_k=1): super().__init__() self.n_clusters = n_clusters self.total_experts = total_experts self.top_k = top_k # Number of experts selected per cluster # Initialize a global pool of experts self.experts = nn.ModuleList([ nn.Sequential( nn.Linear(n_embd, 4 * n_embd), nn.ReLU(), nn.Linear(4 * n_embd, n_embd), nn.Dropout(dropout) ) for _ in range(self.total_experts) ]) # Gating networks for clusters to assign experts self.cluster_gates = nn.ModuleList([ nn.Linear(n_embd, self.total_experts) for _ in range(self.n_clusters) ]) # Auxiliary parameters for enforcing expert utilization constraints self.register_buffer("expert_usage", torch.zeros(self.total_experts)) def forward(self, x): """ Args: x: Tensor of shape (B, T, D) Returns: output: Tensor of shape (B, T, D) after processing through experts total_aux_loss: Scalar tensor representing the sum of auxiliary losses """ B, T, D = x.shape # Initialize output tensor output = torch.zeros_like(x).to(x.device) # (B, T, D) total_aux_loss = 0.0 # Step 1: Compute gating scores for each cluster cluster_logits = [gate(x) for gate in self.cluster_gates] # List of (B, T, E) cluster_scores = [logit / (self.total_experts ** 0.5) for logit in cluster_logits] # Scale for stability # Step 2: Select Top-K experts per cluster selected_experts_per_cluster = [] selected_probs_per_cluster = [] for cluster_idx in range(self.n_clusters): scores = cluster_scores[cluster_idx] # (B, T, E) topk_scores, topk_indices = torch.topk(scores, self.top_k, dim=-1) # Each of shape (B, T, K) topk_probs = F.softmax(topk_scores, dim=-1) # Normalize scores per cluster selected_experts_per_cluster.append(topk_indices) # List of (B, T, K) selected_probs_per_cluster.append(topk_probs) # List of (B, T, K) # Step 3: Flatten batch and time dimensions x_flat = x.view(B*T, D) # (B*T, D) # Step 4: Combine all selected experts and their probabilities across clusters # Shape after view: (B*T, C*K) all_selected_experts = torch.cat(selected_experts_per_cluster, dim=-1).view(B*T, self.n_clusters * self.top_k) # (B*T, C*K) all_selected_probs = torch.cat(selected_probs_per_cluster, dim=-1).view(B*T, self.n_clusters * self.top_k) # (B*T, C*K) # Shape: (B*T*C*K,) expert_indices = all_selected_experts.view(-1) # (B*T*C*K,) gating_weights = all_selected_probs.view(-1) # (B*T*C*K,) # Remove tokens with zero probability (optional) mask = gating_weights > 0 expert_indices = expert_indices[mask] # (N,) gating_weights = gating_weights[mask].unsqueeze(-1) # (N, 1) # Gather all inputs corresponding to these expert assignments # Repeat x_flat for each selected expert # Indices to gather: (N,) for B*T*C*K selections expert_inputs = x_flat.repeat_interleave(self.n_clusters * self.top_k, dim=0)[mask] # (N, D) # Process all expert inputs in a single batch expert_outputs = torch.cat([self.experts[idx](inp).unsqueeze(0) for idx, inp in zip(expert_indices.tolist(), expert_inputs)], dim=0) # (N, D) # Weight the expert outputs weighted_expert_outputs = expert_outputs * gating_weights # (N, D) # Scatter the weighted outputs back to the output tensor # Compute the original token indices token_indices = torch.arange(B*T, device=x.device).repeat_interleave(self.n_clusters * self.top_k)[mask] # (N,) # Scatter add the weighted outputs to the corresponding tokens output_flat = x_flat.clone() # (B*T, D) output_flat.index_add_(0, token_indices, weighted_expert_outputs) # (B*T, D) output = output_flat.view(B, T, D) # (B, T, D) # Step 5: Auxiliary loss for balanced expert usage # Compute average expert usage across all tokens and clusters # Flatten all_selected_experts to (B*T*C*K,) all_allocations = all_selected_experts.view(-1) # (B*T*C*K,) # Count occurrences of each expert expert_counts = torch.bincount(all_allocations, minlength=self.total_experts).float() # (E,) # Compute ideal usage (B*T*C*K / E) ideal_usage = (B * T * self.n_clusters * self.top_k) / self.total_experts # Compute variance from ideal usage usage_variance = ((expert_counts - ideal_usage) ** 2).mean() # Compute entropy of expert usage distribution usage_distribution = expert_counts / (B * T * self.n_clusters * self.top_k + 1e-10) entropy = -torch.sum(usage_distribution * torch.log(usage_distribution + 1e-10)) # Total auxiliary loss combines usage variance and entropy total_aux_loss = aux_loss_weight * (usage_variance + entropy) return output, total_aux_loss # Define the Head class (unchanged) 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): B, T, C = x.shape k = self.key(x) # (B, T, head_size) q = self.query(x) # (B, T, head_size) wei = q @ k.transpose(-2, -1) * C**-0.5 # (B, T, T) wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # Apply causal mask wei = F.softmax(wei, dim=-1) # (B, T, T) wei = self.dropout(wei) v = self.value(x) # (B, T, head_size) out = wei @ v # (B, T, head_size) return out # Define the MultiHeadAttention class (unchanged) 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) # Concatenate all heads out = self.dropout(self.proj(out)) return out # Define the modified Block_ClusteredSwitch class class Block_ClusteredSwitch(nn.Module): """Transformer block with Clustered Mixture-of-Experts FeedForward layer.""" def __init__(self): super().__init__() self.ln1 = nn.LayerNorm(n_embd) self.ln2 = nn.LayerNorm(n_embd) self.sa = MultiHeadAttention(n_head, head_size=n_embd // n_head) self.ffwd = ClusteredSwitchFeedForward(top_k=1) # Adjust top_k as needed def forward(self, x): # Self-Attention with residual connection x = x + self.sa(self.ln1(x)) # (B, T, D) # Clustered MoE FeedForward with auxiliary loss ffwd_out, loss_aux = self.ffwd(self.ln2(x)) # (B, T, D), scalar # FeedForward with residual connection x = x + ffwd_out # (B, T, D) # Return updated tensor and auxiliary loss return x, loss_aux # Define the modified Clustered_ST class class Clustered_ST(nn.Module): """Clustered Switch Transformer with Dynamic Mixture-of-Experts.""" def __init__(self): 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_ClusteredSwitch() for _ in range(n_layer)]) self.ln_f = nn.LayerNorm(n_embd) # Final layer norm self.lm_head = nn.Linear(n_embd, vocab_size) self.apply(self._init_weights) def _init_weights(self, module): """Initialize weights with normal distribution.""" 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) # (B, T, n_embd) pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T, n_embd) x = tok_emb + pos_emb # (B, T, n_embd) aux_loss = 0.0 for block in self.blocks: x, loss_aux = block(x) aux_loss += loss_aux # Accumulate auxiliary loss x = self.ln_f(x) # (B, T, n_embd) 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) + aux_loss_weight * aux_loss # Total loss with auxiliary term 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, :] # Focus on the last time step probs = F.softmax(logits, dim=-1) # Convert to probabilities idx_next = torch.multinomial(probs, num_samples=1) # Sample the next token idx = torch.cat((idx, idx_next), dim=1) # Append to the sequence return idx # Initialize the model and optimizer model = Clustered_ST().to(device) # print the number of parameters in the model print(sum(p.numel() for p in model.parameters())/1e6, 'M parameters') optimizer = optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay) # AdamW optimizer with weight decay start_time = time.time() for iter in range(max_iters): if iter % eval_interval == 0: losses = estimate_loss() print(f"Step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}") xb, yb = get_batch('train') logits, loss = model(xb, yb) optimizer.zero_grad(set_to_none=True) loss.backward() optimizer.step() metrics = compute_metrics(model) end_time = time.time() elapsed_time = end_time - start_time print("Training completed.") print("Elapsed time:", elapsed_time, "seconds") print("Perplexity:", metrics['perplexity']) print("Accuracy:", metrics['accuracy']) - Assistant