Download train.py from Valeztiro/Micro-llm: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/Valeztiro/Micro-llm/resolve/main/train.py
- Command line
-
hf download hf://Valeztiro/Micro-llm/train.py
-
curl -L -o train.py https://huggingface.co/Valeztiro/Micro-llm/resolve/main/train.py
17.6 kB
| """Train the 20M GPT on uint16 memmap token files.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| from datetime import datetime | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from tokenizers import Tokenizer | |
| from tqdm import tqdm | |
| from model import GPT, GPTConfig | |
| END_OF_TEXT = "<|endoftext|>" | |
| DEFAULT_LR = 6e-4 | |
| PROJECT_DIR = Path(__file__).resolve().parent | |
| class MemmapBatchLoader: | |
| def __init__( | |
| self, | |
| path: Path, | |
| batch_size: int, | |
| sequence_length: int, | |
| device: torch.device, | |
| additional_path: Path | None = None, | |
| additional_probability: float = 0.0, | |
| ) -> None: | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"Token file not found: {path}; run prepare_data.py first") | |
| self.data = np.memmap(path, dtype=np.uint16, mode="r") | |
| if len(self.data) < sequence_length + 2: | |
| raise ValueError(f"{path} needs at least {sequence_length + 2} tokens") | |
| self.batch_size = batch_size | |
| self.sequence_length = sequence_length | |
| self.device = device | |
| self.additional_data = None | |
| self.additional_probability = additional_probability | |
| if additional_path is not None: | |
| if not additional_path.is_file(): | |
| raise FileNotFoundError(f"Additional token file not found: {additional_path}") | |
| self.additional_data = np.memmap(additional_path, dtype=np.uint16, mode="r") | |
| if len(self.additional_data) < sequence_length + 2: | |
| raise ValueError(f"{additional_path} needs at least {sequence_length + 2} tokens") | |
| def next_batch(self) -> tuple[torch.Tensor, torch.Tensor]: | |
| positions = np.arange(self.sequence_length + 1) | |
| if self.additional_data is None or self.additional_probability <= 0: | |
| max_start = len(self.data) - self.sequence_length - 1 | |
| starts = np.random.randint(0, max_start + 1, size=self.batch_size) | |
| rows = self.data[starts[:, None] + positions].astype(np.int64) | |
| batch = torch.from_numpy(rows) | |
| return batch[:, :-1].to(self.device), batch[:, 1:].to(self.device) | |
| rows = np.empty( | |
| (self.batch_size, self.sequence_length + 1), dtype=np.int64 | |
| ) | |
| use_additional = np.zeros(self.batch_size, dtype=np.bool_) | |
| if self.additional_data is not None and self.additional_probability > 0: | |
| use_additional = np.random.random(self.batch_size) < self.additional_probability | |
| positions = np.arange(self.sequence_length + 1) | |
| for data, selected_rows in ( | |
| (self.data, np.flatnonzero(~use_additional)), | |
| (self.additional_data, np.flatnonzero(use_additional)), | |
| ): | |
| if data is None or selected_rows.size == 0: | |
| continue | |
| max_start = len(data) - self.sequence_length - 1 | |
| starts = np.random.randint(0, max_start + 1, size=selected_rows.size) | |
| rows[selected_rows] = data[starts[:, None] + positions] | |
| batch = torch.from_numpy(rows) | |
| return batch[:, :-1].to(self.device), batch[:, 1:].to(self.device) | |
| def learning_rate(step: int, warmup_steps: int, total_steps: int, min_lr: float) -> float: | |
| if warmup_steps > 0 and step < warmup_steps: | |
| return DEFAULT_LR * (step + 1) / warmup_steps | |
| progress = min(max((step - warmup_steps) / max(total_steps - warmup_steps, 1), 0.0), 1.0) | |
| return min_lr + 0.5 * (DEFAULT_LR - min_lr) * (1.0 + math.cos(math.pi * progress)) | |
| def make_masked_batch( | |
| input_ids: torch.Tensor, | |
| mask_token_id: int, | |
| vocab_size: int, | |
| mask_probability: float = 0.15, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| selected = torch.rand(input_ids.shape, device=input_ids.device) < mask_probability | |
| empty_rows = ~selected.any(dim=1) | |
| if empty_rows.any(): | |
| rows = empty_rows.nonzero(as_tuple=True)[0] | |
| columns = torch.randint(input_ids.size(1), (len(rows),), device=input_ids.device) | |
| selected[rows, columns] = True | |
| labels = input_ids.masked_fill(~selected, -100) | |
| corrupted = input_ids.clone() | |
| replacement_choice = torch.rand(input_ids.shape, device=input_ids.device) | |
| mask_positions = selected & (replacement_choice < 0.8) | |
| random_positions = selected & (replacement_choice >= 0.8) & (replacement_choice < 0.9) | |
| corrupted[mask_positions] = mask_token_id | |
| corrupted[random_positions] = torch.randint( | |
| vocab_size, (int(random_positions.sum().item()),), device=input_ids.device | |
| ) | |
| return corrupted, labels | |
| def make_optimizer(model: GPT, weight_decay: float) -> torch.optim.Optimizer: | |
| decay: list[torch.Tensor] = [] | |
| no_decay: list[torch.Tensor] = [] | |
| for parameter in model.parameters(): | |
| if not parameter.requires_grad: | |
| continue | |
| if parameter.ndim >= 2: | |
| decay.append(parameter) | |
| else: | |
| no_decay.append(parameter) | |
| return torch.optim.AdamW( | |
| [ | |
| {"params": decay, "weight_decay": weight_decay}, | |
| {"params": no_decay, "weight_decay": 0.0}, | |
| ], | |
| lr=DEFAULT_LR, | |
| betas=(0.9, 0.95), | |
| fused=next(model.parameters()).is_cuda, | |
| ) | |
| def autocast_context(device: torch.device): | |
| return torch.autocast( | |
| device_type=device.type, | |
| dtype=torch.float16, | |
| enabled=device.type == "cuda", | |
| ) | |
| def estimate_loss( | |
| model: GPT, | |
| loader: MemmapBatchLoader, | |
| device: torch.device, | |
| iterations: int, | |
| ) -> float: | |
| model.eval() | |
| losses = torch.empty(iterations, device="cpu") | |
| for index in range(iterations): | |
| inputs, targets = loader.next_batch() | |
| with autocast_context(device): | |
| _, loss = model(inputs, targets) | |
| losses[index] = loss.item() | |
| model.train() | |
| return losses.mean().item() | |
| def save_checkpoint( | |
| path: Path, | |
| model: GPT, | |
| optimizer: torch.optim.Optimizer, | |
| scaler: torch.cuda.amp.GradScaler, | |
| step: int, | |
| best_val_loss: float, | |
| ) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary_path = path.with_suffix(path.suffix + ".tmp") | |
| torch.save( | |
| { | |
| "model": model.state_dict(), | |
| "optimizer": optimizer.state_dict(), | |
| "scaler": scaler.state_dict(), | |
| "step": step, | |
| "best_val_loss": best_val_loss, | |
| "config": model.config.to_dict(), | |
| }, | |
| temporary_path, | |
| ) | |
| os.replace(temporary_path, path) | |
| def append_training_note(path: Path, heading: str, details: str) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| timestamp = datetime.now().astimezone().isoformat(timespec="seconds") | |
| with path.open("a", encoding="utf-8") as notes: | |
| notes.write(f"\n## {heading} ({timestamp})\n\n{details.rstrip()}\n") | |
| def print_sample(model: GPT, tokenizer: Tokenizer, device: torch.device, eos_token_id: int) -> None: | |
| encoded = tokenizer.encode("User: What is photosynthesis?\nAssistant:").ids | |
| input_ids = torch.tensor([encoded], dtype=torch.long, device=device) | |
| with autocast_context(device): | |
| result = model.generate( | |
| input_ids, | |
| max_new_tokens=100, | |
| temperature=0.8, | |
| top_k=40, | |
| eos_token_id=eos_token_id, | |
| ) | |
| print("Sample:", tokenizer.decode(result[0].tolist(), skip_special_tokens=True)) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data-dir", type=Path, default=PROJECT_DIR / "agent-data") | |
| parser.add_argument("--agent-data", type=Path, default=PROJECT_DIR / "agent-data" / "tool-use.bin") | |
| parser.add_argument("--agent-data-probability", type=float, default=0.2) | |
| parser.add_argument("--no-agent-data", action="store_true", help="train only on the No Robots corpus") | |
| parser.add_argument("--tokenizer", type=Path, default=PROJECT_DIR / "agent-tokenizer.json") | |
| parser.add_argument("--save-dir", type=Path, default=PROJECT_DIR / "agent-checkpoints") | |
| parser.add_argument("--notes", type=Path, default=None, help="training notes file (default: <save-dir>/training-notes.md)") | |
| parser.add_argument("--dataset", default="HuggingFaceH4/no_robots") | |
| parser.add_argument("--train-split", default="train") | |
| parser.add_argument("--validation-split", default="test") | |
| parser.add_argument("--steps", type=int, default=10_000) | |
| parser.add_argument("--batch-size", type=int, default=8, help="Micro-batch; benchmarked to fit the project's 4 GB GTX 1650") | |
| parser.add_argument("--gradient-accumulation", type=int, default=4) | |
| parser.add_argument("--eval-every", type=int, default=1_000) | |
| parser.add_argument("--eval-batches", type=int, default=5) | |
| parser.add_argument("--sample-every", type=int, default=2_000) | |
| parser.add_argument("--warmup-steps", type=int, default=500) | |
| parser.add_argument("--min-lr", type=float, default=6e-5) | |
| parser.add_argument("--weight-decay", type=float, default=0.1) | |
| parser.add_argument("--resume", type=Path, default=None) | |
| parser.add_argument("--fresh", action="store_true", help="ignore existing checkpoints and start from scratch") | |
| parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto") | |
| return parser.parse_args() | |
| def choose_fresh_start(args: argparse.Namespace) -> bool: | |
| if args.fresh: | |
| return True | |
| if args.resume is not None: | |
| return False | |
| latest_path = args.save_dir / "latest.pt" | |
| while True: | |
| try: | |
| choice = input("Training mode: [f] fresh, [s] continue from latest: ").strip().lower() | |
| except EOFError as error: | |
| raise SystemExit("Choose a mode interactively, or pass --fresh/--resume.") from error | |
| if choice == "f": | |
| return True | |
| if choice == "s": | |
| if latest_path.is_file(): | |
| return False | |
| print(f"No checkpoint found at {latest_path}; choose f to start fresh.") | |
| else: | |
| print("Enter f for fresh training or s to continue from the latest checkpoint.") | |
| def run_setup_script(script_name: str, *script_args: str) -> None: | |
| print(f"Running {script_name}...") | |
| subprocess.run( | |
| [sys.executable, str(PROJECT_DIR / script_name), *script_args], | |
| cwd=PROJECT_DIR, | |
| check=True, | |
| ) | |
| def prepare_training_inputs(args: argparse.Namespace) -> None: | |
| manifest_path = args.data_dir / "dataset.json" | |
| expected_manifest = { | |
| "dataset": args.dataset, | |
| "train_split": args.train_split, | |
| "validation_split": args.validation_split, | |
| } | |
| try: | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| except (OSError, json.JSONDecodeError): | |
| manifest = None | |
| data_files = (args.data_dir / "train.bin", args.data_dir / "val.bin") | |
| needs_rebuild = ( | |
| not args.tokenizer.is_file() | |
| or not all(path.is_file() for path in data_files) | |
| or manifest != expected_manifest | |
| ) | |
| if needs_rebuild: | |
| run_setup_script( | |
| "tokenizer_train.py", | |
| "--output", | |
| str(args.tokenizer), | |
| "--vocab-size", | |
| str(GPTConfig().vocab_size), | |
| "--dataset", | |
| args.dataset, | |
| "--split", | |
| args.train_split, | |
| ) | |
| run_setup_script( | |
| "prepare_data.py", | |
| "--tokenizer", | |
| str(args.tokenizer), | |
| "--output-dir", | |
| str(args.data_dir), | |
| "--dataset", | |
| args.dataset, | |
| "--train-split", | |
| args.train_split, | |
| "--validation-split", | |
| args.validation_split, | |
| ) | |
| if args.agent_data is not None and not args.agent_data.is_file(): | |
| run_setup_script( | |
| "prepare_agent_data.py", | |
| "--tokenizer", | |
| str(args.tokenizer), | |
| "--output", | |
| str(args.agent_data), | |
| ) | |
| def main() -> None: | |
| args = parse_args() | |
| for path_name in ("data_dir", "agent_data", "tokenizer", "save_dir", "resume", "notes"): | |
| path = getattr(args, path_name) | |
| if path is not None and not path.is_absolute(): | |
| setattr(args, path_name, (Path.cwd() / path).resolve()) | |
| if args.notes is None: | |
| args.notes = args.save_dir / "training-notes.md" | |
| if args.no_agent_data: | |
| args.agent_data = None | |
| if args.steps < 1 or args.batch_size < 1 or args.gradient_accumulation < 1: | |
| raise SystemExit("steps, batch-size, and gradient-accumulation must be positive") | |
| if args.eval_every < 1 or args.eval_batches < 1: | |
| raise SystemExit("eval-every and eval-batches must be positive") | |
| if not 0.0 <= args.agent_data_probability <= 1.0: | |
| raise SystemExit("agent-data-probability must be between 0 and 1") | |
| if args.fresh and args.resume is not None: | |
| raise SystemExit("--fresh cannot be used with --resume") | |
| if args.device == "cuda" and not torch.cuda.is_available(): | |
| raise SystemExit("CUDA was requested but is not available") | |
| fresh_start = choose_fresh_start(args) | |
| prepare_training_inputs(args) | |
| device = torch.device( | |
| "cuda" if args.device == "cuda" or (args.device == "auto" and torch.cuda.is_available()) else "cpu" | |
| ) | |
| config = GPTConfig() | |
| model = GPT(config).to(device) | |
| print(f"Parameters: {model.parameter_count():,}") | |
| print(f"Device: {device}; micro-batch: {args.batch_size}; effective batch: {args.batch_size * args.gradient_accumulation}") | |
| if device.type == "cuda": | |
| print(f"GPU: {torch.cuda.get_device_name(device)}") | |
| train_loader = MemmapBatchLoader( | |
| args.data_dir / "train.bin", | |
| args.batch_size, | |
| config.context_length, | |
| device, | |
| additional_path=args.agent_data, | |
| additional_probability=args.agent_data_probability, | |
| ) | |
| val_loader = MemmapBatchLoader( | |
| args.data_dir / "val.bin", args.batch_size, config.context_length, device | |
| ) | |
| if not args.tokenizer.is_file(): | |
| raise FileNotFoundError(f"Tokenizer not found: {args.tokenizer}; run tokenizer_train.py first") | |
| tokenizer = Tokenizer.from_file(str(args.tokenizer)) | |
| eos_token_id = tokenizer.token_to_id(END_OF_TEXT) | |
| if eos_token_id is None: | |
| raise ValueError(f"Tokenizer is missing {END_OF_TEXT}") | |
| optimizer = make_optimizer(model, args.weight_decay) | |
| scaler = torch.cuda.amp.GradScaler(enabled=device.type == "cuda") | |
| start_step = 0 | |
| best_val_loss = float("inf") | |
| resume_path = args.resume or (args.save_dir / "latest.pt") | |
| if not fresh_start: | |
| if not resume_path.is_file(): | |
| raise FileNotFoundError(f"Checkpoint not found: {resume_path}") | |
| checkpoint = torch.load(resume_path, map_location=device, weights_only=False) | |
| if checkpoint["config"] != config.to_dict(): | |
| raise ValueError("Checkpoint model config does not match this run") | |
| model.load_state_dict(checkpoint["model"]) | |
| optimizer.load_state_dict(checkpoint["optimizer"]) | |
| for group in optimizer.param_groups: | |
| group["fused"] = device.type == "cuda" | |
| scaler.load_state_dict(checkpoint.get("scaler", {})) | |
| start_step = int(checkpoint["step"]) | |
| best_val_loss = float(checkpoint.get("best_val_loss", float("inf"))) | |
| print(f"Resumed from {resume_path} at step {start_step:,}") | |
| append_training_note( | |
| args.notes, | |
| "Training run", | |
| "\n".join( | |
| ( | |
| f"- Mode: {'fresh' if fresh_start else f'resumed from {resume_path}'}", | |
| f"- Dataset: `{args.dataset}` (`{args.train_split}` / `{args.validation_split}`)", | |
| f"- Steps: {start_step:,} to {args.steps:,}", | |
| f"- Batch: {args.batch_size} x {args.gradient_accumulation} accumulation", | |
| f"- Device: `{device}`", | |
| f"- Parameters: {model.parameter_count():,}", | |
| f"- Agent tool-use data: `{args.agent_data}` at {args.agent_data_probability:.0%} batch-row probability", | |
| ) | |
| ), | |
| ) | |
| model.train() | |
| accumulation = args.gradient_accumulation | |
| progress = tqdm(range(start_step + 1, args.steps + 1), initial=start_step, total=args.steps) | |
| completed_step = start_step | |
| try: | |
| for step in progress: | |
| lr = learning_rate(step - 1, args.warmup_steps, args.steps, args.min_lr) | |
| for group in optimizer.param_groups: | |
| group["lr"] = lr | |
| optimizer.zero_grad(set_to_none=True) | |
| start_time = time.perf_counter() | |
| loss_sum = torch.zeros((), device=device) | |
| for _ in range(accumulation): | |
| inputs, targets = train_loader.next_batch() | |
| with autocast_context(device): | |
| _, loss = model(inputs, targets) | |
| loss_sum += loss.detach().float() / accumulation | |
| scaler.scale(loss / accumulation).backward() | |
| loss_value = loss_sum.item() | |
| scaler.unscale_(optimizer) | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| scaler.step(optimizer) | |
| scaler.update() | |
| completed_step = step | |
| elapsed = max(time.perf_counter() - start_time, 1e-9) | |
| tokens_per_second = args.batch_size * accumulation * config.context_length / elapsed | |
| memory = ( | |
| torch.cuda.max_memory_allocated(device) / (1024**2) | |
| if device.type == "cuda" | |
| else 0.0 | |
| ) | |
| progress.set_postfix(objective="causal", loss=f"{loss_value:.4f}", lr=f"{lr:.2e}", tok_s=f"{tokens_per_second:.0f}", gpu_mib=f"{memory:.0f}") | |
| if step % args.eval_every == 0 or step == args.steps: | |
| val_loss = estimate_loss(model, val_loader, device, args.eval_batches) | |
| print( | |
| f"step {step:,} | train loss {loss_value:.4f} | val loss {val_loss:.4f} " | |
| f"| lr {lr:.2e} | tokens/s {tokens_per_second:.0f} | GPU MiB {memory:.0f}" | |
| ) | |
| if val_loss < best_val_loss: | |
| best_val_loss = val_loss | |
| save_checkpoint(args.save_dir / "best.pt", model, optimizer, scaler, step, best_val_loss) | |
| save_checkpoint(args.save_dir / "latest.pt", model, optimizer, scaler, step, best_val_loss) | |
| append_training_note( | |
| args.notes, | |
| f"Step {step:,}", | |
| f"- Train loss: {loss_value:.6f}\n" | |
| f"- Validation loss: {val_loss:.6f}\n" | |
| f"- Learning rate: {lr:.6g}\n" | |
| "- Objective: causal next-token prediction\n" | |
| f"- Throughput: {tokens_per_second:.0f} tokens/s\n" | |
| f"- Best validation loss: {best_val_loss:.6f}\n" | |
| "- Checkpoints: `latest.pt` overwritten; `best.pt` updated if validation improved.", | |
| ) | |
| if args.sample_every > 0 and step % args.sample_every == 0: | |
| print_sample(model, tokenizer, device, eos_token_id) | |
| except KeyboardInterrupt: | |
| print(f"\nInterrupted; saving latest checkpoint at step {completed_step:,}.") | |
| save_checkpoint(args.save_dir / "latest.pt", model, optimizer, scaler, completed_step, best_val_loss) | |
| print(f"Saved {args.save_dir / 'latest.pt'}") | |
| append_training_note( | |
| args.notes, | |
| "Training interrupted", | |
| f"- Saved step: {completed_step:,}\n- Latest checkpoint overwritten: `latest.pt`", | |
| ) | |
| finally: | |
| progress.close() | |
| if start_step >= args.steps: | |
| print("Checkpoint is already at or beyond the requested step count; no training was run.") | |
| else: | |
| append_training_note( | |
| args.notes, | |
| "Training complete", | |
| f"- Final step: {completed_step:,}\n- Best validation loss: {best_val_loss:.6f}", | |
| ) | |
| if __name__ == "__main__": | |
| main() |