Explain impact of changing temperature: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_e = nn.Parameter(torch.randn(embedding_dim, self.hidden_size) * 0.01)
self.W_h = nn.Parameter(torch.randn(self.hidden_size, self.hidden_size) * 0.01)
self.b_h = nn.Parameter(torch.zeros(self.hidden_size))
self.W_out = nn.Parameter(torch.randn(self.hidden_size, output_size) * 0.01)
self.b_out = nn.Parameter(torch.zeros(output_size))
code
Assistant
User
give me this answer as a small paragraph to put in my report
Assistant
The temperature parameter in text generation controls the randomness and diversity of the outputs produced by a model. A low temperature (< 1.0) sharpens the probability distribution of predicted next characters, resulting in more deterministic and coherent text that closely follows patterns in the training data. Conversely, a high temperature (> 1.0) softens this distribution, allowing less probable characters to be selected, which can lead to more creative but potentially incoherent outputs. By adjusting the temperature, users can tailor the generation process to achieve a desired balance between coherence and creativity, enhancing the overall quality of the generated text.
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
h_t = torch.tanh(x_embed[t] @ self.W_e + h_t_minus_1 @ self.W_h + self.b_h)
output.append(h_t)
h_t_minus_1 = h_t
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 = h_t_minus_1.clone() # [b, h]
logits = output @ self.W_out + self.b_out # [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)
===================== Training =====================
device = 'cuda'
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 = {char: idx for idx, char in enumerate(vocab)} # TODO: Create a mapping from characters to indices
idx_to_char = {idx: char for idx, char in enumerate(vocab)} # 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 = 100 # Length of each input sequence
stride = 1 # Stride for creating sequences
embedding_dim = 256 # Dimension of character embeddings
hidden_size = 512 # Number of features in the hidden state of the RNN
learning_rate = 5e-4 # 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 = data_tensor[:train_size]
test_data = data_tensor[train_size:]
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
optimizer.zero_grad() # Zero the gradients from the previous step
loss = criterion(output.view(-1, output_size), batch_targets.view(-1)) # Compute the loss
loss.backward() # Backpropagate the gradients
optimizer.step() # Update the model parameters
total_loss += loss.item() # Accumulate the 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
model.eval() # Set the model to evaluation mode
test_loss = 0
correct_predictions = 0
total_predictions = 0
hidden = None
with torch.no_grad(): # Disable gradient computation for testing
for batch_inputs, batch_targets in tqdm(test_loader, desc="Testing and Calculating Correctness"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
===================== 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):
"""
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
generated_text = start_text
input_sequence = torch.tensor([char_to_idx[char] for char in start_text], dtype=torch.long).unsqueeze(0).to(device)
hidden = None
code
for _ in range(k):
logits, hidden = model(input_sequence, hidden)
next_char_idx = sample_from_output(logits[:, -1, :], temperature).item()
next_char = idx_to_char[next_char_idx]
generated_text += next_char
# Update the input sequence by appending the new character and keeping the last n characters
input_sequence = torch.cat([input_sequence, torch.tensor([[next_char_idx]], dtype=torch.long).to(device)], dim=1)
input_sequence = input_sequence[:, -n:]
return generated_text[generated_text.index(start_text) + len(start_text):]
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}")
In the provided code and context, the "temperature" refers to a parameter used during the text generation phase of the model. It affects the randomness and diversity of the outputs generated by the model when sampling from the predicted probability distribution of the next character. Let's break down the concept of temperature further and its impact on the generated text.
Temperature in Text Generation
Definition:
Temperature is a scalar that modifies the logits (raw outputs) from the model before they are converted to probabilities using the softmax function.
Effects of Changing Temperature:
Low Temperature (< 1.0):
When the temperature is set to a value less than 1.0, the logits are divided by a smaller number, resulting in a sharper probability distribution after applying softmax.
This leads to more deterministic and confident predictions. The model is more likely to choose characters that have higher probabilities, resulting in outputs that stay closer to patterns from the training data.
Example: You might get coherent text when the temperature is low, but it may lack creativity or variability.
High Temperature (> 1.0):
Increasing the temperature makes the logits larger relative to their scale. This results in a softer probability distribution.
It allows less probable characters to have a better chance of being selected, leading to more randomness in the output. The generated text may include unexpected or novel combinations of characters.
High temperature can enhance creativity in text generation but might produce incoherent or nonsensical outputs in some cases.
Extreme Cases:
Temperature = 0:
This would essentially make predictions completely deterministic, resulting in always selecting the character with the highest probability (maximum likelihood). However, the code protects against this case by ensuring it doesn’t allow temperature to reach zero, as that would lead to division by zero.
High Temperatures (e.g., 10.0):
Very high temperatures can yield outputs that are almost completely random. The generated text may bear little resemblance to coherent language.
Practical Example in the Code
In the provided code snippet, the sampling process takes into account the specified temperature:
With different values for the temperature parameter, you can observe different styles of text generation when you input initial text and request subsequent character predictions.
Conclusion
The temperature parameter serves as a powerful tool for controlling the trade-off between randomness and coherence in text generation. It allows you to tailor the output to your specific needs: whether you desire more predictable, coherent text or creative and varied results. Users can experiment with different temperature values to find the right balance for their purposes.