import torch import torch.nn as nn from torch.utils.data import DataLoader,…
- User
import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from tqdm import tqdm import matplotlib.pyplot as plt import string import json import os
Define parameters and directory paths
DATASET_CHUNKS = 3805 # New hyperparameter to control dataset size (number of chunks) SEQUENCE_LENGTH = 60 BATCH_SIZE = 32 HIDDEN_SIZE = 768 NUM_LAYERS = 2 LEARNING_RATE = 0.001 NUM_EPOCHS = 2 GRAD_CLIP = 5.0 # Gradient clipping to prevent exploding gradients CHECKPOINT_FOLDER = "checkpoints" os.makedirs(CHECKPOINT_FOLDER, exist_ok=True) model_name = "Talk-model-1"
Replace ‘your_file.txt’ with the path to your actual text file.
file_path = "Long-Run-Talk-Cutdown.txt"
Print the start of data preparation:
print("\n--- Starting data preparation ---")
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(c) for c in text if c in string.printable[:-6]] # Make sure to include only printable characters print(f"Converted text to ASCII characters: {len(ascii_characters)} characters")
Define the total number of sequences based on the sequence length
total_num_sequences = len(ascii_characters) - SEQUENCE_LENGTH
Calculate the number of sequences to use per chunk
sequences_per_chunk = total_num_sequences // DATASET_CHUNKS
This will be the actual first dimension for the input and target tensors
usable_sequences = sequences_per_chunk * DATASET_CHUNKS
Prepare the datasets
inputs = [] targets = [] for start_idx in range(0, usable_sequences, sequences_per_chunk): for i in range(start_idx, start_idx + sequences_per_chunk): input_seq = ascii_characters[i:i+SEQUENCE_LENGTH] target_seq = ascii_characters[i+1:i+SEQUENCE_LENGTH+1] inputs.append(torch.tensor(input_seq, dtype=torch.long)) targets.append(torch.tensor(target_seq, dtype=torch.long))
input_tensor = torch.stack(inputs) target_tensor = torch.stack(targets) print(f"Created input tensor: {input_tensor.shape}") print(f"Created target tensor: {target_tensor.shape}")
Load data into DataLoader for batch processing
dataset = TensorDataset(input_tensor, target_tensor) data_loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True) print("\n--- Data preparation complete ---")
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)
- Assistant
Your script seems quite comprehensive in training a character-level RNN model on a text dataset. The script includes the following key parts:
- Parameters and directory setup.
- Data preparation by converting text from a file into ASCII values, creating input-target sequences, and splitting them into data chunks.
- User
Are the shapes as expected : --- Starting data preparation --- Converted text to ASCII characters: 4870380 characters Created input tensor: torch.Size([4866595, 60]) Created target tensor: torch.Size([4866595, 60])
--- Data preparation complete --- Total trainable parameters: 9593950
--- Starting training loop --- Epoch 1/2: 0%| | 0/152082 [00:01<?, ?it/s] Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\RNN-byte.py", line 202, in trained_model = train_model(model, data_loader, optimizer, loss_fn, NUM_EPOCHS, BATCH_SIZE, model_name) File "c:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\RNN-byte.py", line 120, in train_model output, hidden = model(input_batch, hidden) File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\RNN-byte.py", line 77, in forward x = self.embedding(x) File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\modules\sparse.py", line 162, in forward return F.embedding( File "C:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\GPT_2_Math\lib\site-packages\torch\nn\functional.py", line 2233, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) IndexError: index out of range in self
- Assistant
The shapes of your tensors appear to be correct for training a character-level RNN:
- Input tensor shape: indicates you have 4,866,595 sequences each of length 60, which makes sense as per your data preparation steps.
- User
--- Starting data preparation --- Converted text to ASCII characters: 4870380 characters Created input tensor: torch.Size([4866595, 60]) Created target tensor: torch.Size([4866595, 60])
--- Data preparation complete --- Out of vocabulary characters found: {94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126} Total trainable parameters: 9593950
- Assistant
The output you've provided indicates that your vocabulary does not include some characters (
{94, 95, ..., 126}) that are present in the ASCII ranges of 94 to 126. In Python's , these correspond to some of the higher ASCII characters including lowercase alphabets and some punctuation. - User
regenerate the last code please
- Assistant
Certainly! Here's the adjusted part of your code to include the proper
vocab_charsand to convert theascii_charactersto indices using thechar_to_indexmapping:# Generate vocabulary with all printable ASCII characters except the non-printable ones excluded_characters = "\x0b\x0c\n\r\t\x0b\x0c" # Explicitly specify which characters to exclude vocab_chars = ''.join(c for c in string.printable if c not in excluded_characters) VOCAB_SIZE = len(vocab_chars) # Update the size of the vocabulary # Map each character to a unique index char_to_index = {char: idx for idx, char in enumerate(vocab_chars)} # Convert text to indices using the char_to_index mapping ascii_indices = [char_to_index[c] for c in text if c in char_to_index] # Define the data preparation with sequences based on indices inputs = [] targets = [] for i in range(0, len(ascii_indices) - SEQUENCE_LENGTH): input_seq = ascii_indices[i:i + SEQUENCE_LENGTH] target_seq = ascii_indices[i + 1:i + SEQUENCE_LENGTH + 1] inputs.append(torch.tensor(input_seq, dtype=torch.long)) targets.append(torch.tensor(target_seq, dtype=torch.long)) input_tensor = torch.stack(inputs) target_tensor = torch.stack(targets) print(f"Created input tensor: {input_tensor.shape}") print(f"Created target tensor: {target_tensor.shape}") # Continue with your data_loader creation and the rest of your script. - User
--- Starting data preparation --- Converted text to ASCII characters: 4870380 characters Created input tensor: torch.Size([5916000, 60]) Created target tensor: torch.Size([5916000, 60])
--- Data preparation complete --- Out of vocabulary characters found: {94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126} Total trainable parameters: 9593950
- Assistant
- User
- Assistant