Please modify the code to save a single model instead of saving it every epoch, and also…
- User
Please modify the code to save a single model instead of saving it every epoch, and also make the code save a json file that contains the configuration of the model as well as another txt file that contains the vocabulary of the model, code: import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from tqdm import tqdm import matplotlib.pyplot as plt import os
Define parameters and directory paths
SEQUENCE_LENGTH = 40 BATCH_SIZE = 128 VOCAB_SIZE = 192 # Number of ASCII characters considered in the vocabulary HIDDEN_SIZE = 384 NUM_LAYERS = 2 LEARNING_RATE = 0.001 NUM_EPOCHS = 10 GRAD_CLIP = 5.0 # Gradient clipping to prevent exploding gradients CHECKPOINT_FOLDER = “checkpoints” os.makedirs(CHECKPOINT_FOLDER, exist_ok=True)
Replace ‘your_file.txt’ with the path to your actual text file.
file_path = “C:/Users/Dell-PC/Desktop/The-Physics-Dataset.txt”
Read the file and filter out blank lines
with open(file_path, “r”, encoding=“utf-8”) as file: lines = file.readlines() text = “”.join(line for line in lines if not line.isspace())
Convert text to ASCII values
ascii_characters = [ord© for c in text]
Prepare datasets
inputs = [] targets = [] for i in range(0, len(ascii_characters) - SEQUENCE_LENGTH): input_seq = ascii_characters[i:i+SEQUENCE_LENGTH] target = ascii_characters[i+1:i+SEQUENCE_LENGTH+1] inputs.append(torch.tensor(input_seq, dtype=torch.long)) targets.append(torch.tensor(target, dtype=torch.long))
input_tensor = torch.stack(inputs) target_tensor = torch.stack(targets)
Load data into DataLoader for batch processing
dataset = TensorDataset(input_tensor, target_tensor) data_loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
Define the sophisticated RNN model architecture
class AdvancedRNN(nn.Module): def init(self, vocab_size, hidden_size, num_layers): super(AdvancedRNN, self).init() self.hidden_size = hidden_size self.num_layers = num_layers self.embedding = nn.Embedding(vocab_size, hidden_size) self.rnn = nn.LSTM(hidden_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, vocab_size)
def forward(self, x, hidden): x = self.embedding(x) out, hidden = self.rnn(x, hidden) out = self.fc(out.reshape(out.size(0) * out.size(1), out.size(2))) return out, hidden
def init_hidden(self, batch_size): weight = next(self.parameters()) hidden = (weight.new_zeros(self.num_layers, batch_size, self.hidden_size), weight.new_zeros(self.num_layers, batch_size, self.hidden_size)) return hidden
Initialize model, loss function, and optimizer
model = AdvancedRNN(VOCAB_SIZE, HIDDEN_SIZE, NUM_LAYERS) loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
Training loop with added production-ready features and tqdm progress
- Assistant
- User
add print statement to print total trainable parameters number
- Assistant
To print the total number of trainable parameters in the model, you can iterate through the model parameters and sum the number of elements in each parameter tensor that requires a gradient. This can be done before training starts. Here's the modified snippet that should be put right after the model is initialized:
# ... [Leave the other definitions unchanged] ... # Initialize model, loss function, and optimizer model = AdvancedRNN(VOCAB_SIZE, HIDDEN_SIZE, NUM_LAYERS) loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE) # Calculate and print the total number of trainable parameters total_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"Total trainable parameters: {total_params}") # ... [Continue with the train_model definition and the rest of the code] ... if __name__ == "__main__": # Train the model trained_model = train_model(model, data_loader, optimizer, loss_fn, NUM_EPOCHS, BATCH_SIZE) # Generate text from the trained model generate_text(trained_model, start_char="P", length=200) - User
- Assistant