Skip to content

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

Harden checkpoint writes and restore Python 3.9 typing compatibility in legacy trainer (#28)

Copilotefb92340f655
diff --git a/README.md b/README.md
index 2fff884..dd2c268 100644
--- a/README.md
+++ b/README.md
@@ -261,6 +261,19 @@ python scripts/train_transformer.py
It will start training the model and save the trained model in the `models/` default directory or the directory specified in the configuration file.
+For long runs, you can save periodic checkpoints and resume after an interruption:
+```bash
+python scripts/train_transformer.py --checkpoint-every 1000 --keep-last 3
+
+# Resume from the newest checkpoint in the default checkpoint directory
+python scripts/train_transformer.py --resume latest
+
+# Or resume from a specific checkpoint
+python scripts/train_transformer.py --resume models/transformer_B_checkpoints/checkpoint_step_00000999.pt
+```
+
+The periodic checkpoints include the model state, optimizer state, loss history, last completed training step, and learning-rate metadata.
+
To generate text using the trained model, run:
```bash
python scripts/generate_text.py --model_path models/your_model.pth --input_text hi
diff --git a/config/config.py b/config/config.py
index 015b731..b9ba4f6 100644
--- a/config/config.py
+++ b/config/config.py
@@ -23,6 +23,9 @@ T_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_OUT_PATH = "models/transformer_B.pt" # Path to save the trained model
+T_CHECKPOINT_STEPS = 0 # Save periodic checkpoints every N steps (0 disables)
+T_KEEP_LAST_CHECKPOINTS = 3 # Number of periodic checkpoints to keep (0 keeps all)
+T_CHECKPOINT_DIR = None # Optional checkpoint directory override
# Device configuration
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
@@ -45,5 +48,8 @@ default_config = {
't_lr': T_LR,
't_lr_decayed': T_LR_DECAYED,
't_out_path': T_OUT_PATH,
+ 't_checkpoint_steps': T_CHECKPOINT_STEPS,
+ 't_keep_last_checkpoints': T_KEEP_LAST_CHECKPOINTS,
+ 't_checkpoint_dir': T_CHECKPOINT_DIR,
'device': DEVICE,
}
diff --git a/scripts/train_transformer.py b/scripts/train_transformer.py
index 0e2cd18..3655ce3 100644
--- a/scripts/train_transformer.py
+++ b/scripts/train_transformer.py
@@ -1,13 +1,24 @@
-import torch
-import torch.nn.functional as F
+from __future__ import annotations
+
+import argparse
import os
+import re
+import sys
+import tempfile
import time
-from tqdm import tqdm
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
import numpy as np
+import torch
+from tqdm import tqdm
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+if str(ROOT_DIR) not in sys.path:
+ sys.path.insert(0, str(ROOT_DIR))
+
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
# --- Runtime Diagnostics Helpers ---
@@ -57,43 +68,219 @@ def get_peak_memory_report(device: str) -> str:
return "Peak VRAM allocated: N/A | Peak VRAM reserved: N/A"
-# --- Initialize the Model and Print Parameters ---
+# --- Checkpoint Helpers ---
-# Print runtime/device diagnostics and reset GPU peak-memory stats before training.
-print(get_device_report(config['device']))
-if config['device'].startswith('cuda') and torch.cuda.is_available():
- torch.cuda.reset_peak_memory_stats()
+CHECKPOINT_RE = re.compile(r"checkpoint_step_(\d+)\.pt$")
-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:,}")
+def load_checkpoint_file(path: str, device: str) -> Dict[str, Any]:
+ """Load a checkpoint while supporting both newer and older PyTorch versions."""
+ try:
+ return torch.load(path, map_location=torch.device(device), weights_only=False)
+ except TypeError:
+ return torch.load(path, map_location=torch.device(device))
+
+
+def default_checkpoint_dir(out_path: str) -> str:
+ """Return a checkpoint directory tied to the configured final model path."""
+ model_path = Path(out_path)
+ return str(model_path.with_suffix("")) + "_checkpoints"
+
-# --- Optimizer Setup and Loss Tracking ---
+def checkpoint_path(checkpoint_dir: str, step: int) -> str:
+ """Build a stable checkpoint path for the last completed training step."""
+ return os.path.join(checkpoint_dir, f"checkpoint_step_{step:08d}.pt")
-# 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 = []
+def checkpoint_step(path: str) -> int:
+ """Extract the step number from a checkpoint filename."""
+ match = CHECKPOINT_RE.search(os.path.basename(path))
+ if not match:
+ return -1
+ return int(match.group(1))
+
+
+def list_checkpoints(checkpoint_dir: str) -> List[str]:
+ """Return periodic checkpoints sorted by training step."""
+ if not os.path.isdir(checkpoint_dir):
+ return []
+ paths = [
+ os.path.join(checkpoint_dir, name)
+ for name in os.listdir(checkpoint_dir)
+ if CHECKPOINT_RE.search(name)
+ ]
+ return sorted(paths, key=checkpoint_step)
-# 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 resolve_resume_path(resume: Optional[str], checkpoint_dir: str) -> Optional[str]:
+ """
+ Resolve a resume argument.
+
+ ``--resume`` with no value uses the latest periodic checkpoint in checkpoint_dir.
+ ``--resume path/to/file.pt`` loads that exact checkpoint.
+ """
+ if resume is None:
+ return None
+ if resume == "latest":
+ checkpoints = list_checkpoints(checkpoint_dir)
+ if not checkpoints:
+ raise FileNotFoundError(f"No checkpoints found in {checkpoint_dir}")
+ return checkpoints[-1]
+ return resume
+
+
+def current_lr(optimizer: torch.optim.Optimizer) -> float:
+ """Read the learning rate from the first optimizer parameter group."""
+ return float(optimizer.param_groups[0]["lr"])
+
+
+def lr_for_step(train_config: Dict[str, Any], step: int) -> float:
+ """Return the learning rate that should be active at a given step."""
+ if step > train_config['t_lr_decay_step']:
+ return float(train_config['t_lr_decayed'])
+ return float(train_config['t_lr'])
+
+
+def set_optimizer_lr(optimizer: torch.optim.Optimizer, lr: float) -> None:
+ """Set all optimizer parameter groups to the same learning rate."""
+ for group in optimizer.param_groups:
+ group["lr"] = lr
+
+
+def save_training_checkpoint(
+ path: str,
+ model: Transformer,
+ optimizer: torch.optim.Optimizer,
+ train_config: Dict[str, Any],
+ losses: List[float],
+ *,
+ step: int,
+ train_loss: Optional[float] = None,
+ dev_loss: Optional[float] = None,
+ is_final: bool = False,
+) -> None:
+ """
+ Save model, optimizer, loss history, and LR schedule metadata.
+
+ ``step`` is the last completed zero-based training step, so resume starts at
+ ``step + 1``.
+ """
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ payload = {
+ 'model_state_dict': model.state_dict(),
+ 'optimizer_state_dict': optimizer.state_dict(),
+ 'losses': losses,
+ 'train_loss': train_loss,
+ 'dev_loss': dev_loss,
+ 'step': step,
+ 'last_completed_step': step,
+ 'steps': step + 1,
+ 'is_final': is_final,
+ 'config': dict(train_config),
+ 'device': train_config['device'],
+ 'pytorch_version': torch.__version__,
+ 'cuda_version': torch.version.cuda,
+ 'lr_state': {
+ 'current_lr': current_lr(optimizer),
+ 'initial_lr': train_config['t_lr'],
+ 'decayed_lr': train_config['t_lr_decayed'],
+ 'decay_step': train_config['t_lr_decay_step'],
+ },
+ }
+ target_dir = os.path.dirname(path) or "."
+ with tempfile.NamedTemporaryFile(
+ dir=target_dir,
+ prefix=f".{os.path.basename(path)}.",
+ suffix=".tmp",
+ delete=False,
+ ) as tmp_file:
+ tmp_path = tmp_file.name
+ try:
+ torch.save(payload, tmp_path)
+ os.replace(tmp_path, path)
+ except Exception:
+ if os.path.exists(tmp_path):
+ os.remove(tmp_path)
+ raise
+
+
+def restore_training_checkpoint(
+ path: str,
+ model: Transformer,
+ optimizer: torch.optim.Optimizer,
+ train_config: Dict[str, Any],
+ device: str,
+) -> Tuple[int, List[float]]:
+ """
+ Restore model/optimizer state and return ``(next_step, losses)``.
+
+ Older checkpoints did not have ``last_completed_step``. For those, ``steps``
+ is treated as the number of completed optimizer steps.
+ """
+ checkpoint = load_checkpoint_file(path, device)
+ model.load_state_dict(checkpoint['model_state_dict'])
+
+ optimizer_state = checkpoint.get('optimizer_state_dict')
+ if optimizer_state:
+ optimizer.load_state_dict(optimizer_state)
+
+ if 'last_completed_step' in checkpoint:
+ last_completed_step = int(checkpoint['last_completed_step'])
+ next_step = last_completed_step + 1
+ else:
+ next_step = int(checkpoint.get('steps', 0))
+ last_completed_step = next_step - 1
+
+ if not optimizer_state:
+ set_optimizer_lr(optimizer, lr_for_step(train_config, next_step))
+
+ losses = [float(loss) for loss in checkpoint.get('losses', [])]
+ print(
+ f"Resumed from {path}. "
+ f"Last completed step: {last_completed_step}. Next step: {next_step}."
+ )
+ return next_step, losses
+
+
+def prune_old_checkpoints(checkpoint_dir: str, keep_last: int) -> None:
+ """Keep only the most recent N periodic checkpoints when requested."""
+ if keep_last <= 0:
+ return
+ checkpoints = list_checkpoints(checkpoint_dir)
+ for old_path in checkpoints[:-keep_last]:
+ os.remove(old_path)
+
+
+def unique_output_path(out_path: str) -> str:
+ """Avoid overwriting an existing final model checkpoint."""
+ modified_model_out_path = out_path
+ save_tries = 0
+ while os.path.exists(modified_model_out_path):
+ save_tries += 1
+ model_out_name = os.path.splitext(out_path)[0]
+ modified_model_out_path = model_out_name + f"_{save_tries}" + ".pt"
+ return modified_model_out_path
+
+
+def as_float(value: Any) -> Optional[float]:
+ """Convert scalar tensors/numbers to plain floats for checkpoint metadata."""
+ if value is None:
+ return None
+ if hasattr(value, "item"):
+ return float(value.item())
+ return float(value)
+
+
+# --- Training / Evaluation ---
+
@torch.no_grad()
-def estimate_loss(steps: int) -> Dict[str, float]:
+def estimate_loss(model: Transformer, train_config: Dict[str, Any], steps: int) -> Dict[str, float]:
"""
Evaluate the model on training and development datasets and calculate average loss.
Args:
+ model (Transformer): The model being trained.
+ train_config (dict): Training configuration values.
steps (int): Number of steps to evaluate.
Returns:
@@ -101,137 +288,248 @@ def estimate_loss(steps: int) -> Dict[str, float]:
"""
out = {}
model.eval() # Set the model to evaluation mode.
+ from data_loader.data_loader import get_batch_iterator
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']
+ data_path = train_config['train_path'] if split == 'train' else train_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']
+ data_path,
+ train_config['t_batch_size'],
+ train_config['t_context_length'],
+ device=train_config['device'],
)
- # Initialize a tensor to track loss values for each evaluation step.
- losses_eval = torch.zeros(steps)
- for k in range(steps):
+ # Track loss values for each evaluation step.
+ losses_eval = []
+ for _ 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()
+ losses_eval.append(float(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()
+ out[split] = float(np.mean(losses_eval)) if losses_eval else float("nan")
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']
-)
-# Number of tokens processed per step (batch_size * context_length), used for throughput.
-tokens_per_step = config['t_batch_size'] * config['t_context_length']
-last_eval_time = time.perf_counter()
-
-# 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 (and start the step timer).
- step_start_time = time.perf_counter()
- 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()
-
- # Clip gradients to prevent exploding gradients.
- torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
-
- optimizer.step()
-
- # Measure step time and instantaneous throughput for diagnostics.
- step_time = time.perf_counter() - step_start_time
- tokens_per_second = tokens_per_step / step_time if step_time > 0 else float('inf')
-
- # 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']
- # Report timing/throughput for the most recent step and wall-time since last eval.
- now = time.perf_counter()
- elapsed_since_eval = now - last_eval_time
- last_eval_time = now
- print(
- f"Step: {step}, Train loss: {train_loss:.4f}, Dev loss: {dev_loss:.4f}, "
- f"Step time: {step_time:.3f}s, Throughput: {tokens_per_second:.2f} tokens/s, "
- f"Elapsed since last eval: {elapsed_since_eval:.2f}s"
- )
- print(get_peak_memory_report(config['device']))
-
- # 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
-# (including the runtime device / PyTorch / CUDA versions for reproducibility).
-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),
- 'device': config['device'],
- 'pytorch_version': torch.__version__,
- 'cuda_version': torch.version.cuda,
- },
- modified_model_out_path
-)
-print(f"Saved model to {modified_model_out_path}")
-print(get_peak_memory_report(config['device']))
-print(f"Finished training. Train loss: {train_loss:.4f}, Dev loss: {dev_loss:.4f}")
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Train the Transformer model from scratch.")
+ parser.add_argument(
+ "--resume",
+ nargs="?",
+ const="latest",
+ default=None,
+ help=(
+ "Resume from a checkpoint path. Pass --resume with no value, or "
+ "--resume latest, to use the newest checkpoint in the checkpoint directory."
+ ),
+ )
+ parser.add_argument(
+ "--checkpoint-every",
+ type=int,
+ default=None,
+ help="Save a periodic checkpoint every N completed steps. 0 disables periodic checkpoints.",
+ )
+ parser.add_argument(
+ "--checkpoint-dir",
+ type=str,
+ default=None,
+ help="Directory for periodic checkpoints. Defaults to a directory next to t_out_path.",
+ )
+ parser.add_argument(
+ "--keep-last",
+ type=int,
+ default=None,
+ help="Keep only the most recent N periodic checkpoints. 0 keeps all.",
+ )
+ return parser.parse_args()
+
+
+def main() -> None:
+ args = parse_args()
+ train_config = dict(config)
+ checkpoint_every = (
+ args.checkpoint_every
+ if args.checkpoint_every is not None
+ else train_config.get('t_checkpoint_steps', 0)
+ )
+ keep_last = (
+ args.keep_last
+ if args.keep_last is not None
+ else train_config.get('t_keep_last_checkpoints', 0)
+ )
+ checkpoint_dir = (
+ args.checkpoint_dir
+ or train_config.get('t_checkpoint_dir')
+ or default_checkpoint_dir(train_config['t_out_path'])
+ )
+
+ # --- Initialize the Model and Print Parameters ---
+
+ # Print runtime/device diagnostics and reset GPU peak-memory stats before training.
+ print(get_device_report(train_config['device']))
+ if train_config['device'].startswith('cuda') and torch.cuda.is_available():
+ torch.cuda.reset_peak_memory_stats()
+
+ model = Transformer(
+ n_head=train_config['n_head'],
+ n_embed=train_config['n_embed'],
+ context_length=train_config['context_length'],
+ vocab_size=train_config['vocab_size'],
+ N_BLOCKS=train_config['n_blocks'],
+ ).to(train_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=train_config['t_lr'])
+
+ # List to track loss values during training.
+ losses: List[float] = []
+ start_step = 0
+ last_completed_step = -1
+ resume_path = resolve_resume_path(args.resume, checkpoint_dir)
+ if resume_path is not None:
+ start_step, losses = restore_training_checkpoint(
+ resume_path,
+ model,
+ optimizer,
+ train_config,
+ train_config['device'],
+ )
+ last_completed_step = start_step - 1
+
+ # Define a window size for averaging recent losses in the training loop.
+ avg_window = 64
+
+ # --- Training Loop ---
+
+ from data_loader.data_loader import get_batch_iterator
+
+ # Create a batch iterator for the training data.
+ batch_iterator = get_batch_iterator(
+ train_config['train_path'],
+ train_config['t_batch_size'],
+ train_config['t_context_length'],
+ device=train_config['device'],
+ )
+
+ # Number of tokens processed per step (batch_size * context_length), used for throughput.
+ tokens_per_step = train_config['t_batch_size'] * train_config['t_context_length']
+ last_eval_time = time.perf_counter()
+ latest_train_loss = None
+ latest_dev_loss = None
+
+ # Create a progress bar to monitor training progress.
+ pbar = tqdm(range(start_step, train_config['t_train_steps']))
+ for step in pbar:
+ try:
+ # Fetch a batch of input and target data (and start the step timer).
+ step_start_time = time.perf_counter()
+ xb, yb = next(batch_iterator)
+
+ # Perform a forward pass and compute the loss.
+ _, loss = model(xb, yb)
+
+ # Record the loss for tracking.
+ losses.append(float(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()
+
+ # Clip gradients to prevent exploding gradients.
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
+
+ optimizer.step()
+ last_completed_step = step
+
+ # Measure step time and instantaneous throughput for diagnostics.
+ step_time = time.perf_counter() - step_start_time
+ tokens_per_second = tokens_per_step / step_time if step_time > 0 else float('inf')
+
+ # Periodically evaluate the model on training and development data.
+ if step % train_config['t_eval_steps'] == 0:
+ evaluation_losses = estimate_loss(model, train_config, train_config['t_eval_iters'])
+ latest_train_loss = evaluation_losses['train']
+ latest_dev_loss = evaluation_losses['dev']
+ # Report timing/throughput for the most recent step and wall-time since last eval.
+ now = time.perf_counter()
+ elapsed_since_eval = now - last_eval_time
+ last_eval_time = now
+ print(
+ f"Step: {step}, Train loss: {latest_train_loss:.4f}, Dev loss: {latest_dev_loss:.4f}, "
+ f"Step time: {step_time:.3f}s, Throughput: {tokens_per_second:.2f} tokens/s, "
+ f"Elapsed since last eval: {elapsed_since_eval:.2f}s"
+ )
+ print(get_peak_memory_report(train_config['device']))
+
+ # Decay the learning rate at the specified step.
+ if step == train_config['t_lr_decay_step']:
+ print('Decaying learning rate')
+ set_optimizer_lr(optimizer, train_config['t_lr_decayed'])
+
+ if checkpoint_every and checkpoint_every > 0 and (step + 1) % checkpoint_every == 0:
+ path = checkpoint_path(checkpoint_dir, step)
+ save_training_checkpoint(
+ path,
+ model,
+ optimizer,
+ train_config,
+ losses,
+ step=step,
+ train_loss=as_float(latest_train_loss),
+ dev_loss=as_float(latest_dev_loss),
+ )
+ prune_old_checkpoints(checkpoint_dir, int(keep_last or 0))
+ print(f"Saved checkpoint to {path}")
+ except StopIteration:
+ # Handle the case where the training data iterator ends early.
+ print("Training data iterator finished early.")
+ break
+
+ # --- Save Model and Final Evaluation ---
+
+ # Perform a final evaluation of the model on training and development datasets.
+ evaluation_losses = estimate_loss(model, train_config, 200)
+ train_loss = evaluation_losses['train']
+ dev_loss = evaluation_losses['dev']
+
+ final_step = max(last_completed_step, start_step - 1)
+ modified_model_out_path = unique_output_path(train_config['t_out_path'])
+
+ # Save the model's state dictionary, optimizer state, and training metadata
+ # (including the runtime device / PyTorch / CUDA versions for reproducibility).
+ save_training_checkpoint(
+ modified_model_out_path,
+ model,
+ optimizer,
+ train_config,
+ losses,
+ step=final_step,
+ train_loss=train_loss,
+ dev_loss=dev_loss,
+ is_final=True,
+ )
+ print(f"Saved model to {modified_model_out_path}")
+ print(get_peak_memory_report(train_config['device']))
+ print(f"Finished training. Train loss: {train_loss:.4f}, Dev loss: {dev_loss:.4f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/models/transformer.py b/src/models/transformer.py
index b8b8877..91fc7b7 100644
--- a/src/models/transformer.py
+++ b/src/models/transformer.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
import torch.nn.functional as F
@@ -151,4 +153,4 @@ if __name__ == '__main__':
# Example of generating tokens
start_indices = input_indices[:, :1] # Take the first token of each sequence as start
generated_tokens = transformer_model.generate(start_indices, max_new_tokens=5)
- print("Generated Tokens Shape:", generated_tokens.shape)
\ No newline at end of file
+ print("Generated Tokens Shape:", generated_tokens.shape)
diff --git a/tests/test_checkpoint_resume.py b/tests/test_checkpoint_resume.py
new file mode 100644
index 0000000..7344613
--- /dev/null
+++ b/tests/test_checkpoint_resume.py
@@ -0,0 +1,102 @@
+"""
+Regression tests for the legacy pretraining checkpoint/resume helpers.
+
+Run from the repo root:
+ PYTHONPATH=. python tests/test_checkpoint_resume.py
+"""
+
+from __future__ import annotations
+
+import tempfile
+import os
+from unittest import mock
+
+import torch
+
+from scripts.train_transformer import (
+ checkpoint_path,
+ list_checkpoints,
+ resolve_resume_path,
+ restore_training_checkpoint,
+ save_training_checkpoint,
+ prune_old_checkpoints,
+)
+from src.models.transformer import Transformer
+
+
+def _tiny_model():
+ torch.manual_seed(0)
+ return Transformer(n_head=2, n_embed=8, context_length=8, vocab_size=32, N_BLOCKS=1)
+
+
+def _tiny_config():
+ return {
+ "t_lr": 1e-3,
+ "t_lr_decayed": 1e-4,
+ "t_lr_decay_step": 10,
+ "device": "cpu",
+ }
+
+
+def test_checkpoint_round_trip_and_latest_resume():
+ cfg = _tiny_config()
+ model = _tiny_model()
+ optimizer = torch.optim.AdamW(model.parameters(), lr=cfg["t_lr"])
+
+ # Populate optimizer state so the round trip proves optimizer resume works too.
+ idx = torch.randint(0, 32, (2, 4))
+ _, loss = model(idx, idx)
+ loss.backward()
+ optimizer.step()
+
+ losses = [3.0, 2.0, 1.0]
+ with tempfile.TemporaryDirectory() as tmp:
+ first = checkpoint_path(tmp, 2)
+ second = checkpoint_path(tmp, 3)
+ save_training_checkpoint(first, model, optimizer, cfg, losses, step=2)
+ save_training_checkpoint(second, model, optimizer, cfg, losses + [0.5], step=3)
+ prune_old_checkpoints(tmp, keep_last=1)
+
+ remaining = list_checkpoints(tmp)
+ assert remaining == [second]
+ assert resolve_resume_path("latest", tmp) == second
+
+ restored = _tiny_model()
+ restored_optim = torch.optim.AdamW(restored.parameters(), lr=cfg["t_lr"])
+ next_step, restored_losses = restore_training_checkpoint(
+ second,
+ restored,
+ restored_optim,
+ cfg,
+ "cpu",
+ )
+
+ assert next_step == 4
+ assert restored_losses == losses + [0.5]
+ assert restored_optim.state_dict()["state"]
+ for original, loaded in zip(model.parameters(), restored.parameters()):
+ assert torch.allclose(original, loaded)
+
+
+def test_checkpoint_save_failure_does_not_leave_partial_file():
+ cfg = _tiny_config()
+ model = _tiny_model()
+ optimizer = torch.optim.AdamW(model.parameters(), lr=cfg["t_lr"])
+
+ with tempfile.TemporaryDirectory() as tmp:
+ target = checkpoint_path(tmp, 7)
+ with mock.patch("scripts.train_transformer.torch.save", side_effect=RuntimeError("boom")):
+ try:
+ save_training_checkpoint(target, model, optimizer, cfg, [1.0], step=7)
+ assert False, "save_training_checkpoint should re-raise save errors"
+ except RuntimeError:
+ pass
+
+ assert not os.path.exists(target)
+ assert not [name for name in os.listdir(tmp) if name.endswith(".tmp")]
+
+
+if __name__ == "__main__":
+ test_checkpoint_round_trip_and_latest_resume()
+ test_checkpoint_save_failure_does_not_leave_partial_file()
+ print("ALL CHECKPOINT RESUME TESTS PASSED")