Download src/train.py from mlvar/tinystories-gpt-124m: direct link, hf CLI and curl.
- Browser
- Download file 9.78 kB
-
https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/train.py
- Command line
-
hf download hf://mlvar/tinystories-gpt-124m/src/train.py
-
curl -L -o train.py https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/train.py
9.78 kB
| """Training loop with mixed precision, gradient accumulation, and checkpointing.""" | |
| import math | |
| import time | |
| from pathlib import Path | |
| import torch | |
| import torch.nn.functional as F | |
| from .config import Config | |
| from .data import get_batch, load_data | |
| from .model import GPT | |
| from .tokenizer import Tokenizer | |
| from .utils import ( | |
| Logger, | |
| cleanup_checkpoints, | |
| get_lr, | |
| load_checkpoint, | |
| save_checkpoint, | |
| ) | |
| def estimate_loss( | |
| model: GPT, | |
| data: dict[str, "np.memmap"], # noqa: F821 | |
| config: Config, | |
| device: torch.device, | |
| dtype: torch.dtype, | |
| ) -> dict[str, float]: | |
| """Estimate loss on train and validation splits.""" | |
| model.eval() | |
| losses = {} | |
| for split, split_data in data.items(): | |
| total = 0.0 | |
| for _ in range(config.training.eval_iters): | |
| x, y = get_batch(split_data, config.training.micro_batch_size, config.training.seq_len, device) | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| _, loss = model(x, y) | |
| total += loss.item() | |
| losses[split] = total / config.training.eval_iters | |
| model.train() | |
| return losses | |
| def train(config: Config, resume_from: str | None = None): | |
| """Main training loop. | |
| Args: | |
| config: Config object with model and training hyperparameters. | |
| resume_from: optional path to a checkpoint to resume from. | |
| """ | |
| # ββ Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| torch.manual_seed(config.training.seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed(config.training.seed) | |
| torch.backends.cuda.matmul.allow_tf32 = True # Enable TF32 | |
| torch.set_float32_matmul_precision("high") # Enable TF32 for matmuls | |
| torch.backends.cuda.enable_flash_sdp(True) # Ensure Flash SDP is on | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| dtype = torch.bfloat16 if config.training.dtype == "bfloat16" and torch.cuda.is_bf16_supported() else torch.float32 | |
| print(f"Device: {device}") | |
| print(f"Precision: {dtype}") | |
| print(f"Flash SDP enabled: {torch.backends.cuda.flash_sdp_enabled()}") | |
| print() | |
| # ββ Data βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| train_data, val_data, train_tokens, val_tokens = load_data(config) | |
| data_splits = {"train": train_data, "val": val_data} | |
| tokens_per_step = config.training.effective_batch_size * config.training.seq_len | |
| steps_per_epoch = train_tokens // tokens_per_step | |
| print(f"Train tokens: {train_tokens:,} | Steps/epoch: ~{steps_per_epoch:,}") | |
| print() | |
| # ββ Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| model = GPT(config.model) | |
| model.to(device) | |
| # VRAM estimate | |
| vram = model.estimate_vram( | |
| config.training.micro_batch_size, config.training.seq_len | |
| ) | |
| print(f"VRAM estimate: {vram}") | |
| # torch.compile requires Triton, which only works on Linux. | |
| # Check availability and skip if not present (e.g., on Windows). | |
| _can_compile = False | |
| try: | |
| import triton # noqa: F401 | |
| _can_compile = True | |
| except ImportError: | |
| pass | |
| if _can_compile and device.type == "cuda": | |
| print("Compiling model with torch.compile (Triton available)...") | |
| model = torch.compile(model) | |
| print(" Model compiled.") | |
| else: | |
| print("torch.compile skipped (Triton not available). Running in eager mode.") | |
| # ββ Optimizer ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| optimizer = model.configure_optimizers(config.training, device) | |
| # ββ Resume βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| start_step = 0 | |
| if resume_from is not None: | |
| print(f"Resuming from {resume_from}") | |
| start_step = load_checkpoint(resume_from, model, optimizer, str(device)) | |
| print(f" Resumed at step {start_step}") | |
| # ββ Logger βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| logger = Logger(config) | |
| # Reset timer so step 0 doesn't include data loading + model init | |
| logger.step_start_time = time.time() | |
| # ββ Training loop ββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nStarting training at step {start_step} -> {config.training.max_steps}") | |
| print( | |
| f" Effective batch: {config.training.effective_batch_size} " | |
| f"({config.training.micro_batch_size} Γ {config.training.grad_accum_steps})" | |
| ) | |
| print(f" Tokens/step: {tokens_per_step:,}") | |
| print() | |
| model.train() | |
| optimizer.zero_grad() | |
| for step in range(start_step, config.training.max_steps): | |
| # ββ Learning rate update ββββββββββββββββββββββββββββββββ | |
| lr = get_lr(step, config.training) | |
| for param_group in optimizer.param_groups: | |
| param_group["lr"] = lr | |
| # ββ Gradient accumulation βββββββββββββββββββββββββββββββ | |
| accum_loss = 0.0 | |
| for micro_step in range(config.training.grad_accum_steps): | |
| x, y = get_batch( | |
| train_data, | |
| config.training.micro_batch_size, | |
| config.training.seq_len, | |
| device, | |
| ) | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| _, loss = model(x, y) | |
| # Normalize loss for gradient accumulation | |
| loss = loss / config.training.grad_accum_steps | |
| loss.backward() | |
| accum_loss += loss.item() | |
| # ββ Gradient clipping βββββββββββββββββββββββββββββββββββ | |
| if config.training.grad_clip > 0: | |
| torch.nn.utils.clip_grad_norm_( | |
| model.parameters(), config.training.grad_clip | |
| ) | |
| # ββ Optimizer step ββββββββββββββββββββββββββββββββββββββ | |
| optimizer.step() | |
| optimizer.zero_grad() | |
| # ββ Logging βββββββββββββββββββββββββββββββββββββββββββββ | |
| if step % config.training.log_interval == 0: | |
| # tokens_per_step is for one optimizer step; log_interval steps | |
| # have elapsed since the last log call, so multiply accordingly. | |
| total_tokens = tokens_per_step * config.training.log_interval | |
| logger.log_step(step, accum_loss, lr, total_tokens) | |
| # ββ Validation ββββββββββββββββββββββββββββββββββββββββββ | |
| if step % config.training.eval_interval == 0 and step > 0: | |
| losses = estimate_loss(model, data_splits, config, device, dtype) | |
| print( | |
| f" ββ eval @ step {step:>6d} ββ " | |
| + " ".join(f"{s} loss {v:.4f}" for s, v in losses.items()) | |
| ) | |
| # ββ Checkpointing βββββββββββββββββββββββββββββββββββββββ | |
| if ( | |
| config.training.checkpoint_interval > 0 | |
| and step > 0 | |
| and step % config.training.checkpoint_interval == 0 | |
| ): | |
| ckpt_path = save_checkpoint( | |
| model, optimizer, step, config, config.checkpoint_dir | |
| ) | |
| cleanup_checkpoints(config.checkpoint_dir, config.training.max_checkpoints) | |
| print(f" ββ checkpoint saved: {ckpt_path.name}") | |
| # ββ Generation ββββββββββββββββββββββββββββββββββββββββββ | |
| if ( | |
| config.training.generate_interval > 0 | |
| and step > 0 | |
| and step % config.training.generate_interval == 0 | |
| ): | |
| tokenizer = Tokenizer() | |
| prompt = "Once upon a time" | |
| input_ids = torch.tensor( | |
| [tokenizer.encode(prompt)], device=device | |
| ) | |
| output_ids = model.generate( | |
| input_ids, max_new_tokens=100, temperature=0.8, top_k=40 | |
| ) | |
| generated = tokenizer.decode(output_ids[0].tolist()) | |
| print(f" ββ generation @ step {step:>6d} ββ") | |
| print(f" {generated[:300]}") | |
| print() | |
| # ββ Final checkpoint ββββββββββββββββββββββββββββββββββββββββββββ | |
| final_path = save_checkpoint( | |
| model, optimizer, config.training.max_steps, config, config.checkpoint_dir | |
| ) | |
| print(f"Final checkpoint saved: {final_path.name}") | |
| # ββ Final stats ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| logger.finalize(config.training.max_steps) | |
| return model | |