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
def forward(self, x):
h, _ = self.lstm(x)
# Shape of h: [batch_size, sequence_length, hidden_size]
# No longer taking the last sequence output, transform for all time steps
h = h.reshape(-1, h.shape[2]) # Flatten to two dimensions: [batch_size * sequence_length, hidden_size]
return self.fc(h)
def forward(self, x):
if x.dim() > 2:
x = x.view(x.size(0), -1) # Flatten the tensor correctly
x = self.fc(x)
return self.softmax(x)
Mixture of Experts Model
class MixtureOfExperts(nn.Module):
def init(self, input_size, hidden_size, output_size, num_experts):
super(MixtureOfExperts, self).init()
self.num_experts = num_experts
self.experts = nn.ModuleList([LSTMExpert(input_size, hidden_size, output_size) for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
code
Assistant
Everything looks great in your code! You've defined your models, the dataset class to handle loading and tokenizing your data, a collate function for padding sequences in your DataLoader, and individual training and text generation functions. Additionally, you've integrated the Mixture of Experts model into the flow and instantiated an MoEModel with embeddings and the mixture of experts.
I see that you've planned to interactively generate text by providing a seed and then using the trained model to predict subsequent tokens. Just to reiterate, this process feeds the model's predictions back as input in a loop to generate a sequence of tokens.
User
Total trainable parameters: 14652208
Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Q&A.py", line 235, in
train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader)
File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Q&A.py", line 162, in train_model_TXT
average_loss = total_loss / len(data_loader.dataset)
AttributeError: 'tqdm' object has no attribute 'dataset'
Assistant
It looks like you're trying to get the length of the dataset from the tqdm-wrapped data_loader, which will not work because the tqdm object does not have a 'dataset' attribute. The dataset is an attribute of the original data_loader, not the tqdm wrapper.
To fix this, you should refer to the directly when you need the dataset's length or other properties. Since is not modified by wrapping it in tqdm, you can safely use it. Adjust your function like so:
def forward(self, x):
# Flatten x for gating input: [batch_size * sequence_length, input_size]
gating_input = x.contiguous().view(-1, x.shape[-1])
# Get gating scores for each expert: [batch_size * sequence_length, num_experts, 1]
gating_scores = self.gating_network(gating_input).view(-1, self.num_experts, 1)
# Compute outputs from each expert
expert_outputs = [expert(x) for expert in self.experts] # List of [batch_size * sequence_length, vocab_size] tensors
# Stack along a new dimension for experts: [batch_size * sequence_length, vocab_size, num_experts]
expert_outputs = torch.stack(expert_outputs, dim=2)
# Calculate weighted sum of expert outputs: [batch_size * sequence_length, vocab_size]
mixed_output = torch.bmm(expert_outputs, gating_scores) # [batch_size * sequence_length, vocab_size, 1]
mixed_output = mixed_output.squeeze(-1) # Remove last singleton dimension
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)
def train_model_TXT(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
code
# Wrap the data loader with tqdm for the progress bar
data_loader = tqdm(data_loader, desc=f"Epoch {epoch+1}", leave=False)
for i, (inputs, targets) in enumerate(data_loader):
optimizer.zero_grad()
# Forward pass
predictions = model(inputs)
# Flatten targets to be [batch_size * sequence_length]
targets = targets.view(-1)
# Flatten predictions to be [batch_size * sequence_length, num_classes]
predictions = predictions.view(-1, predictions.size(-1))
# Loss computation
loss = criterion(predictions, targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
# Update the tqdm progress bar
data_loader.set_postfix({"Loss": loss.item()})
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, 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
Integration of MoE with the rest of the code
vocab_size = len(dataset.vocab) # The size of the vocabulary
embedding_dim = 128 # Size of embeddings
hidden_size = 256 # Number of features in the hidden state of the LSTM
num_experts = 2 # Define the number of LSTM experts you want in your MoE model
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 = 0.5 # Sampling temperature, higher will increase diversity
# Use the trained model to generate text
generated_text = generate_text(moe_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
One point I would like to highlight is that during text generation, after generating one token, you should consider using that newly generated token immediately as part of the input for the next prediction. In the generate_text function, you handled it well by concatenating the new token with the existing sequence.
It seems like you have some placeholders such as 'GSM2K.jsonl'. Make sure to replace those with the actual paths to your dataset files.
If you run into issues while training (e.g., GPU memory errors, convergence issues), you might want to adjust the batch size, learning rate, optimizer settings, or the model's hyperparameters (number of experts, hidden layer sizes, etc.).
Also, if during text generation the generated sequences are not coherent or meaningful, you might need to tweak the temperature parameter used in sampling from the softmax output or consider training the model for more epochs.
Lastly, ensure to save the model after training so you don't have to retrain it every time you need to use it. You can do so with:
Feel free to execute the code and monitor your memory usage and training performance metrics as you go!
data_loader
data_loader
train_model_TXT
python
def train_model_TXT(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()
# Forward pass
predictions = model(inputs)
# Flatten targets to be [batch_size * sequence_length]
targets = targets.view(-1)
# Flatten predictions to be [batch_size * sequence_length, num_classes]
predictions = predictions.view(-1, predictions.size(-1))
# Loss computation
loss = criterion(predictions, targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
# Update the tqdm progress bar
progress_bar.set_postfix({"Loss": loss.item()})
average_loss = total_loss / (len(data_loader.dataset) * data_loader.batch_size)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
Important modifications:
Create progress_bar wrapped around the enumerate(data_loader) with the total number of iterations set to len(data_loader).
Inside the loop, continue to iterate over progress_bar which yields the index and data tuple.
When calculating average_loss, use len(data_loader.dataset) directly to get the dataset length, and multiply by data_loader.batch_size to get the total number of samples processed.
By doing these changes, your code should now work as expected without any AttributeError.