import torch
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
from collections import Counter
from itertools import chain
Example data
source_sentences = ["hello how are you", "what is your name"]
target_sentences = ["hi i am fine", "i am a chatbot"]
Tokenization and vocabulary
Tokenize and detokenize
def tokenize(sentence):
return sentence.split()
def numericalize(sentences, vocab):
return [[vocab.get(word, vocab['']) for word in tokenize(sentence)] for sentence in sentences]
def detokenize(tokens, vocab):
reverse_vocab = {idx: word for word, idx in vocab.items()}
return ' '.join(reverse_vocab.get(idx, '') for idx in tokens)
def build_vocab(sentences):
flat_list = list(chain(*sentences))
counter = Counter(flat_list)
vocab = {word: i+1 for i, (word, _) in enumerate(counter.items())}
vocab[''] = 0
vocab[''] = len(vocab) + 1
return vocab
Traceback (most recent call last):
File "/home/max/test.py", line 31, in
source_tokens = tokenize(source_sentences)
File "/home/max/test.py", line 14, in tokenize
return sentence.split()
AttributeError: 'list' object has no attribute 'split'
Assistant
The error you are encountering indicates that the tokenize function is being called on a list of sentences (source_sentences and target_sentences) instead of on individual sentences. This causes an AttributeError because lists do not have a split method. To resolve this, you should iterate over each sentence in the list and apply tokenize to each one individually.
Here's the corrected code for tokenizing your sentences:
# Tokenization and vocabulary
def tokenize(sentence):
return sentence.split()
# Tokenizing each individual sentence in a list
source_tokens = [tokenize(sentence) for sentence in source_sentences]
target_tokens = [tokenize(sentence) for sentence in target_sentences]
def build_vocab(tokenized_sentences):
flat_list = list(chain(*tokenized_sentences))
counter = Counter(flat_list)
vocab = {word: i+1 for i, (word, _) in enumerate(counter.items())}
vocab['<pad>'] = 0
vocab['<unk>'] = len(vocab) + 1
return vocab
source_vocab = build_vocab(source_tokens)
target_vocab = build_vocab(target_tokens)
def numericalize(sentences, vocab):
return [[vocab.get(word, vocab['<unk>']) for word in sentence] for sentence in sentences]
source_numerical = numericalize(source_tokens, source_vocab)
target_numerical = numericalize(target_tokens, target_vocab)
User
File "/home/max/test.py", line 163, in
train_loss = train(model, train_loader, criterion, optimizer, device)
File "/home/max/test.py", line 136, in train
output = model(src, trg)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/home/max/test.py", line 121, in forward
output, encoder_hidden, encoder_cell = self.decoder(input.unsqueeze(1), encoder_hidden, encoder_cell, encoder_outputs)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/home/max/test.py", line 99, in forward
context, _ = self.attention(hidden[-1].unsqueeze(1), encoder_outputs, encoder_outputs)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/max/venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/home/max/test.py", line 85, in forward
context = torch.bmm(weights, values)
RuntimeError: Expected size for first two dimensions of batch2 tensor to be: [4, 1] but got: [4, 2].
def train(model, dataloader, criterion, optimizer, device):
model.train()
total_loss = 0
for src, trg in dataloader:
src, trg = src.to(device), trg.to(device)
except KeyboardInterrupt:
pass
cannon split text.split() because it is a list
After training, generate responses
print("Ready for response generation.")
while True:
prompt = input("Enter prompt: ")
response = generate_response(prompt, model, source_vocab, target_vocab, device)
print(f"Response: {response}")
The code you provided is intended to create a sequence-to-sequence model with attention in PyTorch for training on example data. However, there are a few issues and typos, I'll help you address them:
Issues & Fixes
Tokenization Error:
You are calling tokenize() on lists of sentences, which results in a list of lists. Instead, you should tokenize each individual sentence.
Vocabulary Initialization in the Interactive Loop:
You initialize the source and target vocabularies incorrectly during the interrupt signal handling. They are overwritten with an empty state {<pad>: 0, <unk>: 1} on each iteration.
Collate Function:
You should adjust the collate function to transpose the padded sequences so they could be properly fed through the LSTM.
Integrating Signal Handling:
Handling SIGINT to update datasets is complex and might not work as expected in some environments. It's useful, but not necessary if input handling is the main objective.
Incorrect Context Usage During Response Generation:
Inside the generate_response() function, model inference isn't aligned with training. Embedding context vectors properly using repeated forward passes of the decoder isn't implemented.
Here’s a corrected version of the core logic:
# Tokenize each individual sentence
source_tokens = [tokenize(sentence) for sentence in source_sentences]
target_tokens = [tokenize(sentence) for sentence in target_sentences]
# Build vocabulary with tokenized sentences
source_vocab = build_vocab(source_tokens)
target_vocab = build_vocab(target_tokens)
# Numericalize each tokenized sentence
source_numerical = numericalize(source_sentences, source_vocab)
target_numerical = numericalize(target_sentences, target_vocab)
def collate_fn(batch):
src_batch, trg_batch = zip(*batch)
src_lengths = [len(seq) for seq in src_batch]
trg_lengths = [len(seq) for seq in trg_batch]
src_padded = pad_sequence(src_batch, padding_value=source_vocab['<pad>'])
trg_padded = pad_sequence(trg_batch, padding_value=target_vocab['<pad>'])
return src_padded.t(), trg_padded.t() # Transpose for proper LSTM batch dimension
def generate_response(prompt, model, source_vocab, target_vocab, device, max_length=50):
model.eval()
with torch.no_grad():
prompt_tokens = tokenize(prompt)
prompt_numerical = [source_vocab.get(word, source_vocab['<unk>']) for word in prompt_tokens]
src_tensor = torch.tensor(prompt_numerical, dtype=torch.long).unsqueeze(0).to(device)
# Encoder forward pass
encoder_hidden, encoder_cell = model.encoder(src_tensor)
encoder_outputs, _ = model.encoder.lstm(model.encoder.embedding(src_tensor))
outputs = []
input_token = torch.tensor([target_vocab['<pad>']], dtype=torch.long).to(device)
hidden, cell = encoder_hidden, encoder_cell
for _ in range(max_length):
# Decoder forward pass for each token
output, hidden, cell = model.decoder(input_token.unsqueeze(0), hidden, cell, encoder_outputs)
predicted_token = output.argmax(2).squeeze()
outputs.append(predicted_token.item())
# Stop if end token is predicted (optional)
input_token = predicted_token
response = detokenize(outputs, target_vocab)
return response
# Training and generating responses as per your original code
Suggestions
Incremental Updates:
Consider using a more interactive approach to gather and retrain new data to adapt the model, but ensure resources are handled without conflicts (e.g., using threads, if necessary).
Hyperparameters and Advanced Features:
Explore enriched tokenizers (e.g., subword tokenization with BPE or SentencePiece) and adjust the training configuration to fit specific NLP tasks.
Key Changes
source_tokens and target_tokens: These are now lists where each element is the tokenized form of a single sentence.
Use List Comprehension: Tokenize each sentence by iterating through source_sentences and target_sentences.
This way, the function tokenize() is correctly applied to each individual sentence string instead of the whole list. The rest of the code will now work as expected, provided that sentences are processed one by one before being used further.
The error you are encountering suggests that there is a mismatch in the expected dimensions for a batch matrix multiplication (torch.bmm) in your attention mechanism. Specifically, the dimensions of weights and values do not align for a valid matrix multiplication operation.
Debugging the Attention Mechanism
Let's break down your attention mechanism to identify and fix the dimension mismatch:
Attention Score Calculation:
You concatenate the transformed query and keys matrices and calculate the attention scores.
The problem is likely in the dimensions being fed to torch.bmm.
Expected Dimensions:
weights should have dimensions [batch_size, target_len, 1].
values should have dimensions [batch_size, target_len, hidden_dim].
Fixing the Issue
Ensure weights are computed correctly and align with values:
Adjust matrix sizes to match up properly in attention calculations.
Verify that all preceding operations maintain consistent dimensions:
Check the sizes of each involved tensor during execution (manual debugging or inserted debug prints).
Here is a potential fix for your attention mechanism:
This will help verify that all tensors have compatible sizes and are processed correctly throughout the forward pass. If these prints reveal discrepancies, modify the code accordingly to address dimensionality issues.