Download src/utils.py from mlvar/tinystories-gpt-124m: direct link, hf CLI and curl.
- Browser
- Download file 6.53 kB
-
https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/utils.py
- Command line
-
hf download hf://mlvar/tinystories-gpt-124m/src/utils.py
-
curl -L -o utils.py https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/utils.py
6.53 kB
| """Training utilities: LR schedule, checkpointing, logging.""" | |
| import math | |
| import os | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| from .config import Config, TrainingConfig | |
| # ββ Learning Rate Schedule ββββββββββββββββββββββββββββββββββββββββββββ | |
| def get_lr(step: int, config: TrainingConfig) -> float: | |
| """Cosine decay with linear warmup. | |
| Returns the learning rate at step `step`. | |
| """ | |
| # Linear warmup | |
| if step < config.warmup_steps: | |
| return config.peak_lr * (step + 1) / config.warmup_steps | |
| # After max_steps, hold at min_lr | |
| if step >= config.max_steps: | |
| return config.min_lr | |
| # Cosine decay from peak_lr to min_lr | |
| decay_steps = config.max_steps - config.warmup_steps | |
| decay_ratio = (step - config.warmup_steps) / decay_steps | |
| assert 0.0 <= decay_ratio <= 1.0 | |
| coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) | |
| return config.min_lr + coeff * (config.peak_lr - config.min_lr) | |
| # ββ Checkpointing βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def save_checkpoint( | |
| model: torch.nn.Module, | |
| optimizer: torch.optim.Optimizer, | |
| step: int, | |
| config: Config, | |
| checkpoint_dir: str | Path, | |
| ) -> Path: | |
| """Save a training checkpoint. | |
| Saves model state, optimizer state, step, config, and RNG states. | |
| Uses .tmp suffix to avoid corruption from interrupted writes. | |
| """ | |
| checkpoint_dir = Path(checkpoint_dir) | |
| checkpoint_dir.mkdir(parents=True, exist_ok=True) | |
| checkpoint_path = checkpoint_dir / f"step_{step:06d}.pt" | |
| tmp_path = checkpoint_dir / f"step_{step:06d}.pt.tmp" | |
| # Gather state | |
| state = { | |
| "model": model.state_dict(), | |
| "optimizer": optimizer.state_dict(), | |
| "step": step, | |
| "config": config, | |
| "rng_state": torch.get_rng_state(), | |
| } | |
| if torch.cuda.is_available(): | |
| state["cuda_rng_state"] = torch.cuda.get_rng_state() | |
| # Write to temp file first, then rename (atomic-ish on same filesystem) | |
| torch.save(state, tmp_path) | |
| os.replace(tmp_path, checkpoint_path) | |
| return checkpoint_path | |
| def load_checkpoint( | |
| path: str | Path, | |
| model: torch.nn.Module, | |
| optimizer: torch.optim.Optimizer | None = None, | |
| map_location: str = "cuda", | |
| ) -> int: | |
| """Load a training checkpoint. Returns the step number.""" | |
| checkpoint = torch.load(str(path), map_location=map_location, weights_only=False) | |
| model.load_state_dict(checkpoint["model"]) | |
| if optimizer is not None and "optimizer" in checkpoint: | |
| optimizer.load_state_dict(checkpoint["optimizer"]) | |
| # Restore RNG state (non-critical; skip if format is incompatible) | |
| try: | |
| if "rng_state" in checkpoint: | |
| torch.set_rng_state(checkpoint["rng_state"]) | |
| if "cuda_rng_state" in checkpoint and torch.cuda.is_available(): | |
| torch.cuda.set_rng_state(checkpoint["cuda_rng_state"]) | |
| except (TypeError, RuntimeError) as e: | |
| print(f" Warning: could not restore RNG state ({e}), continuing anyway.") | |
| return checkpoint["step"] | |
| def cleanup_checkpoints(checkpoint_dir: str | Path, max_keep: int) -> None: | |
| """Remove old checkpoints, keeping only the `max_keep` most recent.""" | |
| if max_keep <= 0: | |
| return | |
| checkpoint_dir = Path(checkpoint_dir) | |
| checkpoints = sorted( | |
| checkpoint_dir.glob("step_*.pt"), | |
| key=lambda p: p.stat().st_mtime, | |
| reverse=True, | |
| ) | |
| for cp in checkpoints[max_keep:]: | |
| cp.unlink() | |
| # ββ Logging ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class Logger: | |
| """Simple console logger with timing and optional TensorBoard support.""" | |
| def __init__(self, config: Config, use_tensorboard: bool = False): | |
| self.config = config | |
| self.start_time = time.time() | |
| self.step_start_time = time.time() | |
| self.tokens_processed = 0 | |
| self.writer = None | |
| if use_tensorboard: | |
| try: | |
| from torch.utils.tensorboard import SummaryWriter | |
| self.writer = SummaryWriter(log_dir="runs") | |
| print("TensorBoard logging enabled (runs/)") | |
| except ImportError: | |
| print("TensorBoard not installed, skipping.") | |
| def log_step( | |
| self, | |
| step: int, | |
| train_loss: float, | |
| lr: float, | |
| tokens_per_step: int, | |
| val_loss: float | None = None, | |
| ): | |
| """Log a training step to console and optionally TensorBoard.""" | |
| elapsed = time.time() - self.start_time | |
| step_time = time.time() - self.step_start_time | |
| self.tokens_processed += tokens_per_step | |
| tokens_per_sec = tokens_per_step / step_time if step_time > 0 else 0 | |
| vals = [ | |
| f"step {step:>6d}/{self.config.training.max_steps}", | |
| f"loss {train_loss:.4f}", | |
| f"lr {lr:.2e}", | |
| f"tok/s {tokens_per_sec:,.0f}", | |
| f"elapsed {elapsed/60:.1f}m", | |
| ] | |
| if val_loss is not None: | |
| vals.insert(2, f"val {val_loss:.4f}") | |
| print(" | ".join(vals)) | |
| if self.writer is not None: | |
| self.writer.add_scalar("train/loss", train_loss, step) | |
| self.writer.add_scalar("train/lr", lr, step) | |
| self.writer.add_scalar("train/tokens_per_sec", tokens_per_sec, step) | |
| if val_loss is not None: | |
| self.writer.add_scalar("val/loss", val_loss, step) | |
| self.step_start_time = time.time() | |
| def finalize(self, step: int) -> dict[str, Any]: | |
| """Print final stats and close writer.""" | |
| total_time = time.time() - self.start_time | |
| tokens_per_sec = ( | |
| self.tokens_processed / total_time if total_time > 0 else 0 | |
| ) | |
| stats = { | |
| "total_steps": step, | |
| "total_time_minutes": round(total_time / 60, 1), | |
| "tokens_processed": self.tokens_processed, | |
| "tokens_per_sec": round(tokens_per_sec, 1), | |
| } | |
| print(f"\nTraining complete!") | |
| print(f" Total time: {total_time/60:.1f} min") | |
| print(f" Average throughput: {tokens_per_sec:,.0f} tok/s") | |
| if self.writer is not None: | |
| self.writer.close() | |
| return stats | |