import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
import re
class CharRNN(nn.Module):
def init(self, input_size, hidden_size, output_size, embedding_dim=30):
super().init()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(output_size, embedding_dim)
# TODO: Initialize your model parameters as needed e.g. W_e, W_h, etc.
self.W_h = nn.Parameter(torch.randn(hidden_size, hidden_size) * 0.01) # Hidden to hidden
self.W_x = nn.Parameter(torch.randn(embedding_dim, hidden_size) * 0.01) # Input to hidden
self.b_h = nn.Parameter(torch.zeros(hidden_size)) # Hidden bias
self.W_y = nn.Parameter(torch.randn(hidden_size, output_size) * 0.01) # Hidden to output
self.b_y = nn.Parameter(torch.zeros(output_size)) # Output bias
code
Assistant
def forward(self, x, hidden):
x_embed = self.embedding(x) # [b=batch_size, l=sequence_length, e=embedding_dim]
b, l, _ = x_embed.size()
x_embed = x_embed.transpose(0, 1) # [l, b, e]
if hidden is None:
h_t_minus_1 = self.init_hidden(b)
else:
h_t_minus_1 = hidden
output = []
for t in range(l):
x_t = x_embed[t] # Current input (embedded)
# RNN recurrence equation
h_t = torch.tanh(x_t @ self.W_x + h_t_minus_1 @ self.W_h + self.b_h) # Compute new hidden state
output.append(h_t) # Append the hidden state to output
h_t_minus_1 = h_t # Update h_{t-1} for the next timestep
output = torch.stack(output) # [l, b, h]
output = output.transpose(0, 1) # [b, l, h]
# Compute final hidden and logits
final_hidden = h_t # [b, h]
logits = output @ self.W_y + self.b_y # Project hidden states to vocab size, [b, l, vocab_size]
return logits, final_hidden
def init_hidden(self, batch_size):
return torch.zeros(batch_size, self.hidden_size).to(device)
===================== Training =====================
device = 'cpu'
print(f"Using device: {device}")
def read_file(filename):
with open(filename, "r", encoding="utf-8") as file:
text = file.read().lower()
text = re.sub(r'[^a-z.,!?;:()[] ]+', '', text)
return text
For debugging
Uncomment this line to read from warandpeace.txt
sequence = read_file("warandpeace.txt") # Read the contents of the text file
vocab = sorted(set(sequence))
char_to_idx = {char: idx for idx, char in enumerate(vocab)} # Create a mapping from characters to indices
idx_to_char = {idx: char for idx, char in enumerate(vocab)} # Create the reverse mapping
data = [char_to_idx[char] for char in sequence]
Hyperparameters
sequence_length = 200 # Reduced for demonstration/testing
stride = 1 # Adjusted to simplify and ensure we get enough training examples
embedding_dim = 256 # Keep the embedding dimension
hidden_size = 512 # Hidden layer size
learning_rate = 0.0005 # Learning rate
num_epochs = 50 # Number of training epochs
batch_size = 64 # Batch size
vocab_size = len(vocab)
# Test loop
model.eval() # Set the model to evaluation mode
hidden = None
total_test_loss = 0
with torch.no_grad(): # Disable gradient computation
for batch_inputs, batch_targets in tqdm(test_loader, desc="Testing"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
output, hidden = model(batch_inputs, hidden)
loss = criterion(output.view(-1, output.size(-1)), batch_targets.view(-1))
total_test_loss += loss.item()
print(f"Test Loss: {total_test_loss/len(test_loader):.4f}")
else:
print("No test data available for evaluation.")
===================== Text Generation =====================
def sample_from_output(logits, temperature=1.0):
"""
Sample from the logits with temperature scaling.
logits: Tensor of shape [batch_size, vocab_size] (raw scores, before softmax)
temperature: a float controlling the randomness (higher = more random)
"""
if temperature <= 0:
temperature = 0.00000001
# Apply temperature scaling to logits (increase randomness with higher values)
scaled_logits = logits / temperature
# Apply softmax to convert logits to probabilities
probabilities = F.softmax(scaled_logits, dim=1)
code
# Sample from the probability distribution
sampled_idx = torch.multinomial(probabilities, 1)
return sampled_idx
def generate_text(model, start_text, n, k, temperature=1.0):
"""
Generate text using the trained RNN model.
"""
model.eval()
start_text = start_text.lower()
code
# Convert input text to indices
start_indices = torch.tensor([char_to_idx[char] for char in start_text], dtype=torch.long).unsqueeze(0).to(device) # Shape: [1, n]
generated = start_text
hidden = None
# Generate k characters
for _ in range(k):
output, hidden = model(start_indices, hidden)
logits = output[:, -1, :] # Get the last time step logits
next_char_idx = sample_from_output(logits, temperature) # Sample the next character
# next_char_idx has shape [1, 1], and we need it to have shape [1]. To resolve this:
next_char_idx = next_char_idx.squeeze(0) # Squeeze to shape [1]
# Append the predicted character to the generated text
generated += idx_to_char[next_char_idx.item()] # next_char_idx is now [1]
# Update start_indices to include the newly predicted char
start_indices = torch.cat((start_indices, next_char_idx.view(1, -1)), dim=1) # Shape: [1, n+1]
return generated
print("Training complete. Now you can generate text.")
while True:
start_text = input("Enter the initial text (n characters, or 'exit' to quit): ")
code
if start_text.lower() == 'exit':
print("Exiting...")
break
n = len(start_text)
k = int(input("Enter the number of characters to generate: "))
temperature_input = input("Enter the temperature value (1.0 is default, >1 is more random): ")
temperature = float(temperature_input) if temperature_input else 1.0
completed_text = generate_text(model, start_text, n, k, temperature)
print(f"Generated text: {completed_text}")
this gives results like:
PS C:\Users<redacted>\OneDrive\Documents\GitHub\assignment-7-neural-complete- & C:/Users//AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users//OneDrive/Documents/GitHub/assignment-7-neural-complete-/rnn_complete.py
Using device: cpu
Training data size: 2807969
Test data size: 311997
Testing: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4871/4871 [02:17<00:00, 35.51it/s]
Test Loss: 3.6111
Training complete. Now you can generate text.
Enter the initial text (n characters, or 'exit' to quit): hello
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 1
Generated text: hellonnpcdbvyqe
Enter the initial text (n characters, or 'exit' to quit): war
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0.7
Generated text: warmgg:em,umw
Enter the initial text (n characters, or 'exit' to quit): peace
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0.7
Generated text: peacekjmw cergc
Enter the initial text (n characters, or 'exit' to quit): what is your name
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0.7
Generated text: what is your name(itjf].xpv
Enter the initial text (n characters, or 'exit' to quit): what is war
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 2
Generated text: what is war;bsiw)htv]
Enter the initial text (n characters, or 'exit' to quit): hello
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0.1
Generated text: hellowy?g.]oerd
Enter the initial text (n characters, or 'exit' to quit): is there
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0.01
Generated text: is therenkwjisd,z:
Enter the initial text (n characters, or 'exit' to quit): what is it
Enter the number of characters to generate: 0
Enter the temperature value (1.0 is default, >1 is more random): 10
Generated text: what is it
Enter the initial text (n characters, or 'exit' to quit): what is it
Enter the number of characters to generate: 10
Enter the temperature value (1.0 is default, >1 is more random): 0
Generated text: what is itkndml![ifk
Enter the initial text (n characters, or 'exit' to quit):
It looks like you have successfully set up a character-level RNN for text generation using PyTorch. The output generated by your model seems to show a mix of coherence and randomness, which is typical for RNNs, especially when generating sequences based on learned distributions of characters.
To improve or adjust the text generation behavior, here are a few considerations and potential modifications you might want to explore:
Temperature:
Your implementation allows the user to adjust the temperature during text generation. Higher temperatures (e.g., >1.0) increase randomness, while lower temperatures (<1.0) make the output more deterministic. You can invite users to experiment with different values of temperature to see how it affects the generated text.
Training:
The quality of text generation heavily depends on the training process. Here are a few suggestions:
More Training Epochs: If you have the time and computational power, increase the number of training epochs. This often helps the network learn better representations of the language.
Learning Rate Tuning: You might want to experiment with different learning rates or use learning rate scheduling to improve training.
Data Augmentation: Depending on the dataset, you might also consider sampling more diverse training examples or employing methods to augment the dataset.
Model Architecture:
Since you are using a fairly basic RNN architecture, you might consider using more advanced architectures like LSTM (Long Short-Term Memory) or GRU (Gated Recurrent Unit), which can capture longer dependencies in sequences better than vanilla RNNs.
Sequence Length:
Adjusting the sequence length, depending on the context dependencies you want to capture, can also be worthwhile. In certain cases, longer sequences might allow the model to learn better contextual relationships.
Data Preprocessing:
Examine your text preprocessing step. Currently, you only keep certain punctuation marks and spaces. You might need to modify these rules based on the expected style or domain of generated text.
Evaluation Metrics:
After training, consider leveraging different metrics to evaluate the quality of generated text. Consider metrics like BLEU, ROUGE, or perplexity, especially in line with your intended application of the model.
Batch Normalization and Dropout:
If you encounter issues with overfitting, implementing dropout layers or batch normalization in the model can be beneficial to improve generalization.
Character Set:
The choice of characters (vocabulary) can greatly affect how coherent the output is. If your application allows, consider expanding or constraining the character set based on your training corpus.
Sample Output Review:
Periodically reviewing samples generated during different training stages can help you understand how the model is learning. It can also inform adjustments to the training regime or architecture.
Logging and Checkpointing:
Implementing logging of loss values and saving model checkpoints at regular intervals can help you monitor your model's performance over time and retrieve the best model without the need for retraining in case of suboptimal runs.
Keep iterating on your model, and good luck with your text generation project! If you have specific goals for the text generation (like a particular style or coherence), you may need to target your training process and architecture accordingly.