File size: 9,784 Bytes
7f1e014 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | """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,
)
@torch.no_grad()
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
|