A straightforward method for training your LLM, from downloading data to generating text.
feat: re-implement training loop
Tianyi (Alex) Qiu155af31ea04b
diff --git a/.gitignore b/.gitignoreindex ba0430d..54e6782 100644--- a/.gitignore+++ b/.gitignore@@ -1 +1,2 @@-__pycache__/\ No newline at end of file+__pycache__/+data/\ No newline at end of filediff --git a/config/config.py b/config/config.pyindex ae4bf50..4f75bb5 100644--- a/config/config.py+++ b/config/config.py@@ -2,10 +2,14 @@# Define vocabulary size and transformer configuration (3 Billion)VOCAB_SIZE = 50304 # Number of unique tokens in the vocabulary-CONTEXT_LENGTH = 512 # Maximum sequence length for the model-N_EMBED = 2048 # Dimension of the embedding space-N_HEAD = 16 # Number of attention heads in each transformer block-N_BLOCKS = 64 # Number of transformer blocks in the model+# CONTEXT_LENGTH = 512 # Maximum sequence length for the model+# N_EMBED = 2048 # Dimension of the embedding space+# N_HEAD = 16 # Number of attention heads in each transformer block+# N_BLOCKS = 64 # Number of transformer blocks in the model+CONTEXT_LENGTH = 16 # Maximum sequence length for the model+N_EMBED = 32 # Dimension of the embedding space+N_HEAD = 8 # Number of attention heads in each transformer block+N_BLOCKS = 1 # Number of transformer blocks in the model# Paths to training and development datasetsTRAIN_PATH = "data/train/pile_train.h5" # File path for the training dataset@@ -18,12 +22,14 @@ T_TRAIN_STEPS = 200000 # Total number of training stepsT_EVAL_STEPS = 1000 # Frequency (in steps) to perform evaluationT_EVAL_ITERS = 250 # Number of iterations to evaluate the modelT_LR_DECAY_STEP = 50000 # Step at which to decay the learning rate-T_LR = 5e-4 # Initial learning rate for training-T_LR_DECAYED = 5e-5 # Learning rate after decay+T_LR = 5e-5 # Initial learning rate for training+T_LR_DECAYED = 5e-6 # Learning rate after decay+T_LR_DECAY_RATE = 0.95T_OUT_PATH = "models/transformer_B.pt" # Path to save the trained model# Device configuration-DEVICE = 'cuda'+# DEVICE = 'cuda'+DEVICE = 'cpu'# Store all configurations in a dictionary for easy access and modificationdefault_config = {diff --git a/scripts/train_transformer.py b/scripts/train_transformer.pyindex 8cbb14a..ef8158a 100644--- a/scripts/train_transformer.py+++ b/scripts/train_transformer.py@@ -1,156 +1,100 @@+from data_loader.data_loader import get_batch_iterator+from src.models import Transformer+from config import config+from typing import Iterator, Literal, Tupleimport torch-import torch.nn.functional as F-import os-from tqdm import tqdmimport 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-from typing import Dict-# --- Initialize the Model and Print Parameters ---+try:+ device = torch.device(config.DEVICE)+except:+ device = torch.device('cpu')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+ text_dim=config.VOCAB_SIZE,+ ctx_len=config.CONTEXT_LENGTH,+ emb_dim=config.N_EMBED,+ num_heads=config.N_HEAD,+ num_blocks=config.N_BLOCKS,+).to(device)++criterion = torch.nn.CrossEntropyLoss()++def create_dataloader(split: Literal["train", "val"]) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:+ dataloader = get_batch_iterator(+ (config.TRAIN_PATH if split == "train" else config.DEV_PATH),+ config.T_BATCH_SIZE,+ config.CONTEXT_LENGTH,+ )+ return dataloader++train_dataloader = create_dataloader("train")+val_dataloader = create_dataloader("val")++def compute_loss(logits: torch.Tensor, gt: torch.Tensor) -> torch.Tensor:+ B, CL, VOCAB = logits.shape+ logits = torch.moveaxis(logits, 2, 1)+ assert logits.shape == (B, VOCAB, CL)+ assert gt.shape == (B, CL)++ loss = criterion(logits, gt)+ return loss-# Helper function to estimate the average loss for training and development data.@torch.no_grad()-def estimate_loss(steps: int) -> Dict[str, float]:- """- 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']+def evaluate_model(model: Transformer, num_batches: int = config.T_EVAL_ITERS, split: Literal["train", "val"] = "val") -> float:+ if split == "val":+ dataloader = val_dataloader+ else:+ dataloader = create_dataloader(split)++ losses = []+ for _ in range(num_batches):+ x, y = next(dataloader)+ assert len(x.shape) == 2 and x.shape[0] == y.shape[0]++ losses.append(+ compute_loss(+ model(x),+ y+ ).item())++ return np.mean(losses)- # 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']+model_params = model.parameters()+optimizer = torch.optim.Adam(+ model_params,+ config.T_LR,)-# 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}")+train_losses = []+eval_losses = []++for step in range(config.T_TRAIN_STEPS):+ x, y_gt = next(train_dataloader)+ logits = model(x, get_probs=False, keep_prompt_seg=True)++ optimizer.zero_grad(set_to_none=True)+ loss = compute_loss(logits, y_gt)+ train_losses.append(loss.item())+ loss.backward()+ optimizer.step()++ if step % config.T_EVAL_STEPS == 0:+ eval_loss = evaluate_model(model)+ print(f"Eval loss at step {step:7d}: {eval_loss:1.6f}")+ eval_losses.append((step, eval_loss))++ if step % config.T_LR_DECAY_STEP == 0:+ for gr in optimizer.param_groups:+ gr["lr"] *= config.T_LR_DECAY_RATE- # 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),+ "model_state": model.state_dict(),+ "optim_state": optimizer.state_dict(),+ "train_losses": train_losses,+ "eval_losses": eval_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+ config.T_OUT_PATH+)\ No newline at end of filediff --git a/src/models/attention.py b/src/models/attention.pyindex c92ce75..87f8327 100644--- a/src/models/attention.py+++ b/src/models/attention.py@@ -54,6 +54,7 @@ class MultiHeadAttn(nn.Module):dim = -1)+if __name__ == "__main__":mha = MultiHeadAttn(16, 4)x = torch.randn((5, 64, 16))