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.
code
def forward(self, x, hidden):
"""
x in [b, l] # b is batch_size and l is sequence length
"""
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):
# TODO: Implement forward pass for a single RNN timestamp, append the hidden to the output
pass
output = torch.stack(output) # [l, b, e]
output = output.transpose(0, 1) # [b, l, e]
# TODO set these values after completing the loop above
final_hidden = None # [b, h]
logits = None # [b, l, vocab_size=v]
return logits, final_hidden
def init_hidden(self, batch_size):
return torch.zeros(batch_size, self.hidden_size).to(device)
Assistant
User
Assistant
User
Assistant
RNN implementation
Inside CharRNN.init(), you’ll need to define the learned parameters of the RNN
Your task: Randomly initialize each parameter using nn.Parameter(...), and follow the structure discussed in lecture. Keep standard deviations small (e.g., * 0.01).
Inside the forward() method:
for t in range(l):
# TODO: Implement forward pass for a single RNN timestamp
pass
Here you’ll implement the recurrence equation for the RNN. Each timestep receives:
the current input embedding x_t
the previous hidden state h_{t-1}
and outputs:
the new hidden state h_t
Your task:
Implement the RNN recurrence step
Append the computed hidden to the output list
Update h_t_minus_1 to be the computed hidden for subsequent timesteps
After the loop, compute:
final_hidden = create a clone() (deep copy) of your final hidden state to return
logits = result of projecting the full hidden sequence to the output space
To implement the CharRNN class properly, we need to define the learned parameters (weights and biases) and implement the forward pass for the RNN as per the requirements laid out. Below, I will show how to initialize the parameters in the __init__ method, and implement the RNN recurrence in the forward method.
Here's how you can complete the CharRNN class:
python
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)
# Initialize the parameters
self.W_hh = nn.Parameter(torch.randn(hidden_size, hidden_size) * 0.01) # Hidden to hidden weights
self.W_xh = nn.Parameter(torch.randn(embedding_dim, hidden_size) * 0.01) # Input to hidden weights
self.b_h = nn.Parameter(torch.zeros(hidden_size)) # Hidden bias
self.W_hy = nn.Parameter(torch.randn(hidden_size, output_size) * 0.01) # Hidden to output weights
self.b_y = nn.Parameter(torch.zeros(output_size)) # Output bias
def forward(self, x, hidden):
"""
x in [b, l] # b is batch_size and l is sequence length
"""
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):
# Get current input embedding
x_t = x_embed[t] # [b, e]
# RNN recurrence step
h_t = torch.tanh(x_t @ self.W_xh + h_t_minus_1 @ self.W_hh + self.b_h) # [b, h]
output.append(h_t)
h_t_minus_1 = h_t # Update previous hidden state
output = torch.stack(output) # [l, b, h]
output = output.transpose(0, 1) # [b, l, h]
# Compute the final hidden state as a clone
final_hidden = h_t.clone() # [b, h]
# Compute logits by projecting the hidden states to the output space
logits = output @ self.W_hy + self.b_y # [b, l, v]
return logits, final_hidden
def init_hidden(self, batch_size):
return torch.zeros(batch_size, self.hidden_size).to(device)
Explanation:
Parameter Initialization:
W_hh: This matrix is for the connections from hidden state to hidden state.
W_xh: This matrix connects the input embeddings to the hidden state.
b_h: This is the bias vector for the hidden state.
W_hy: This matrix connects hidden states to output.
b_y: This is the bias vector for the output.
Forward Pass:
The input (x) is embedded using the embedding layer.
The embeddings are processed in a loop, where the hidden state is updated at each time step based on the current input and the previous hidden state. This is achieved using the typical RNN recurrence equation:
[
h_t = \text{tanh}(x_t W_{xh} + h_{t-1} W_{hh} + b_h)
]
After calculating all hidden states, we create a final hidden state and compute logits by projecting the hidden states to the output space using the output weights and bias.
Final Outputs:
logits are the raw output scores from the RNN for each time step.
final_hidden is the last hidden state which can be used for further predictions or stateful processing.
This implementation structure aligns with the typical framework of recurrent neural networks, enabling the model to learn patterns in sequential data.
===================== 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
To debug your model you should start with a simple sequence an RNN should predict this perfectly
sequence = "abcdefghijklmnopqrstuvwxyz" * 100
sequence = read_file("warandpeace.txt") # Uncomment to read from file
vocab = sorted(set(sequence))
char_to_idx = {} # TODO: Create a mapping from characters to indices
idx_to_char = {} # TODO: Create the reverse mapping
data = [char_to_idx[char] for char in sequence]
TODO Understand and adjust the hyperparameters once the code is running
sequence_length = 1000 # Length of each input sequence
stride = 10 # Stride for creating sequences
embedding_dim = 2 # Dimension of character embeddings
hidden_size = 1 # Number of features in the hidden state of the RNN
learning_rate = 200 # Learning rate for the optimizer
num_epochs = 1 # Number of epochs to train
batch_size = 64 # Batch size for training
vocab_size = len(vocab)
input_size = len(vocab)
output_size = len(vocab)
data_tensor = torch.tensor(data, dtype=torch.long)
train_size = int(len(data_tensor) * 0.9)
#TODO: Split the data into 90:10 ratio with PyTorch indexing
train_data = None
test_data = None
for epoch in range(num_epochs):
total_loss = 0
hidden = None
for batch_inputs, batch_targets in tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
code
output, hidden = model(batch_inputs, hidden)
# Detach removes the hidden state from the computational graph.
# This is prevents backpropagating through the full history, and
# is important for stability in training RNNs
hidden = hidden.detach()
# TODO compute the loss, backpropagate gradients, and update total_loss
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
Test the model
TODO: Implement a test loop to evaluate the model on the test set
Finish the training loop, test loop, and set the hyperparameters
Now that you've finished the model you have the forward pass established, finish the backward pass of the model using the PyTorch formula from Assignment 5 and create a test loop following a similar structure (don't forget to stop computing gradients in the test loop!).
Once that's done the code should start training when you run the file. However, it will not train successfully. In order to train the model properly you will need to update the training hyperparameters. If everything is set up properly at this point you should see a model that learns to predict the alphabet with very high accuracy 98+% and very low loss (near 0).
Hyperparmeter Tuning Tips
Start with reasonable model parameters
The first thing you should do is set reasonable starting hyperparams for the model itself. This will come to understanding what each hyperparams does by understanding the architecture and the objective you're training your model to complete. Set these and keep them fixed while you tune the training hyperparameters. As long as these are close enough the model will learn. They can be further refined once you have your training is starting to learn something.
Refine learning rate
When it comes to learning hyperparameters, the most important is learning rate. Others often are just optimizations to learn faster or maximize the output of your hardware. It's useful to imagine your loss space as a large flat desert. The loss space for neural networks is often very 'flat' with small 'divots' that are optimal regions. You want a learning rate that is small enough to be able to find these divots without jumping over them. Further you also want them to be small enough to reach the bottom of the divot (although optimizers these days often change your learning rate dynamically to accomplish this). I'd recommend starting with as small a learning rate as possible, if it's too small you're not traversing the space fast enough (never finding a divot, or only moving slightly into it). If this is the case, make it progressively larger, say by a factor of 10. Eventually you'll find a "sweet spot" and your model will learn.
Refine other parameters
Now that your model is learning something you can try to optimize it further. At this point try refining the model and other learning parameters. I wouldn't recommend changing the learning rate by much maybe only a factor of 5 or less.
To complete the provided code, we will finish the training loop, implement the test loop, and address the missing hyperparameter settings. I will also provide guidance on how to adjust the hyperparameters for better learning outcomes.
Here's the complete implementation with the training and testing loops:
python
# ===================== 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
# Generate sequence for testing
sequence = "abcdefghijklmnopqrstuvwxyz" * 100
# sequence = read_file("warandpeace.txt") # Uncomment to read from file
vocab = sorted(set(sequence))
char_to_idx = {char: i for i, char in enumerate(vocab)} # Mapping from characters to indices
idx_to_char = {i: char for i, char in enumerate(vocab)} # Reverse mapping
data = [char_to_idx[char] for char in sequence]
# Hyperparameters
sequence_length = 100 # Length of each input sequence
stride = 10 # Stride for creating sequences
embedding_dim = 30 # Dimension of character embeddings
hidden_size = 128 # Number of features in the hidden state of the RNN
learning_rate = 0.001 # Learning rate for the optimizer
num_epochs = 10 # Number of epochs to train
batch_size = 64 # Batch size for training
vocab_size = len(vocab)
input_size = len(vocab)
output_size = len(vocab)
model = CharRNN(input_size, hidden_size, output_size, embedding_dim).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Prepare data
data_tensor = torch.tensor(data, dtype=torch.long)
train_size = int(len(data_tensor) * 0.9)
# Split the data into 90:10 ratio
train_data = data_tensor[:train_size]
test_data = data_tensor[train_size:]
train_dataset = CharDataset(train_data, sequence_length, stride, output_size)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True)
# Training loop
for epoch in range(num_epochs):
total_loss = 0
hidden = None
for batch_inputs, batch_targets in tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
# Forward pass
output, hidden = model(batch_inputs, hidden)
hidden = hidden.detach()
# Compute loss
loss = criterion(output.view(-1, output_size), batch_targets.view(-1))
total_loss += loss.item()
# Backpropagate gradients and update weights
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
# Test the model
model.eval() # Set the model to evaluation mode
test_inputs = test_data.unsqueeze(0) # Convert to [1, test_size]
hidden = None
predictions = []
with torch.no_grad(): # Disable gradient calculation for testing
for i in range(test_inputs.size(1) - sequence_length):
input_seq = test_inputs[:, i:i + sequence_length] # Get input sequence
output, hidden = model(input_seq, hidden)
# Use the last time step's output for making a prediction
last_output = output[:, -1, :] # Shape: [batch_size, output_size]
predicted_char_idx = torch.argmax(last_output, dim=1) # Get the predicted character indices
predictions.append(predicted_char_idx.item())
# Decode predictions to characters
predicted_chars = ''.join([idx_to_char[idx] for idx in predictions])
print("Predicted characters:", predicted_chars)
Key Additions Made:
Character Mapping: Created a mapping from characters to indices and vice versa using dictionary comprehensions.
Hyperparameters: Adjusted the model's hyperparameters:
Increased hidden_size to 128 for better capacity.
Set a reasonable learning_rate of 0.001 for stable training.
Changed sequence_length to 100 for quicker iterations, as a longer sequence might create difficulties in training convergence.
Training Loop:
Added forward and backward passes for loss computation and gradient updates.
Detached the hidden state properly to avoid backpropagating through the entire sequence history.
Testing Loop: Implemented a testing mechanism that predicts a sequence after training:
Disabled gradient calculations to ensure inference runs efficiently.
Collected predictions over the test sequence.
Tips for Tuning:
If the model is not learning: Decrease the learning rate.
If the loss is decreasing very slowly: Try increasing the learning rate slightly.
Model architecture tuning: Once the model starts learning, consider increasing the embedding dimension or hidden size further for higher capacity if needed.
Run the code above after making minor adjustments to the hyperparameters based on your observations during training. You should start seeing the model learning to predict the pattern with high accuracy on the simple sequence provided.
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):
"""
model: The trained RNN model used for character prediction.
start_text: The initial string of length n provided by the user to start the generation.
n: The length of the initial input sequence.
k: The number of additional characters to generate.
temperature: Optional
A scaling factor for randomness in predictions. Higher values (e.g., >1) make
predictions more random, while lower values (e.g., <1) make predictions more deterministic.
Default is 1.0.
"""
start_text = start_text.lower()
#TODO: Implement the rest of the generate_text function
# Hint: you will call sample_from_output() to sample a character from the logits
code
return "TODO"
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}")
Now that we've learned a model, let's use it to generate text. In this part of the assignment, your task is to implement the generate_text function, which uses a trained RNN model to generate text character-by-character, continuing from a given input. The function will produce an extended sequence by repeatedly predicting and appending the next character to the input.
generate_text(model, start_text, n, k, temperature=1.0)
Take an initial input text of length n from the user, convert it into indices using a - predefined vocabulary (char_to_idx).
Use a trained model to predict the next character in the sequence.
Append the predicted character to the input, extend the input sequence, and repeat the process until k additional characters are generated.
Return the generated text, including the original input and the newly predicted characters.
Your task: Generate text and test that you can generate an alphabet sequence from your trained model.
Enter the initial text: cde
Enter the number of characters to generate: 5
Generated text: fghijk
To implement the generate_text function, we will follow these steps:
Convert the input string into a sequence of indices using the char_to_idx mapping.
Use the trained RNN model to predict the next character one at a time, appending the predicted character to the sequence.
Repeat the prediction process for k additional characters.
Convert the generated output indices back to characters using the idx_to_char mapping and return the completed text.
Here's how you can implement this:
python
def generate_text(model, start_text, n, k, temperature=1.0):
start_text = start_text.lower()
# Convert the start_text to a tensor of indices
input_indices = torch.tensor([char_to_idx[char] for char in start_text], dtype=torch.long).unsqueeze(0).to(device) # Shape: [1, n]
# Initialize hidden state
hidden = None
generated_text = start_text # Start generating from the input text
for _ in range(k):
# Get logits from the model
logits, hidden = model(input_indices, hidden) # logits shape: [1, 1, vocab_size]
# Obtain the predictions for the last character in the sequence
last_logits = logits[:, -1, :] # This would be the logits for the last character generated, shape: [1, vocab_size]
# Sample the next character from the predicted probabilities
next_char_idx = sample_from_output(last_logits, temperature) # Next character index
next_char_idx = next_char_idx.item() # Get the integer value
# Append the predicted character to the generated text
generated_text += idx_to_char[next_char_idx]
# Prepare the input for the next character prediction
input_indices = torch.cat((input_indices, torch.tensor([[next_char_idx]], dtype=torch.long).to(device)), dim=1) # Shape: [1, n+i] where i is the current step
return generated_text
print("Training complete. Now you can generate text.")
while True:
start_text = input("Enter the initial text (n characters, or 'exit' to quit): ")
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}")
Explanation of the Code:
Input Processing: Start with the initial text provided by the user and convert it into a tensor of indices using the char_to_idx mapping. The input is reshaped to [1, n] to match the batch format expected by the model.
Character Generation Loop:
For each character that we want to generate (total k):
Call the model to get the logits for the last character in the current sequence.
Sample the next character index using the sample_from_output function, which incorporates randomness controlled by the temperature.
Update the generated text by appending the newly predicted character.
Prepare the new input for the next iteration by concatenating the newly generated index onto the input tensor.
Returning Generated Text: After generating k new characters, the complete text including the original input and newly generated characters is returned to the user.
Testing the Function:
You can now run the complete program and test the text generation. Enter a starting string, specify how many characters you'd like to generate, and adjust the temperature to see how it affects the randomness of the generated output. For instance, starting with "cde" and setting k=5 should yield a sequence that continues from "cde" with the next 5 characters predicted by the model.