Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

training scripts

FareedKhan-dev2d7b8f0b126a
diff --git a/scripts/data_download.py b/scripts/data_download.py
new file mode 100644
index 0000000..a95537d
--- /dev/null
+++ b/scripts/data_download.py
@@ -0,0 +1,80 @@
+import os
+import argparse
+import requests
+from tqdm import tqdm
+
+# Base URL for the dataset files
+BASE_URL = "https://huggingface.co/datasets/monology/pile-uncopyrighted/resolve/main"
+VAL_URL = f"{BASE_URL}/val.jsonl.zst" # URL for the validation dataset
+TRAIN_URLS = [f"{BASE_URL}/train/{i:02d}.jsonl.zst" for i in range(65)] # URLs for 65 training files (adjust the range if needed)
+
+def download_file(url, file_name):
+ """
+ Downloads a file from the given URL and saves it with the specified file name.
+ Displays a progress bar using tqdm.
+
+ Args:
+ url (str): The URL of the file to download.
+ file_name (str): The local path where the file will be saved.
+ """
+ print(f"Downloading: {file_name}...")
+ response = requests.get(url, stream=True) # Stream the file content
+ total_size = int(response.headers.get('content-length', 0)) # Get total file size if available
+ block_size = 1024 # Size of each block for the progress bar
+ with open(file_name, 'wb') as f: # Open file for writing in binary mode
+ for chunk in tqdm(response.iter_content(block_size), total=total_size // block_size, desc="Downloading", leave=True):
+ f.write(chunk) # Write each chunk to the file
+
+def download_dataset(val_url, train_urls, val_dir, train_dir, max_train_files):
+ """
+ Manages downloading of the dataset, including both validation and training files.
+
+ Args:
+ val_url (str): URL for the validation dataset.
+ train_urls (list): List of URLs for the training dataset files.
+ val_dir (str): Directory where the validation file will be stored.
+ train_dir (str): Directory where the training files will be stored.
+ max_train_files (int): Maximum number of training files to download.
+ """
+ # Define the path for the validation file
+ val_file_path = os.path.join(val_dir, "val.jsonl.zst")
+ if not os.path.exists(val_file_path): # Check if the validation file already exists
+ print(f"Validation file not found. Downloading from {val_url}...")
+ download_file(val_url, val_file_path) # Download the validation file
+ else:
+ print("Validation data already present. Skipping download.")
+
+ # Loop through the training file URLs and download if not already present
+ for idx, url in enumerate(train_urls[:max_train_files]): # Limit to max_train_files
+ file_name = f"{idx:02d}.jsonl.zst" # Format file name (e.g., 00.jsonl.zst)
+ file_path = os.path.join(train_dir, file_name) # Construct the full file path
+ if not os.path.exists(file_path): # Check if the file already exists
+ print(f"Training file {file_name} not found. Downloading...")
+ download_file(url, file_path) # Download the training file
+ else:
+ print(f"Training file {file_name} already present. Skipping download.")
+
+def main():
+ """
+ Main function to parse arguments and orchestrate the dataset download process.
+ """
+ # Parse command-line arguments using argparse
+ parser = argparse.ArgumentParser(description="Download PILE dataset.") # Description of the script
+ parser.add_argument('--train_max', type=int, default=1, help="Max number of training files to download.") # Max training files
+ parser.add_argument('--train_dir', default="data/train", help="Directory for storing training data.") # Training directory
+ parser.add_argument('--val_dir', default="data/val", help="Directory for storing validation data.") # Validation directory
+
+ args = parser.parse_args() # Parse the arguments provided by the user
+
+ # Ensure directories for training and validation data exist
+ os.makedirs(args.train_dir, exist_ok=True) # Create training directory if it doesn't exist
+ os.makedirs(args.val_dir, exist_ok=True) # Create validation directory if it doesn't exist
+
+ # Start downloading the dataset
+ download_dataset(VAL_URL, TRAIN_URLS, args.val_dir, args.train_dir, args.train_max)
+
+ print("Dataset downloaded successfully.") # Indicate successful download
+
+if __name__ == "__main__":
+ # Entry point of the script
+ main()
\ No newline at end of file
diff --git a/scripts/data_preprocess.py b/scripts/data_preprocess.py
new file mode 100644
index 0000000..e6541d7
--- /dev/null
+++ b/scripts/data_preprocess.py
@@ -0,0 +1,115 @@
+import os
+import json
+import zstandard as zstd
+import tiktoken
+import h5py
+from tqdm import tqdm
+import argparse
+
+def process_files(input_dir, output_file, tokenizer_name, max_data=None):
+ """
+ Process a specified number of lines from each .jsonl.zst file in the input directory
+ and save encoded tokens to an HDF5 file.
+
+ Args:
+ input_dir (str): Directory containing input .jsonl.zst files.
+ output_file (str): Path to the output HDF5 file.
+ tokenizer_name (str): Name of the tiktoken tokenizer to use (e.g., 'r50k_base').
+ max_data (int, optional): Maximum number of lines to process from each file.
+ If None, process all lines.
+ """
+ # Print processing strategy based on max_data
+ if max_data is not None:
+ print(f"You have chosen max_data = {max_data}. Processing only the top {max_data} JSON objects from each file.")
+ else:
+ print("Processing all available JSON objects from each file.")
+
+ # Load the tokenizer using the provided tokenizer name
+ enc = tiktoken.get_encoding(tokenizer_name)
+
+ # Create an HDF5 file for output
+ with h5py.File(output_file, 'w') as out_f:
+ # Initialize the dataset for storing tokenized data
+ dataset = out_f.create_dataset('tokens', (0,), maxshape=(None,), dtype='i')
+ start_index = 0 # Track the starting index for the next batch of tokens
+
+ # Process each .jsonl.zst file in the input directory
+ for filename in sorted(os.listdir(input_dir)):
+ if filename.endswith(".jsonl.zst"): # Only process .jsonl.zst files
+ in_file = os.path.join(input_dir, filename)
+ print(f"Processing: {in_file}")
+
+ processed_lines = 0 # Counter for processed lines in the current file
+
+ # Open the compressed .jsonl.zst file for reading
+ with zstd.open(in_file, 'rt', encoding='utf-8') as in_f:
+ # Iterate over each line in the file
+ for line in tqdm(in_f, desc=f"Processing {filename}", total=max_data if max_data is not None else None):
+ try:
+ # Parse the line as JSON
+ data = json.loads(line)
+ text = data.get('text') # Extract the 'text' field from the JSON object
+
+ if text:
+ # Tokenize the text and append an end-of-text token
+ encoded = enc.encode(text + "<|endoftext|>", allowed_special={'<|endoftext|>'})
+ encoded_len = len(encoded)
+
+ # Resize the dataset to accommodate new tokens
+ end_index = start_index + encoded_len
+ dataset.resize(dataset.shape[0] + encoded_len, axis=0)
+
+ # Store the encoded tokens in the dataset
+ dataset[start_index:end_index] = encoded
+ start_index = end_index # Update the start index
+ else:
+ # Warn if 'text' key is missing in the JSON object
+ print(f"Warning: 'text' key missing in line from {filename}")
+ except json.JSONDecodeError:
+ # Handle JSON decoding errors
+ print(f"Warning: Could not decode JSON from line in {filename}")
+ except Exception as e:
+ # Handle any other errors
+ print(f"An error occurred while processing line in {filename}: {e}")
+
+ processed_lines += 1
+ # Stop processing if max_data limit is reached
+ if max_data is not None and processed_lines >= max_data:
+ break
+
+def main():
+ """
+ Main function to parse arguments, validate directories, and process files.
+ """
+ # Parse command-line arguments
+ parser = argparse.ArgumentParser(description="Preprocess PILE dataset files and save tokens to HDF5.")
+ parser.add_argument("--train_dir", type=str, default="data/train", help="Directory containing training .jsonl.zst files.")
+ parser.add_argument("--val_dir", type=str, default="data/val", help="Directory containing validation .jsonl.zst files.")
+ parser.add_argument("--out_train_file", type=str, default="data/train/pile_train.h5", help="Path to the output training HDF5 file.")
+ parser.add_argument("--out_val_file", type=str, default="data/val/pile_dev.h5", help="Path to the output validation HDF5 file.")
+ parser.add_argument("--tokenizer_name", type=str, default="r50k_base", help="Name of the tiktoken tokenizer to use.")
+ parser.add_argument("--max_data", type=int, default=1000, help="Maximum number of json objects to process from each file in both train and val datasets (default: 1000).")
+
+ args = parser.parse_args()
+
+ # Validate the existence of the training and validation directories
+ if not os.path.isdir(args.train_dir):
+ print(f"Error: Training directory not found: {args.train_dir}")
+ return
+ if not os.path.isdir(args.val_dir):
+ print(f"Error: Validation directory not found: {args.val_dir}")
+ return
+
+ # Process training data
+ print("Starting training data preprocessing...")
+ process_files(args.train_dir, args.out_train_file, args.tokenizer_name, args.max_data)
+ print("Training data preprocessing complete.")
+
+ # Process validation data
+ print("Starting validation data preprocessing...")
+ process_files(args.val_dir, args.out_val_file, args.tokenizer_name, args.max_data)
+ print("Validation data preprocessing complete.")
+
+# Entry point of the script
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/scripts/generate_text.py b/scripts/generate_text.py
new file mode 100644
index 0000000..51d0625
--- /dev/null
+++ b/scripts/generate_text.py
@@ -0,0 +1,61 @@
+import torch
+import tiktoken
+import argparse
+from config.config import default_config as config
+from src.models.transformer import Transformer # Assuming your Transformer class is in this module
+
+def generate_text(model_path, input_text, max_new_tokens=100, device='cuda'):
+ """
+ Generates text using a pre-trained Transformer model.
+
+ Args:
+ model_path (str): Path to the saved model checkpoint.
+ input_text (str): The initial text to start generation from.
+ max_new_tokens (int): The maximum number of new tokens to generate.
+ device (str): 'cuda' or 'cpu', the device to run the model on.
+
+ Returns:
+ str: The generated text.
+ """
+ # Load the model checkpoint
+ checkpoint = torch.load(model_path, map_location=torch.device(device))
+
+ # Initialize the model using the configuration from config.py
+ model = Transformer(
+ n_head=config['n_head'],
+ n_embed=config['n_embed'],
+ context_length=config['context_length'],
+ vocab_size=config['vocab_size'],
+ N_BLOCKS=config['n_blocks']
+ )
+ model.load_state_dict(checkpoint['model_state_dict'])
+ model.eval().to(device)
+
+ # Load the tokenizer
+ enc = tiktoken.get_encoding("r50k_base")
+
+ start_ids = enc.encode_ordinary(input_text)
+ context = torch.tensor(start_ids, dtype=torch.long, device=device).unsqueeze(0)
+
+ # Generation process
+ with torch.no_grad():
+ generated_tokens = model.generate(context, max_new_tokens=max_new_tokens)[0].tolist()
+
+ # Decode the generated tokens
+ output_text = enc.decode(generated_tokens)
+
+ return output_text
+
+def main():
+ parser = argparse.ArgumentParser(description="Generate text using a pre-trained Transformer model.")
+ parser.add_argument('--model_path', type=str, help='Path to the saved model checkpoint.')
+ parser.add_argument('--input_text', type=str, help='The initial text to start generation from.')
+ parser.add_argument('--max_new_tokens', type=int, default=100, help='Maximum number of new tokens to generate.')
+
+ args = parser.parse_args()
+
+ generated = generate_text(args.model_path, args.input_text, args.max_new_tokens)
+ print(f"Generated text:\n{generated}")
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/scripts/train_transformer.py b/scripts/train_transformer.py
new file mode 100644
index 0000000..d1341de
--- /dev/null
+++ b/scripts/train_transformer.py
@@ -0,0 +1,155 @@
+import torch
+import torch.nn.functional as F
+import os
+from tqdm import tqdm
+import numpy as np
+from config.config import default_config as config
+from src.models.transformer import Transformer
+from data_loader.data_loader import get_batch_iterator
+
+# --- Initialize the Model and Print Parameters ---
+
+model = Transformer(
+ n_head=config['n_head'],
+ n_embed=config['n_embed'],
+ context_length=config['context_length'],
+ vocab_size=config['vocab_size'],
+ N_BLOCKS=config['n_blocks']
+).to(config['device'])
+
+# Print the total number of parameters
+total_params = sum(p.numel() for p in model.parameters())
+print(f"Total number of parameters in the model: {total_params:,}")
+
+# --- Optimizer Setup and Loss Tracking ---
+
+# Set up the AdamW optimizer with the specified learning rate.
+optimizer = torch.optim.AdamW(model.parameters(), lr=config['t_lr'])
+
+# List to track loss values during training.
+losses = []
+
+# Define a window size for averaging recent losses in the training loop.
+AVG_WINDOW = 64
+
+# Helper function to estimate the average loss for training and development data.
+def estimate_loss(steps):
+ """
+ Evaluate the model on training and development datasets and calculate average loss.
+
+ Args:
+ steps (int): Number of steps to evaluate.
+
+ Returns:
+ dict: Dictionary containing average losses for 'train' and 'dev' splits.
+ """
+ out = {}
+ model.eval() # Set the model to evaluation mode.
+
+ for split in ['train', 'dev']:
+ # Select the appropriate data path for the current split.
+ data_path = config['train_path'] if split == 'train' else config['dev_path']
+
+ # Create a batch iterator for evaluation.
+ batch_iterator_eval = get_batch_iterator(
+ data_path, config['t_batch_size'], config['t_context_length'], device=config['device']
+ )
+
+ # Initialize a tensor to track loss values for each evaluation step.
+ losses_eval = torch.zeros(steps)
+ for k in range(steps):
+ try:
+ # Fetch a batch and calculate the loss.
+ xb, yb = next(batch_iterator_eval)
+ _, loss = model(xb, yb)
+ losses_eval[k] = loss.item()
+ except StopIteration:
+ # Handle the case where the data iterator ends early.
+ print(f"Warning: Iterator for {split} ended early.")
+ break
+
+ # Compute the mean loss for the current split.
+ out[split] = losses_eval[:k + 1].mean()
+
+ model.train() # Restore the model to training mode.
+ return out
+
+# --- Training Loop ---
+
+# Create a batch iterator for the training data.
+batch_iterator = get_batch_iterator(
+ config['train_path'],
+ config['t_batch_size'],
+ config['t_context_length'],
+ device=config['device']
+)
+
+# Create a progress bar to monitor training progress.
+pbar = tqdm(range(config['t_train_steps']))
+for step in pbar:
+ try:
+ # Fetch a batch of input and target data.
+ xb, yb = next(batch_iterator)
+
+ # Perform a forward pass and compute the loss.
+ _, loss = model(xb, yb)
+
+ # Record the loss for tracking.
+ losses.append(loss.item())
+ pbar.set_description(f"Train loss: {np.mean(losses[-AVG_WINDOW:]):.4f}")
+
+ # Backpropagate the loss and update the model parameters.
+ optimizer.zero_grad(set_to_none=True)
+ loss.backward()
+ optimizer.step()
+
+ # Periodically evaluate the model on training and development data.
+ if step % config['t_eval_steps'] == 0:
+ evaluation_losses = estimate_loss(config['t_eval_iters'])
+ train_loss = evaluation_losses['train']
+ dev_loss = evaluation_losses['dev']
+ print(f"Step: {step}, Train loss: {train_loss:.4f}, Dev loss: {dev_loss:.4f}")
+
+ # Decay the learning rate at the specified step.
+ if step == config['t_lr_decay_step']:
+ print('Decaying learning rate')
+ for g in optimizer.param_groups:
+ g['lr'] = config['t_lr_decayed']
+ except StopIteration:
+ # Handle the case where the training data iterator ends early.
+ print("Training data iterator finished early.")
+ break
+
+# --- Save Model and Final Evaluation ---
+
+# Create the output directory if it does not exist.
+os.makedirs(config['t_out_path'].split('/')[0], exist_ok=True)
+
+# Perform a final evaluation of the model on training and development datasets.
+evaluation_losses = estimate_loss(200)
+train_loss = evaluation_losses['train']
+dev_loss = evaluation_losses['dev']
+
+# Ensure unique model save path in case the file already exists.
+modified_model_out_path = config['t_out_path']
+save_tries = 0
+while os.path.exists(modified_model_out_path):
+ save_tries += 1
+ model_out_name = os.path.splitext(config['t_out_path'])[0]
+ modified_model_out_path = model_out_name + f"_{save_tries}" + ".pt"
+
+# Save the model's state dictionary, optimizer state, and training metadata.
+torch.save(
+ {
+ 'model_state_dict': model.state_dict(),
+ 'optimizer_state_dict': optimizer.state_dict(),
+ 'losses': losses,
+ 'train_loss': train_loss,
+ 'dev_loss': dev_loss,
+ 'steps': len(losses),
+ },
+ modified_model_out_path
+)
+print(f"Saved model to {modified_model_out_path}")
+print(f"Finished training. Train loss: {train_loss:.4f}, Dev loss: {dev_loss:.4f}")
\ No newline at end of file