Download src/pat/train.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/train.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/train.py
-
curl -L -o train.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/train.py
13.9 kB
| """Train PAT or FA with CUDA BF16, using one device or torchrun.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import signal | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.distributed as dist | |
| from torch.nn.parallel import DistributedDataParallel | |
| from .checkpoint import load_checkpoint, save_checkpoint, sha256, verify_checkpoint | |
| from .config import PATConfig | |
| from .data import PieceDataset, training_batches, validation_batches | |
| from .model import PATModel | |
| from .tokenizer import TOKENIZER_SHA256 | |
| from .training import ( | |
| TrainingConfig, | |
| backward_loss, | |
| optimizer_for, | |
| validate_resume_plan, | |
| validate_resume_state, | |
| ) | |
| def _sum(values: torch.Tensor, world_size: int) -> torch.Tensor: | |
| if world_size > 1: | |
| dist.all_reduce(values, op=dist.ReduceOp.SUM) | |
| return values | |
| def _plan_hash(plan: list[list[int]]) -> str: | |
| return hashlib.sha256(json.dumps(plan, separators=(",", ":")).encode()).hexdigest() | |
| def validate(model, data: PieceDataset, budget: int, device, rank: int, world: int) -> dict: | |
| model.eval() | |
| totals = torch.zeros(4, device=device, dtype=torch.float64) | |
| for index, batch in enumerate(validation_batches(data, budget, seed=model.config.seed)): | |
| if index % world != rank: | |
| continue | |
| pieces = [data[item].to(device) for item in batch] | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| output = model(pieces) | |
| totals += torch.tensor([ | |
| output.loss_sum.item(), output.token_count, | |
| output.lexical_loss_sum.item(), output.lexical_token_count, | |
| ], device=device, dtype=torch.float64) | |
| _sum(totals, world) | |
| if totals[1].item() <= 0 or totals[3].item() <= 0: | |
| raise ValueError("Validation corpus contains no supervised lexical tokens") | |
| model.train() | |
| return {"loss": (totals[0] / totals[1]).item(), | |
| "lexical_loss": (totals[2] / totals[3]).item(), | |
| "targets": int(totals[1].item()), "lexical_targets": int(totals[3].item())} | |
| def _save(model, optimizer, directory: Path, state: dict, rank: int, world: int) -> None: | |
| rng = {"cpu": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state().cpu()} | |
| states = [None] * world if rank == 0 else None | |
| if world > 1: | |
| dist.gather_object(rng, states, dst=0) | |
| else: | |
| states = [rng] | |
| if rank == 0: | |
| # The outer directory is published only after both weights and resume | |
| # state have been written and hashed; interrupted saves are never latest. | |
| stage_root = Path(tempfile.mkdtemp(prefix=".saving-", dir=directory.parent)) | |
| stage = stage_root / "checkpoint" | |
| save_checkpoint(model, stage, metadata={"tokens": state["seen_tokens"], "step": state["step"]}) | |
| torch.save({**state, "optimizer": optimizer.state_dict(), "rng_by_rank": states}, stage / "training.pt") | |
| manifest = json.loads((stage / "manifest.json").read_text()) | |
| manifest["files"]["training.pt"] = { | |
| "sha256": sha256(stage / "training.pt"), "size_bytes": (stage / "training.pt").stat().st_size, | |
| } | |
| (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") | |
| stage.rename(directory) | |
| stage_root.rmdir() | |
| if world > 1: | |
| dist.barrier() | |
| def run(args) -> None: | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("Training requires a CUDA GPU; no alternate attention implementation is provided") | |
| rank, world = int(os.environ.get("RANK", "0")), int(os.environ.get("WORLD_SIZE", "1")) | |
| device = torch.device("cuda", int(os.environ.get("LOCAL_RANK", "0"))) | |
| torch.cuda.set_device(device) | |
| if not torch.cuda.is_bf16_supported(): | |
| raise RuntimeError("Training requires BF16 support") | |
| if world > 1: | |
| dist.init_process_group("nccl", device_id=device) | |
| document = json.loads(args.config.read_text()) | |
| if set(document) != {"model", "training"}: | |
| raise ValueError("Training config must contain exactly 'model' and 'training'") | |
| model_config = PATConfig.from_dict(document["model"]) | |
| training_values = dict(document["training"]) | |
| if args.tokens is not None: | |
| training_values["tokens"] = args.tokens | |
| config = TrainingConfig(**training_values) | |
| if config.seed != model_config.seed: | |
| raise ValueError("Model and training initialization seeds must agree") | |
| random.seed(config.seed) | |
| np.random.seed(config.seed) | |
| torch.manual_seed(config.seed) | |
| torch.cuda.manual_seed_all(config.seed) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch._dynamo.config.optimize_ddp = False | |
| dataset = PieceDataset(args.data) | |
| val_dataset = PieceDataset(args.validation) if args.validation else None | |
| for data in (dataset, val_dataset): | |
| if data is None: | |
| continue | |
| if data.manifest["tokenizer_sha256"] != TOKENIZER_SHA256: | |
| raise ValueError("Dataset tokenizer differs from the model tokenizer") | |
| if data.manifest["context_length"] != model_config.context_length: | |
| raise ValueError("Dataset context length differs from model configuration") | |
| if config.microbatch_tokens < model_config.context_length: | |
| raise ValueError("Microbatch token budget must fit one maximum-length piece") | |
| if args.resume and args.init_checkpoint: | |
| raise ValueError("Choose resume or initialize from weights, not both") | |
| source = args.resume or args.init_checkpoint | |
| model = load_checkpoint(source, device=device) if source else PATModel(model_config).to(device) | |
| if model.config.to_dict() != model_config.to_dict(): | |
| raise ValueError("Checkpoint architecture differs from the training configuration") | |
| model.train() | |
| optimizer = optimizer_for(model, config) | |
| state = {"format": "pat-training-state-1", "seen_tokens": 0, "step": 0, | |
| "epoch": 0, "cursor": 0, "data_fingerprint": dataset.fingerprint, | |
| "validation_fingerprint": val_dataset.fingerprint if val_dataset else None, | |
| "training_config": config.to_dict(), "world_size": world, "plan_sha256": None} | |
| if args.resume: | |
| verify_checkpoint(args.resume) | |
| restored = torch.load(args.resume / "training.pt", map_location="cpu", weights_only=True) | |
| validate_resume_state(restored, state) | |
| optimizer.load_state_dict(restored.pop("optimizer")) | |
| rng = restored.pop("rng_by_rank")[rank] | |
| torch.set_rng_state(rng["cpu"]) | |
| torch.cuda.set_rng_state(rng["cuda"], device) | |
| state = restored | |
| if args.output.exists() and any(args.output.iterdir()) and not args.resume: | |
| raise FileExistsError("Use a new output directory for a new training run") | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| wrapped = ( | |
| DistributedDataParallel(model, device_ids=[device.index], find_unused_parameters=True) | |
| if world > 1 else model | |
| ) | |
| stopping = False | |
| def request_stop(_signal, _frame): | |
| nonlocal stopping | |
| stopping = True | |
| for number in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1): | |
| signal.signal(number, request_stop) | |
| log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None | |
| last_save = state["seen_tokens"] | |
| last_eval = state["seen_tokens"] | |
| quantum = world * config.accumulation_steps | |
| try: | |
| while state["seen_tokens"] < config.tokens: | |
| plan = training_batches(dataset.routed_lengths, dataset.lexical_lengths, | |
| budget=config.microbatch_tokens, seed=config.seed, | |
| epoch=state["epoch"], quantum=quantum) | |
| if not plan: | |
| raise ValueError("Dataset is too small for one distributed optimizer window") | |
| identity = _plan_hash(plan) | |
| validate_resume_plan(state, len(plan), identity) | |
| state["plan_sha256"] = identity | |
| while state["cursor"] < len(plan) and state["seen_tokens"] < config.tokens: | |
| started = time.perf_counter() | |
| batches = plan[state["cursor"]:state["cursor"] + quantum] | |
| # With explicit next-token labels, each routed token has exactly | |
| # one predecessor (including BOS->first token and lexical->EOD). | |
| lexical = [int(dataset.lexical_lengths[batch].sum()) for batch in batches] | |
| targets = [int(dataset.routed_lengths[batch].sum()) for batch in batches] | |
| total_lexical, total_targets = sum(lexical), sum(targets) | |
| optimizer.zero_grad(set_to_none=True) | |
| lr = config.lr_at(state["seen_tokens"]) | |
| for group in optimizer.param_groups: | |
| group["lr"] = lr | |
| metrics = torch.zeros(4, device=device, dtype=torch.float64) | |
| for microstep in range(config.accumulation_steps): | |
| position = microstep * world + rank | |
| batch = batches[position] | |
| pieces = [dataset[item].to(device) for item in batch] | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| result = wrapped(pieces) | |
| if result.token_count != targets[position]: | |
| raise RuntimeError("Model target count differs from the planned objective") | |
| loss_sum = result.loss_sum.to(dtype=next(model.parameters()).dtype) | |
| global_loss_sum = ( | |
| _sum(result.loss_sum.detach().to(torch.float64), world) | |
| if world > 1 else None | |
| ) | |
| loss = backward_loss( | |
| loss_sum, model_config.architecture, world_size=world, | |
| local_lexical=lexical[position], | |
| global_microbatch_targets=sum(targets[microstep * world:(microstep + 1) * world]), | |
| global_window_targets=total_targets, | |
| global_window_lexical=total_lexical, | |
| global_loss_sum=global_loss_sum, | |
| ) | |
| # DDP reduces every microstep, preserving accumulation and | |
| # reduction order even when multiple microsteps form an update. | |
| loss.backward() | |
| metrics += torch.tensor([result.loss_sum.item(), result.token_count, | |
| result.lexical_loss_sum.item(), result.lexical_token_count], | |
| device=device, dtype=torch.float64) | |
| grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True) | |
| if not torch.isfinite(metrics).all(): | |
| raise FloatingPointError("Nonfinite loss; optimizer update was not performed") | |
| optimizer.step() | |
| state["step"] += 1 | |
| state["cursor"] += quantum | |
| state["seen_tokens"] += total_lexical | |
| _sum(metrics, world) | |
| stop_flag = torch.tensor(int(stopping), device=device) | |
| _sum(stop_flag, world) | |
| stopping = stop_flag.item() > 0 | |
| row = {"step": state["step"], "tokens": state["seen_tokens"], "lr": lr, | |
| "loss": (metrics[0] / metrics[1]).item(), | |
| "lexical_loss": (metrics[2] / metrics[3]).item(), | |
| "grad_norm": float(grad_norm), | |
| "tokens_per_second": total_lexical / (time.perf_counter() - started)} | |
| finished = state["seen_tokens"] >= config.tokens | |
| if val_dataset and (finished or state["seen_tokens"] - last_eval >= config.validate_every): | |
| row["validation"] = validate(model, val_dataset, config.microbatch_tokens, device, rank, world) | |
| last_eval = state["seen_tokens"] | |
| if rank == 0: | |
| log.write(json.dumps(row) + "\n") | |
| if state["step"] % 10 == 0 or finished or stopping: | |
| print(json.dumps(row), flush=True) | |
| if finished or stopping or state["seen_tokens"] - last_save >= config.checkpoint_every: | |
| path = args.output / f"step-{state['step']:08d}" | |
| _save(model, optimizer, path, state, rank, world) | |
| last_save = state["seen_tokens"] | |
| if rank == 0: | |
| (args.output / "latest.txt").write_text(path.name + "\n") | |
| if stopping: | |
| return | |
| if state["cursor"] == len(plan): | |
| state["epoch"] += 1 | |
| state["cursor"] = 0 | |
| state["plan_sha256"] = None | |
| finally: | |
| if log: | |
| log.close() | |
| if world > 1: | |
| dist.destroy_process_group() | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--config", type=Path, required=True, help="Model and training JSON recipe") | |
| parser.add_argument("--data", type=Path, required=True, help="Prepared training dataset") | |
| parser.add_argument("--validation", type=Path, help="Prepared held-out validation dataset") | |
| parser.add_argument("--output", type=Path, required=True, help="Run directory for metrics and checkpoints") | |
| parser.add_argument("--resume", type=Path, help="Complete checkpoint from this trainer, including training.pt") | |
| parser.add_argument("--init-checkpoint", type=Path, help="Initialize weights; start a NEW optimizer and token clock") | |
| parser.add_argument("--tokens", type=int, help="Override lexical training horizon; complete the final optimizer window") | |
| run(parser.parse_args()) | |
| if __name__ == "__main__": | |
| main() | |