Don't reply: import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
from collections import Counter
import json
from tqdm import tqdm
import math
def forward(self, x):
# Assuming x is of shape [batch_size, seq_len, d_model] you may want to aggregate
# across the sequence length dimension before the gating network
x = x.mean(dim=1) # Take mean or another operation that reduces seq_len dimension
x = self.fc(x) # Now the shape of x should match the weight matrix of the fc layer
return self.softmax(x)
It looks like you've provided a comprehensive and detailed Python code that defines a machine learning architecture for a Mixture of Experts (MoE) using Transformers, specifically designed for a question-answering task. The code includes parts for data preparation, model definition, training, and text generation.
Here's a summary of what each main part of the code does:
User
I get this error: Total trainable parameters: 8897328
Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-Transformer_Q&A.py", line 231, in
train_model(moe_transformer_model, criterion, optimizer, num_epochs, data_loader)
File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-Transformer_Q&A.py", line 154, in train_model
loss = criterion(predictions.view(-1, predictions.size(-1)), targets.view(-1))
File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\loss.py", line 1179, in forward
return F.cross_entropy(input, target, weight=self.weight,
File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\functional.py", line 3053, in cross_entropy
return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
ValueError: Expected input batch_size (128) to match target batch_size (8192).
class QAJsonlDataset(Dataset):
def init(self, path, seq_len):
self.seq_len = seq_len
self.pairs = self.load_data(path)
# Flatten the pairs completely before passing them to build_vocab
self.vocab, self.idx2token = self.build_vocab([word for pair in self.pairs for sublist in pair for word in sublist])
self.tokenized_pairs = [(self.tokenize(q), self.tokenize(a)) for q, a in self.pairs]
code
def load_data(self, path):
pairs = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
data = json.loads(line.strip())
question, answer = data.get("question", ""), data.get("answer", "")
pairs.append((question.split(), answer.split()))
return pairs
def tokenize(self, words):
# Tokenize a sentence and pad if necessary
# Add <eos> token at the end if there’s room
tokens = [self.vocab.get(w, self.vocab["<unk>"]) for w in words]
if len(tokens) < self.seq_len:
tokens.append(self.vocab["<eos>"]) # Add <eos> token
tokens.extend([self.vocab["<pad>"]] * (self.seq_len - len(tokens))) # Pad the rest
else:
tokens = tokens[:self.seq_len - 1] + [self.vocab["<eos>"]]
return tokens
def build_vocab(self, words):
# Start with special tokens with fixed indices
vocab = {"<unk>": 0, "<pad>": 1, "<eos>": 2}
start_index = len(vocab)
# Use Counter to count word frequencies in the corpus
counts = Counter(words)
# Create the vocab dictionary with all words, starting indices after the special tokens
for word, _ in counts.most_common():
if word not in vocab: # Skip special tokens
vocab[word] = len(vocab)
# Create the reverse mapping from indices to words
idx2token = {idx: token for token, idx in vocab.items()}
return vocab, idx2token
def __len__(self):
return len(self.tokenized_pairs)
def __getitem__(self, idx):
tokenized_question, tokenized_answer = self.tokenized_pairs[idx]
return torch.tensor(tokenized_question, dtype=torch.long), torch.tensor(tokenized_answer, dtype=torch.long)
Training loop - added gradient clipping to avoid exploding gradients
def train_model(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
progress_bar = tqdm(enumerate(data_loader), total=len(data_loader), desc=f"Epoch {epoch+1}", leave=False)
for i, (inputs, targets) in progress_bar:
optimizer.zero_grad()
predictions = model(inputs)
loss = criterion(predictions.view(-1, predictions.size(-1)), targets.view(-1))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # Gradient clipping
optimizer.step()
total_loss += loss.item()
progress_bar.set_postfix({"Loss": loss.item()})
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, Average Loss: {average_loss}")
def generate_text(model, dataset, seed_text, num_generate, temperature=1.0):
model.eval() # Put the model in evaluation mode
code
# List to store the generated tokens
generated_tokens = []
# Initial sequence (prefix) to start the generation process
input_sequence = [dataset.vocab.get(word, dataset.vocab["<pad>"]) for word in seed_text.split()] # Convert to token IDs
current_sequence = torch.tensor(input_sequence, dtype=torch.long).unsqueeze(0)
# Generate num_generate tokens
for _ in range(num_generate):
# Forward pass through the model
with torch.no_grad():
output = model(current_sequence)
# Get probabilities, apply temperature scaling, and sample from the distribution
probabilities = F.softmax(output[-1] / temperature, dim=0).detach()
next_token_idx = torch.multinomial(probabilities, 1).item()
# Append token to the current sequence and to the generated tokens
generated_tokens.append(next_token_idx)
current_sequence = torch.cat((current_sequence, torch.tensor([[next_token_idx]])), 1)
# Convert tokens to words
generated_text = " ".join([dataset.idx2token.get(token, "<unk>") for token in generated_tokens]) # Use .get() to provide a default value for missing keys
return generated_text
Define hyperparameters specific to the transformer
d_model = 128
nhead = 8
dim_feedforward = 256
num_encoder_layers = 2
num_experts = 2
vocab_size = len(dataset.vocab) # Assume dataset.vocab is defined in the QAJsonlDataset class
Instantiate resulting MoE transformer model
moe = MixtureOfTransformerExperts(
input_size=d_model, # Assuming each word is represented by d_model features
d_model=d_model,
output_size=vocab_size, # Output size is the vocab size for token generation
nhead=nhead,
dim_feedforward=dim_feedforward,
num_experts=num_experts,
num_encoder_layers=num_encoder_layers
)
Start a loop for the interactive chat-like text generation
while True:
try:
# Get user input
seed_text = input("Enter seed text (type 'quit' to stop): ")
code
# Check if user wants to quit the interaction
if seed_text.lower() == "quit":
print("Exiting text generation chat.")
break
# User input is not empty and not “quit”, generate text
if seed_text.strip():
num_generate = 16 # Number of words to generate
temperature = 1.0 # Sampling temperature, higher will increase diversity
# Use the trained model to generate text
generated_text = generate_text(moe_transformer_model, dataset, seed_text, num_generate, temperature)
print("Generated Text:", generated_text)
else:
print("Seed text cannot be empty.")
except KeyboardInterrupt:
# Handle KeyboardInterrupt (Ctrl+C) to gracefully exit
print("\nExiting text generation chat.")
break
The positional_encoding function creates sinusoidal position encodings that are added to the transformer's token embeddings to provide the model with positional context.
The TransformerExpert class defines a single transformer encoder model that will serve as one "expert" in the MoE.
The GatingNetwork class creates a neural network that outputs gating weights for each expert based on the input features.
The MixtureOfTransformerExperts class builds the MoE model by combining several TransformerExpert models and a GatingNetwork to weigh their outputs.
The QAJsonlDataset class is a PyTorch Dataset that loads and preprocesses a QA dataset from a JSONL file for use in training and evaluating the model.
The MoETransformerModel class wraps the MoE and embedding layers to create the final model structure used for training.
The collate_fn function is used to create minibatches of data with padding for efficient batch processing.
train_model is a function to train the model using the specified loss function, optimizer, and data loader, and it includes gradient clipping to prevent exploding gradients during training.
generate_text is a function that generates text given a seed text. It uses a sampling technique based on softmax probabilities to add diversity to the generated text.
The latter part of the code, from defining the model configurations to calling the train_model function, sets up and trains the MoE Transformer model on the question-answering dataset.
The interactive loop at the end allows a user to input seed text, which the model then uses to generate and output a sequence of text.
The final statement saves the trained model's parameters to disk.
If there's any specific question or task you have about this code or if you need more detail about any section, please let me know, and I'll be happy to help!
The error message you're encountering indicates that there is a mismatch between the batch size of your model's predictions and the batch size of the target tensors.
The specific part of the error message:
code
ValueError: Expected input batch_size (128) to match target batch_size (8192).
tells us that the shape of the predictions tensor is not aligning with the shape of the targets tensor when you're trying to compute the cross-entropy loss. The predictions tensor appears to have a batch size of 128, whereas targets tensor has a batch size of 8192 (which is likely 128 multiplied by the sequence length, 64).
This often happens during the reshaping or viewing operation before the loss calculation:
python
loss = criterion(predictions.view(-1, predictions.size(-1)), targets.view(-1))
To fix the error, you need to ensure that when you reshape predictions and targets tensors to calculate the loss, they have compatible shapes. You would want your predictions tensor to be of the shape (batch_size * sequence_length, num_classes) and your targets tensor to be of the shape (batch_size * sequence_length).
Here's why the shapes are mismatched:
predictions come from a model with the last dimension representing logits for each class. It presumably has the shape (batch_size, sequence_length, num_classes) before the view call.
targets come from a data loader, which usually have the shape (batch_size, sequence_length).
Therefore, when you use .view(-1) on targets, you're indeed flattening out the entire tensor to be one-dimensional with the total number of tokens across the batch and sequence length.
You need to ensure that the logits are also being reshaped properly such that the number of rows in logits matches the total number of target tokens. This would involve reshaping the logits to be two-dimensional, with one row per token in the batch. Here is how the loss calculation should look:
python
predictions = predictions.view(-1, predictions.size(-1)) # Reshape from [batch_size, seq_len, num_classes] to [batch_size * seq_len, num_classes]
targets = targets.view(-1) # Flatten the targets to [batch_size * seq_len]
loss = criterion(predictions, targets)
After these modifications, the predictions tensor should align with the targets tensor, and you should be able to compute the loss without any error regarding a mismatch in batch sizes. If you see a mismatch in the number of classes, you'll also need to ensure that the second dimension of predictions matches the number of unique classes in your dataset (num_classes).
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
from collections import Counter
import json
from tqdm import tqdm
import math
def forward(self, x):
# Assuming x is of shape [batch_size, seq_len, d_model] you may want to aggregate
# across the sequence length dimension before the gating network
x = x.mean(dim=1) # Take mean or another operation that reduces seq_len dimension
x = self.fc(x) # Now the shape of x should match the weight matrix of the fc layer
return self.softmax(x)
class QAJsonlDataset(Dataset):
def init(self, path, seq_len):
self.seq_len = seq_len
self.pairs = self.load_data(path)
# Flatten the pairs completely before passing them to build_vocab
self.vocab, self.idx2token = self.build_vocab([word for pair in self.pairs for sublist in pair for word in sublist])
self.tokenized_pairs = [(self.tokenize(q), self.tokenize(a)) for q, a in self.pairs]
code
def load_data(self, path):
pairs = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
data = json.loads(line.strip())
question, answer = data.get("question", ""), data.get("answer", "")
pairs.append((question.split(), answer.split()))
return pairs
def tokenize(self, words):
# Tokenize a sentence and pad if necessary
# Add <eos> token at the end if there’s room
tokens = [self.vocab.get(w, self.vocab["<unk>"]) for w in words]
if len(tokens) < self.seq_len:
tokens.append(self.vocab["<eos>"]) # Add <eos> token
tokens.extend([self.vocab["<pad>"]] * (self.seq_len - len(tokens))) # Pad the rest
else:
tokens = tokens[:self.seq_len - 1] + [self.vocab["<eos>"]]
return tokens
def build_vocab(self, words):
# Start with special tokens with fixed indices
vocab = {"<unk>": 0, "<pad>": 1, "<eos>": 2}
start_index = len(vocab)
# Use Counter to count word frequencies in the corpus
counts = Counter(words)
# Create the vocab dictionary with all words, starting indices after the special tokens
for word, _ in counts.most_common():
if word not in vocab: # Skip special tokens
vocab[word] = len(vocab)
# Create the reverse mapping from indices to words
idx2token = {idx: token for token, idx in vocab.items()}
return vocab, idx2token
def __len__(self):
return len(self.tokenized_pairs)
def __getitem__(self, idx):
tokenized_question, tokenized_answer = self.tokenized_pairs[idx]
return torch.tensor(tokenized_question, dtype=torch.long), torch.tensor(tokenized_answer, dtype=torch.long)
Training loop - added gradient clipping to avoid exploding gradients
def train_model(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
progress_bar = tqdm(enumerate(data_loader), total=len(data_loader), desc=f"Epoch {epoch+1}", leave=False)
for i, (inputs, targets) in progress_bar:
optimizer.zero_grad()
predictions = model(inputs)
predictions = predictions.view(-1, predictions.size(-1))
targets = targets.view(-1) # Flatten the targets to [batch_size * seq_len]
loss = criterion(predictions, targets)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # Gradient clipping
optimizer.step()
total_loss += loss.item()
progress_bar.set_postfix({"Loss": loss.item()})
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, Average Loss: {average_loss}")
def generate_text(model, dataset, seed_text, num_generate, temperature=1.0):
model.eval() # Put the model in evaluation mode
code
# List to store the generated tokens
generated_tokens = []
# Initial sequence (prefix) to start the generation process
input_sequence = [dataset.vocab.get(word, dataset.vocab["<pad>"]) for word in seed_text.split()] # Convert to token IDs
current_sequence = torch.tensor(input_sequence, dtype=torch.long).unsqueeze(0)
# Generate num_generate tokens
for _ in range(num_generate):
# Forward pass through the model
with torch.no_grad():
output = model(current_sequence)
# Get probabilities, apply temperature scaling, and sample from the distribution
probabilities = F.softmax(output[-1] / temperature, dim=0).detach()
next_token_idx = torch.multinomial(probabilities, 1).item()
# Append token to the current sequence and to the generated tokens
generated_tokens.append(next_token_idx)
current_sequence = torch.cat((current_sequence, torch.tensor([[next_token_idx]])), 1)
# Convert tokens to words
generated_text = " ".join([dataset.idx2token.get(token, "<unk>") for token in generated_tokens]) # Use .get() to provide a default value for missing keys
return generated_text
Define hyperparameters specific to the transformer
d_model = 128
nhead = 8
dim_feedforward = 256
num_encoder_layers = 2
num_experts = 2
vocab_size = len(dataset.vocab) # Assume dataset.vocab is defined in the QAJsonlDataset class
Instantiate resulting MoE transformer model
moe = MixtureOfTransformerExperts(
input_size=d_model, # Assuming each word is represented by d_model features
d_model=d_model,
output_size=vocab_size, # Output size is the vocab size for token generation
nhead=nhead,
dim_feedforward=dim_feedforward,
num_experts=num_experts,
num_encoder_layers=num_encoder_layers
)
Start a loop for the interactive chat-like text generation
while True:
try:
# Get user input
seed_text = input("Enter seed text (type 'quit' to stop): ")
code
# Check if user wants to quit the interaction
if seed_text.lower() == "quit":
print("Exiting text generation chat.")
break
# User input is not empty and not “quit”, generate text
if seed_text.strip():
num_generate = 16 # Number of words to generate
temperature = 1.0 # Sampling temperature, higher will increase diversity
# Use the trained model to generate text
generated_text = generate_text(moe_transformer_model, dataset, seed_text, num_generate, temperature)
print("Generated Text:", generated_text)
else:
print("Seed text cannot be empty.")
except KeyboardInterrupt:
# Handle KeyboardInterrupt (Ctrl+C) to gracefully exit
print("\nExiting text generation chat.")
break
torch.save(moe_transformer_model.state_dict(), "MoE_Transformer-X2-9M-QA.pth") i still get the same error
The error indicates that the model's output predictions and the target labels are not correctly aligned in terms of batch size when computing the loss. Given that the code seems correct in terms of reshaping predictions and targets before loss computation, we'll need to check other aspects of the code that could be causing this issue.
Let's take a look at your MixtureOfTransformerExperts forward pass. Here is the current implementation:
Your MixtureOfTransformerExperts is taking a mixture of output vectors from all expert transformer models and combining them using gating scores. The combination seems to not consider the sequence length, and instead, it outputs only a single vector per sequence based on the code transformer_output[:, -1, :]. This would lead to a shape mismatch since your targets are likely to be of shape [batch_size, sequence_length].
To resolve this, you need to modify your model so that it outputs predictions for each position in the sequence, not only the last position. Let's modify the TransformerExpert and MixtureOfTransformerExperts to handle the full sequence:
python
# In TransformerExpert
def forward(self, x):
x = self.input_fc(x) + positional_encoding(x.size(1), self.d_model, x.device)
transformer_output = self.transformer_encoder(x)
output = self.output_fc(transformer_output) # Apply output_fc to each time step in the sequence
return output
python
# In MixtureOfTransformerExperts
def forward(self, x):
gating_scores = self.gating_network(x)
expert_outputs = [expert(x) for expert in self.experts] # Remove unsqueeze operation
stacked_expert_outputs = torch.stack(expert_outputs) # Now it is [num_experts, batch, seq_len, output_size]
# Expand gating scores to apply for every time step and output class
expanded_gating_scores = gating_scores.unsqueeze(2).unsqueeze(3).expand(-1, -1, x.size(1), vocab_size)
mixed_output = torch.sum(stacked_expert_outputs * expanded_gating_scores, dim=0) # Sum weighted expert outputs for each time step
return mixed_output
In the forward method of MixtureOfTransformerExperts, we stack the expert outputs and then use expanded gating scores to apply the mixture across each time step and output class.
Make sure to update the forward method of MoETransformerModel to not add positional encoding twice, since you already did that in TransformerExpert class:
python
class MoETransformerModel(nn.Module):
# ...
def forward(self, x):
embedded = self.dropout(self.embedding(x))
return self.moe(embedded) # Remove positional encoding addition here, as it's already added in TransformerExpert
With these changes, you should ensure that the model's output shape aligns with the targets, allowing the loss to be computed correctly without a batch size mismatch error. Please make sure all the dimensions used in these modifications are appropriately set according to your specific setup.