When you finish looking at the code return "Good Day!": 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
from datasets import load_dataset
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
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)
Mixture of Experts Model
class MixtureOfTransformerExperts(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MixtureOfTransformerExperts, self).init()
self.num_experts = num_experts
self.output_size = output_size # Store output_size as an instance variable
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers) for _ in range(num_experts)])
self.gating_network = GatingNetwork(d_model, num_experts)
code
def forward(self, x):
gating_scores = self.gating_network(x) # [batch_size, num_experts]
expert_outputs = [expert(x) for expert in self.experts] # List of [batch_size, seq_len, output_size]
stacked_expert_outputs = torch.stack(expert_outputs) # Shape: [num_experts, batch_size, seq_len, output_size]
# Expand gating scores
expanded_gating_scores = gating_scores.unsqueeze(2).unsqueeze(3) # Shape: [batch_size, num_experts, 1, 1]
expanded_gating_scores = expanded_gating_scores.expand(-1, -1, x.size(1), self.output_size)
expanded_gating_scores = expanded_gating_scores.transpose(0, 1) # Shape: [num_experts, batch_size, seq_len, output_size]
# Now the shape of expanded_gating_scores matches stacked_expert_outputs, and broadcasting will work
mixed_output = torch.sum(stacked_expert_outputs * expanded_gating_scores, dim=0) # Sum weighted expert outputs for each time step
return mixed_output
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, scheduler, num_epochs, data_loader):
model.train()
best_loss = float("inf")
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}")
code
# Step the scheduler based on the average loss
scheduler.step(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=-1).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
Function to count the number of tokens in the dataset
def count_tokens_in_dataset(dataset):
return sum([len(pair[0]) + len(pair[1]) for pair in dataset.pairs])
num_tokens = count_tokens_in_dataset(dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
Define hyperparameters specific to the transformer
d_model = 128 #128
nhead = 8 #8
dim_feedforward = 512 #256
num_encoder_layers = 4 #2
num_experts = 2 #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
I get this error: AttributeError Traceback (most recent call last)
in <cell line: 220>()
218 return sum([len(pair[0]) + len(pair[1]) for pair in dataset.pairs])
219
--> 220 num_tokens = count_tokens_in_dataset(dataset)
221 print(f"Total number of tokens in the dataset: {num_tokens}")
222
in count_tokens_in_dataset(dataset)
216 # Function to count the number of tokens in the dataset
217 def count_tokens_in_dataset(dataset):
--> 218 return sum([len(pair[0]) + len(pair[1]) for pair in dataset.pairs])
219
220 num_tokens = count_tokens_in_dataset(dataset)
AttributeError: 'DatasetDict' object has no attribute 'pairs'
Assistant
The error you've encountered indicates that the count_tokens_in_dataset function is expecting a dataset object with an attribute pairs, which is supposed to be a list of question-answer pairs. However, the dataset variable passed to the function is a DatasetDict object from the datasets library and does not have this attribute.
To resolve this issue, you need to modify the count_tokens_in_dataset function so that it properly counts tokens within the GSM8K dataset structure. Since you already defined a GSM8KDataset class earlier in your code, you can use that class to iterate over the data and count the tokens.
You can adjust the function like this:
python
def count_tokens_in_dataset(dataset):
return sum(len(question) + len(answer) for question, answer in dataset)
Then, you should pass an instance of GSM8KDataset to this function instead of the raw DatasetDict. Here's how you can call the count_tokens_in_dataset function with a GSM8KDataset instance:
python
num_tokens = count_tokens_in_dataset(gsm8k_dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
This will iterate over your custom dataset class which properly extracts the question and answer tokens, allowing for the computation of the total token count.
Make sure that you place the call to count_tokens_in_dataset(gsm8k_dataset) after you've instantiated the GSM8KDataset object. If you try to use dataset directly (as it was done originally), it will fail because DatasetDict doesn't have a structure that's compatible with the count_tokens_in_dataset function without modifications.
User
After making the change, i got this error: ValueError Traceback (most recent call last)
in <cell line: 220>()
218 return sum(len(question) + len(answer) for question, answer in dataset)
219
--> 220 num_tokens = count_tokens_in_dataset(gsm8k_dataset)
221 print(f"Total number of tokens in the dataset: {num_tokens}")
222
The issue is happening because you're trying to create a torch tensor directly from a list of strings. The torch.tensor() function expects a sequence of numbers, not strings. You see this error when you call count_tokens_in_dataset(gsm8k_dataset) because it's iterating over the dataset and trying to retrieve items via the __getitem__ method, which is causing the error.
Instead of changing the count_tokens_in_dataset function as previously suggested, what you should do is modify the __getitem__ method in your GSM8KDataset class to return the lengths of the questions and answers, rather than the tokenized tensors. Here's how you can fix the __getitem__ method:
And now, adjust the count_tokens_in_dataset function to handle lengths directly:
python
def count_tokens_in_dataset(dataset):
return sum(len_question + len_answer for len_question, len_answer in dataset)
Use these updated functions and call them like before:
python
num_tokens = count_tokens_in_dataset(gsm8k_dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
This should now correctly sum the lengths of the questions and answers without trying to convert them into tensor objects.
User
After making the changes, i got this: AttributeError Traceback (most recent call last)
in <cell line: 229>()
227 num_encoder_layers = 4 #2
228 num_experts = 2 #2
--> 229 vocab_size = len(dataset.vocab) # Assume dataset.vocab is defined in the QAJsonlDataset class
230
231 # Instantiate resulting MoE transformer model
AttributeError: 'DatasetDict' object has no attribute 'vocab'
Assistant
The error suggests that you are trying to access a vocab attribute from the DatasetDict object, but this object does not have such an attribute by default. This vocab attribute is expected to be present in the QAJsonlDataset class instance instead.
Here is what you need to do to resolve the issue:
Make sure you have instantiated your QAJsonlDataset class with the appropriate parameters. For example, you may have a code snippet like this:
python
seq_len = 128 # Or some appropriate sequence length for your task
path_to_jsonl_file = 'path/to/your/jsonl/file' # Replace this with the actual path to your file
qa_jsonl_dataset = QAJsonlDataset(path_to_jsonl_file, seq_len) # Create an instance of your dataset class
Once you have created an instance of QAJsonlDataset, you can then access the vocab attribute from this instance:
python
vocab_size = len(qa_jsonl_dataset.vocab)
Update the references to the dataset in your code that require the vocab property so that they refer to the QAJsonlDataset instance.
Please ensure that you have loaded your JSONL data properly and initialized the QAJsonlDataset class prior to accessing its attributes. If your data is within the gsm8k_dataset variable and you have defined the vocab inside the GSM8KDataset class, then you should access it like this:
python
vocab_size = len(gsm8k_dataset.vocab)
Make sure to replace gsm8k_dataset with the name of the instance of your custom dataset class with the vocab attribute. It is crucial that the vocab is built and the attribute is assigned in the class before you try to access it.
If you haven't already built the vocab in your dataset class, you will need to add that step to your code so that the vocab attribute will exist and can be accessed. The building of the vocab should typically happen when you create an instance of your dataset class, likely in the __init__ method.
User
Now i get this: AttributeError Traceback (most recent call last)
in <cell line: 229>()
227 num_encoder_layers = 4 #2
228 num_experts = 2 #2
--> 229 vocab_size = len(dataset.vocab) # Assume dataset.vocab is defined in the QAJsonlDataset class
230
231 # Instantiate resulting MoE transformer model
AttributeError: 'GSM8KDataset' object has no attribute 'vocab'
Assistant
Apologies for the oversight. From the code you provided, we need a bit of reorganization for the script to work as intended.
There are a few things to address:
The QAJsonlDataset class expects a path to a JSONL file, which you would need to provide for it to work. The GSM8KDataset does not have a vocab attribute as written, it only tokenizes the data and returns as tensors.
It seems like you want to use QAJsonlDataset to handle the vocabulary and tokenization, but it is not instantiated in the provided code block.
The QAJsonlDataset class also attempts to create a vocabulary from data which is not provided in your dataset loading part where you load the 'gsm8k' dataset from datasets.load_dataset.
Here's how you should approach the problem:
Instantiate the QAJsonlDataset class if you have a file containing the QA pairs.
Use this instantiated object to determine your vocab_size.
Since you are already using a datasets.load_dataset, it appears you might not have them in a JSONL file. If you only have them as part of the datasets library download, you should create the vocabulary from that data.
Here's a simple refactored way to compute the vocabulary size directly from the GSM8KDataset class:
python
# Instantiate your custom dataset class (Assuming its __getitem__ returns tokenized tensors, not lengths):
gsm8k_dataset = GSM8KDataset(train_dataset)
# Iterate over the dataset to build a vocabulary
def build_vocab(dataset):
vocab = Counter()
for idx in range(len(dataset)):
question, answer = dataset[idx]
vocab.update(question.tolist())
vocab.update(answer.tolist())
return vocab
# Use this function to build the vocab and then get its size
vocab = build_vocab(gsm8k_dataset)
vocab_size = len(vocab)
# Now continue with your code
# ...
Make sure that your GSM8KDataset.__getitem__ is outputting tokenized tensors correctly, then the code snippet above to build the vocabulary should work. Replace the piece of code where you try to get the vocab size from dataset.vocab with the new method of obtaining vocab_size.
User
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
from datasets import load_dataset
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
The issue is that the GSM8KDataset class does not contain a vocab attribute. We have previously discussed moving the vocabulary-related code into the dataset class, or creating a separate mechanism to handle the vocabulary. From the code you provided, it looks like you're trying to build the vocabulary after initializing the dataset, which is a valid approach. However, you should not try to access dataset.vocab afterward, as that attribute does not exist.
You should remove the line vocab_size = len(dataset.vocab) since we've already obtained vocab_size from the vocab right after building it:
Below is the correct portion of the code where vocab_size is set. This change fixes the error:
python
num_tokens = count_tokens_in_dataset(dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
vocab = build_vocab(dataset)
vocab_size = len(vocab) # Use the previously built vocab to get the size
# Define hyperparameters specific to the transformer
d_model = 128 # 128
nhead = 8 # 8
dim_feedforward = 512 # 256
num_encoder_layers = 4 # 2
num_experts = 2 # 2
# 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
)
# Instantiate the MoE transformer model
moe_transformer_model = MoETransformerModel(vocab_size, d_model, moe)
# ... Rest of the code remains the same
With this correction, your vocab_size should now correctly reflect the size of the vocabulary as calculated directly from the Counter returned by build_vocab. This should resolve the AttributeError you were experiencing.
User
I get this now: AttributeError Traceback (most recent call last)
in <cell line: 180>()
178 print(f"Total number of tokens in the dataset: {num_tokens}")
179
--> 180 vocab = build_vocab(dataset)
181 vocab_size = len(vocab) # Use the previously built vocab to get the size
182
in build_vocab(dataset)
19 for idx in range(len(dataset)):
20 question, answer = dataset[idx]
---> 21 vocab.update(question.tolist())
22 vocab.update(answer.tolist())
23 return vocab
AttributeError: 'int' object has no attribute 'tolist'
Assistant
The AttributeError is caused by trying to call the tolist method on an int object within the build_vocab function. This is occurring because the __getitem__ method in GSM8KDataset was modified previously to return only the lengths of the questions and answers, which are integers, and not the tokenized questions and answers themselves.
To correct this, you must revert the __getitem__ method in the GSM8KDataset to return tokenized questions and answers. To build the vocabulary, you should tokenize and count the tokens occurring in the questions and answers.
First, update the GSM8KDataset class to tokenize and return the actual tokens:
python
class GSM8KDataset(Dataset):
def __init__(self, train_dataset, vocab=None, max_length=None):
self.train_dataset = train_dataset
self.vocab = vocab or self._build_vocab()
self.max_length = max_length or 512 # Set a default value if not provided
def _build_vocab(self):
vocab = Counter()
for idx in range(len(self.train_dataset)):
item = self.train_dataset[idx]
question = item["question"].split()
answer = item["answer"].split()
vocab.update(question)
vocab.update(answer)
return {word: i for i, (word, _) in enumerate(vocab.items(), start=2)} # Start from 2 to leave 0 for padding and 1 for unknown
# This method now tokenizes the text and also handles words not in the vocabulary
def _tokenize(self, text):
tokens = [self.vocab.get(word, 1) for word in text.split()] # 1 is the index for unknown words
return tokens[:self.max_length] # Truncate if necessary
def __len__(self):
return len(self.train_dataset)
def __getitem__(self, idx):
item = self.train_dataset[idx]
question_tokens = self._tokenize(item["question"])
answer_tokens = self._tokenize(item["answer"])
return torch.tensor(question_tokens, dtype=torch.long), torch.tensor(answer_tokens, dtype=torch.long)
User
Check if what you said has been applied: 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
from datasets import load_dataset
def build_vocab(dataset):
vocab = Counter()
for idx in range(len(dataset)):
question, answer = dataset[idx]
vocab.update(question.tolist())
vocab.update(answer.tolist())
return vocab
class GSM8KDataset(Dataset):
def init(self, train_dataset, vocab=None, max_length=None):
self.train_dataset = train_dataset
self.vocab = vocab or self._build_vocab()
self.max_length = max_length or 512 # Set a default value if not provided
code
def _build_vocab(self):
vocab = Counter()
for idx in range(len(self.train_dataset)):
item = self.train_dataset[idx]
question = item["question"].split()
answer = item["answer"].split()
vocab.update(question)
vocab.update(answer)
return {word: i for i, (word, _) in enumerate(vocab.items(), start=2)} # Start from 2 to leave 0 for padding and 1 for unknown
# This method now tokenizes the text and also handles words not in the vocabulary
def _tokenize(self, text):
tokens = [self.vocab.get(word, 1) for word in text.split()] # 1 is the index for unknown words
return tokens[:self.max_length] # Truncate if necessary
def __len__(self):
return len(self.train_dataset)
def __getitem__(self, idx):
item = self.train_dataset[idx]
question_tokens = self._tokenize(item["question"])
answer_tokens = self._tokenize(item["answer"])
return torch.tensor(question_tokens, dtype=torch.long), torch.tensor(answer_tokens, dtype=torch.long)
The provided code has indeed implemented the suggested changes to the GSM8KDataset class, including the _build_vocab and _tokenize methods which are essential for handling vocabulary and tokenization. You've also correctly instantiated the gsm8k_dataset and are using its vocab to determine the vocab_size.
However, there are still a couple of issues to be addressed:
The count_tokens_in_dataset function is still using the previous version of the dataset that returned the lengths of questions and answers. Due to the new implementation of the GSM8KDataset class, which returns tensors of token IDs, this function will no longer work as expected.
The code snippet for generate_text is using the dataset instance to convert words to IDs, but it incorrectly references the dataset as just dataset. It should be using the instantiated gsm8k_dataset (or whatever your dataset instance is named) for this purpose.
Let's fix these issues.
Update the count_tokens_in_dataset function to work with the new dataset (assuming we will count the total tokens across all samples):
python
def count_tokens_in_dataset(dataset):
# Initialize the counter for tokens
token_count = 0
for question, answer in dataset:
token_count += (question != 0).sum().item() # Count nonzero tokens in question
token_count += (answer != 0).sum().item() # Count nonzero tokens in answer
return token_count
And when calling this function, pass the gsm8k_dataset:
python
num_tokens = count_tokens_in_dataset(gsm8k_dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
For the text generation part, ensure that you are referencing the correct dataset instance to convert seed text to token IDs in the generate_text function:
python
# Use the trained model to generate text
generated_text = generate_text(moe_transformer_model, gsm8k_dataset, seed_text, num_generate, temperature)
print("Generated Text:", generated_text)
Now you can remove the standalone build_vocab function at the beginning of the code, as the GSM8KDataset class is handling vocabulary creation internally.
Make sure to apply these fixes consistently throughout your code, and it should resolve the remaining issues.
User
ValueError Traceback (most recent call last)
in <cell line: 231>()
229
230 # Train the model with the text data
--> 231 train_model(moe_transformer_model, criterion, optimizer, scheduler, num_epochs, data_loader)
232
233 # Start a loop for the interactive chat-like text generation
4 frames
/usr/local/lib/python3.10/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
3051 if size_average is not None or reduce is not None:
3052 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 3053 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
3054
3055
ValueError: Expected input batch_size (2976) to match target batch_size (3904).
Assistant
The error you're seeing is related to the shapes of the predictions and targets tensors not matching. In your training loop, you have a block where predictions and targets are being reshaped:
The expectation here is that the total number of elements in predictions should match the total number of elements in targets. However, they don't, which is what the error is telling you ("Expected input batch_size (2976) to match target batch_size (3904)").
There might be differences in sequence lengths after padding, and it's important that both the predictions and the targets have the same sequence length for each sample so that they can be correctly paired. In other words, each prediction should correspond to exactly one target.
Here's how you can ensure they match:
If you're using padding, make sure that your target tensor is masked so that it doesn't calculate loss for the padded tokens. Typically, you would use a padding index value in your targets, and those values should be ignored in the loss calculation. Make sure your loss function ignores the index that's used for padding:
Modify your collate function if necessary to ensure that both inputs and targets are correctly padded and aligned. Your collate_fn seems to be correct, but you'll want to double-check this part just in case.
Check that each question/answer pair is being appropriately processed so that the sequence lengths match up after any tokenization, truncating, or padding operations.
With these considerations, go back and check your Data Preprocessing steps, especially collate_fn and GSM8KDataset.__getitem__, and also verify that your Dataloader is correctly batching your data so that each element of a batch has the same sequence length (after padding). Then, adjust your training loop if necessary to ensure the loss function receives the correct batch sizes for input and target tensors.
Once the preprocessing is aligned correctly, the input and target tensors should reshape without error and the training loop should work without the reported ValueError.
User
after modifying the criterion, i got this: ValueError Traceback (most recent call last)
in <cell line: 231>()
229
230 # Train the model with the text data
--> 231 train_model(moe_transformer_model, criterion, optimizer, scheduler, num_epochs, data_loader)
232
233 # Start a loop for the interactive chat-like text generation
4 frames
/usr/local/lib/python3.10/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
3051 if size_average is not None or reduce is not None:
3052 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 3053 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
3054
3055
ValueError: Expected input batch_size (3104) to match target batch_size (4864).
Assistant
The error message suggests that there is still a mismatch between the batch sizes for your inputs and targets when they are passed to the cross-entropy loss function. This indicates that the model's outputs and the target labels do not have corresponding dimensions.
Let's check a few things:
Ensure that pad_sequence in collate_fn function is applied correctly to both questions and answers. It aligns the length of sequences within each batch by adding padding where necessary, and the padding_value should be set to a value that the model recognizes as padding. Typically, this value should be the index of the padding token in your vocabulary, which is often 0.
Confirm that the model is configured to output predictions with a shape that matches the targets. This means you should have one prediction per token per batch.
Ensure the padding tokens in the target labels are ignored by the loss function, which you are already handling by setting ignore_index=0 in the criterion.
If the issue persists after double-checking the above points, it would be helpful to inspect the shapes of inputs, targets, and predictions immediately before the loss function is called. Add print statements to log their shapes:
python
for i, (inputs, targets) in progress_bar:
optimizer.zero_grad()
predictions = model(inputs)
print("inputs shape:", inputs.shape)
print("targets shape:", targets.shape)
print("predictions shape:", predictions.shape)
# Ensure that the predictions are reshaped to match the target dimensions
predictions = predictions.view(-1, predictions.size(-1))
targets = targets.view(-1)
print("Reshaped predictions shape:", predictions.shape)
print("Reshaped targets shape:", targets.shape)
loss = criterion(predictions, targets)
# ...
If the predictions tensor has three dimensions ([batch_size, sequence_length, num_classes]) and the targets tensor has two dimensions ([batch_size, sequence_length]), the reshaping of should be compatible with the reshaped . However, if either or is not correctly shaped, the loss function will raise an error.
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)
Mixture of Experts Model
class MixtureOfTransformerExperts(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MixtureOfTransformerExperts, self).init()
self.num_experts = num_experts
self.output_size = output_size # Store output_size as an instance variable
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers) for _ in range(num_experts)])
self.gating_network = GatingNetwork(d_model, num_experts)
code
def forward(self, x):
gating_scores = self.gating_network(x) # [batch_size, num_experts]
expert_outputs = [expert(x) for expert in self.experts] # List of [batch_size, seq_len, output_size]
stacked_expert_outputs = torch.stack(expert_outputs) # Shape: [num_experts, batch_size, seq_len, output_size]
# Expand gating scores
expanded_gating_scores = gating_scores.unsqueeze(2).unsqueeze(3) # Shape: [batch_size, num_experts, 1, 1]
expanded_gating_scores = expanded_gating_scores.expand(-1, -1, x.size(1), self.output_size)
expanded_gating_scores = expanded_gating_scores.transpose(0, 1) # Shape: [num_experts, batch_size, seq_len, output_size]
# Now the shape of expanded_gating_scores matches stacked_expert_outputs, and broadcasting will work
mixed_output = torch.sum(stacked_expert_outputs * expanded_gating_scores, dim=0) # Sum weighted expert outputs for each time step
return mixed_output
Training loop - added gradient clipping to avoid exploding gradients
def train_model(model, criterion, optimizer, scheduler, num_epochs, data_loader):
model.train()
best_loss = float("inf")
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}")
code
# Step the scheduler based on the average loss
scheduler.step(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=-1).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
Function to count the number of tokens in the dataset
def count_tokens_in_dataset(dataset):
return sum(len_question + len_answer for len_question, len_answer in dataset)
num_tokens = count_tokens_in_dataset(dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
Define hyperparameters specific to the transformer
d_model = 128 #128
nhead = 8 #8
dim_feedforward = 512 #256
num_encoder_layers = 4 #2
num_experts = 2 #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
In this updated class, a _build_vocab helper function creates the vocabulary from the dataset, and _tokenize handles converting text to token IDs. The __getitem__ method has been reverted to returning tensors of token IDs.
Now that GSM8KDataset takes care of the vocabulary, you don't have to call build_vocab separately, and you can directly obtain the vocabulary size from GSM8KDataset's vocab attribute:
python
# Create dataset instance
gsm8k_dataset = GSM8KDataset(train_dataset)
# Get vocabulary size from the dataset instance
vocab_size = len(gsm8k_dataset.vocab)
# Proceed with the remaining code...
When creating the data loader, ensure you use the gsm8k_dataset instance:
Moreover, the count_tokens_in_dataset function and the way token counts are used elsewhere in the code may need further adjustments, depending on how you want to handle the vocabulary. The changes to the GSM8KDataset above should facilitate the correct handling of vocabularies and tokenization.
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
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)
Mixture of Experts Model
class MixtureOfTransformerExperts(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MixtureOfTransformerExperts, self).init()
self.num_experts = num_experts
self.output_size = output_size # Store output_size as an instance variable
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers) for _ in range(num_experts)])
self.gating_network = GatingNetwork(d_model, num_experts)
code
def forward(self, x):
gating_scores = self.gating_network(x) # [batch_size, num_experts]
expert_outputs = [expert(x) for expert in self.experts] # List of [batch_size, seq_len, output_size]
stacked_expert_outputs = torch.stack(expert_outputs) # Shape: [num_experts, batch_size, seq_len, output_size]
# Expand gating scores
expanded_gating_scores = gating_scores.unsqueeze(2).unsqueeze(3) # Shape: [batch_size, num_experts, 1, 1]
expanded_gating_scores = expanded_gating_scores.expand(-1, -1, x.size(1), self.output_size)
expanded_gating_scores = expanded_gating_scores.transpose(0, 1) # Shape: [num_experts, batch_size, seq_len, output_size]
# Now the shape of expanded_gating_scores matches stacked_expert_outputs, and broadcasting will work
mixed_output = torch.sum(stacked_expert_outputs * expanded_gating_scores, dim=0) # Sum weighted expert outputs for each time step
return mixed_output
Training loop - added gradient clipping to avoid exploding gradients
def train_model(model, criterion, optimizer, scheduler, num_epochs, data_loader):
model.train()
best_loss = float("inf")
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}")
code
# Step the scheduler based on the average loss
scheduler.step(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=-1).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
Function to count the number of tokens in the dataset
def count_tokens_in_dataset(dataset):
return sum(len_question + len_answer for len_question, len_answer in dataset)
num_tokens = count_tokens_in_dataset(dataset)
print(f"Total number of tokens in the dataset: {num_tokens}")
Get vocabulary size from the dataset instance
vocab_size = len(gsm8k_dataset.vocab)
Define hyperparameters specific to the transformer
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
Based on the printed shapes, you should be able to determine where the mismatch is occurring. You may need to adjust how sequences are being padded or change how tensors are being reshaped.
For example, if targets contains padded indices that should be ignored, make sure the padding index is indeed 0 (or whatever was used in collate_fn). Additionally, ensure that predictions contains valid probability distributions for each token, including the padding tokens, which will not contribute to the loss due to the ignore_index=0 parameter.