Download quasar/training/trainer.py from AtlasAI-org/Quasar: direct link, hf CLI and curl.
- Browser
- Download file 21.2 kB
-
https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/training/trainer.py
- Command line
-
hf download hf://AtlasAI-org/Quasar/quasar/training/trainer.py
-
curl -L -o trainer.py https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/training/trainer.py
21.2 kB
| """Training engine for one curriculum stage of the shared Quasar backbone.""" | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import platform | |
| import time | |
| from collections import defaultdict | |
| from contextlib import nullcontext | |
| from pathlib import Path | |
| import torch | |
| import yaml | |
| from ..data.datasets import TASK_MODALITY, MixtureLoader, TaskSources, available_tasks, fixed_eval_batches, split_task | |
| from ..model.config import ModelConfig, load_yaml | |
| from ..model.transformer import Quasar | |
| from ..tokenizers.multimodal import UnifiedVocab | |
| from ..tokenizers.universal import UniversalVocab | |
| from ..data.curated import UniversalSources | |
| from ..data.collator import collate | |
| from ..tokenizers.multimodal import Sample | |
| from ..tokenizers.text import TextTokenizer | |
| from .checkpoint import load_quasar, load_trainer_state, rng_state, save_checkpoint, set_rng_state | |
| from .metrics import JsonlLogger, Meter, gpu_memory | |
| from .hardware import check_gpu | |
| from .compilation import compile_loss, real_warmup_samples | |
| from .validation_guard import ValidationGuard | |
| DEFAULTS = { | |
| "lr": 6e-4, "min_lr_ratio": 0.1, "warmup": 200, "weight_decay": 0.1, "betas": [0.9, 0.95], "clip": 1.0, | |
| "micro_tokens": 16384, "grad_accum": 4, "precision": "auto", "grad_checkpoint": False, "optimizer": "adamw", | |
| "log_every": 25, "eval_every": 500, "save_every": 500, "eval_batches": 4, "seed": 1337, "task_weights": {}, | |
| "compile": False, "compile_backend": "inductor", "compile_dynamic": False, "compile_buckets": True, | |
| "max_vram_fraction": 0.9, | |
| } | |
| def resolve_config(config_path: str | Path, stage: str, overrides: list[str] | None = None) -> dict: | |
| """defaults < root `defaults` < profile `train` < stage block < --set overrides.""" | |
| root = load_yaml(config_path) | |
| prof = root["model_profile"] | |
| prof = load_yaml(prof) if isinstance(prof, str) else prof | |
| if stage not in root["stages"]: | |
| raise KeyError(f"stage '{stage}' not in {config_path}; available: {list(root['stages'])}") | |
| cfg = {**DEFAULTS, **root.get("defaults", {}), **prof.get("train", {}), **root["stages"][stage]} | |
| cfg |= {"model": prof["model"], "vq": root["vq"], "cache": root["cache"], "run_dir": root["run_dir"], "stage": stage} | |
| cfg["training_enabled"] = root.get("training_enabled", True) | |
| for kv in overrides or []: | |
| k, v = kv.split("=", 1) | |
| cfg[k] = yaml.safe_load(v) | |
| return cfg | |
| class Trainer: | |
| def __init__(self, cfg: dict, resume: bool = False): | |
| if not cfg.get("training_enabled", True): | |
| raise RuntimeError("training is disabled in this preparation configuration; no optimizer or checkpoint was created") | |
| check_gpu(cfg) | |
| self.cfg = cfg | |
| self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| torch.manual_seed(cfg["seed"]) | |
| if self.dev.type == "cuda": | |
| # Windows/WDDM silently spills past-VRAM allocations into system RAM (~25x slower) instead of | |
| # raising OOM; a hard cap turns that into a real OutOfMemoryError that train() recovers from. | |
| torch.cuda.set_per_process_memory_fraction(cfg["max_vram_fraction"]) | |
| cache = Path(cfg["cache"]) | |
| self.tok_path = cache / "text_tokenizer.json" | |
| self.tok = TextTokenizer.load(self.tok_path) | |
| self.universal = (cache / "vocab_v2.json").exists() | |
| vp = cache / ("vocab_v2.json" if self.universal else "vocab.json") | |
| vd = json.loads(vp.read_text()) | |
| self.vocab = UniversalVocab(**vd) if self.universal else UnifiedVocab.from_dict(vd) | |
| self.root = Path(cfg["run_dir"]) | |
| self.dir = self.root / cfg["stage"] | |
| self.log = JsonlLogger(self.dir / "train_log.jsonl") | |
| self.eval_log = JsonlLogger(self.dir / "eval_log.jsonl") | |
| prec = cfg["precision"] | |
| if prec == "auto": | |
| prec = "bf16" if self.dev.type == "cuda" and torch.cuda.is_bf16_supported() else "fp16" if self.dev.type == "cuda" else "fp32" | |
| self.amp_dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": None}[prec] | |
| self.scaler = torch.amp.GradScaler("cuda") if prec == "fp16" else None | |
| self.precision = prec | |
| self.start_step = 0 | |
| self.prev_meta: dict = {} | |
| state = None | |
| latest = self.dir / "latest" | |
| if resume and latest.exists(): | |
| self.model, vocab, self.prev_meta = load_quasar(latest, self.dev) | |
| state = load_trainer_state(latest) | |
| self.start_step = state["step"] | |
| print(f"[trainer] resuming {latest} at step {self.start_step}") | |
| elif cfg.get("init_from"): | |
| src = self.root / cfg["init_from"] / "final" | |
| self.model, vocab, self.prev_meta = load_quasar(src, self.dev) | |
| print(f"[trainer] initialised from {src} ({self.prev_meta.get('stage')} @ step {self.prev_meta.get('step')})") | |
| else: | |
| mc = ModelConfig.from_dict({**cfg["model"], "vocab_size": self.vocab.size, "visual_offset": self.vocab.visual_offset, | |
| "visual_size": self.vocab.visual_size, "vis_positions": self.vocab.tokens_per_frame}) | |
| self.model = Quasar(mc).to(self.dev) | |
| vocab = self.vocab | |
| save_checkpoint(self.root / "init" / "final", self.model, self.vocab, self.tok_path, cfg["vq"], self._meta(0, {}, {}, stage="init")) | |
| if vocab.to_dict() != self.vocab.to_dict(): | |
| raise RuntimeError("checkpoint vocabulary does not match the data cache vocabulary") | |
| self.model.cfg.grad_checkpoint = bool(cfg["grad_checkpoint"]) | |
| self.fwd = compile_loss(self.model, cfg) | |
| decay = [p for p in self.model.parameters() if p.dim() >= 2] | |
| no_decay = [p for p in self.model.parameters() if p.dim() < 2] | |
| groups = [{"params": decay, "weight_decay": cfg["weight_decay"]}, {"params": no_decay, "weight_decay": 0.0}] | |
| if cfg["optimizer"] == "adamw8bit": | |
| import bitsandbytes as bnb | |
| self.opt = bnb.optim.AdamW8bit(groups, lr=cfg["lr"], betas=tuple(cfg["betas"])) | |
| else: | |
| self.opt = torch.optim.AdamW(groups, lr=cfg["lr"], betas=tuple(cfg["betas"]), fused=self.dev.type == "cuda") | |
| total, warm, floor = cfg["steps"], cfg["warmup"], cfg["min_lr_ratio"] | |
| def lr_lambda(s: int) -> float: | |
| if s < warm: | |
| return (s + 1) / warm | |
| p = min(1.0, (s - warm) / max(1, total - warm)) | |
| return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * p)) | |
| self.sched = torch.optim.lr_scheduler.LambdaLR(self.opt, lr_lambda) | |
| self.tokens_seen = self.prev_meta.get("tokens_seen", 0) | |
| self.task_tokens = defaultdict(int, self.prev_meta.get("task_target_tokens", {})) | |
| self.stage_tokens: dict[str, int] = defaultdict(int) | |
| self.image_128_target_tokens = int(self.prev_meta.get('image_128_target_tokens', 0)) | |
| if state is not None: | |
| self.opt.load_state_dict(state["optimizer"]) | |
| self.sched.load_state_dict(state["scheduler"]) | |
| set_rng_state(state["rng"]) | |
| self.tokens_seen, self.task_tokens = state["tokens_seen"], defaultdict(int, state["task_tokens"]) | |
| self.stage_tokens = defaultdict(int, state.get("stage_tokens", {})) | |
| cfg["micro_tokens"], cfg["grad_accum"] = state["micro_tokens"], state["grad_accum"] | |
| self.image_128_target_tokens = state.get('image_128_target_tokens', self.image_128_target_tokens) | |
| self.validation_guard = (ValidationGuard(cfg['validation_guard'], state.get('validation_guard') if state else None) | |
| if cfg.get('validation_guard') else None) | |
| # ------------------------------------------------------------------------------------ | |
| def _amp(self): | |
| return torch.autocast(self.dev.type, dtype=self.amp_dtype) if self.amp_dtype else nullcontext() | |
| def _meta(self, step: int, task_tokens: dict, stage_tokens: dict, stage: str | None = None) -> dict: | |
| stats_p = Path(self.cfg["cache"]) / "stats.json" | |
| stats = json.loads(stats_p.read_text()) if stats_p.exists() else {} | |
| done = list(self.prev_meta.get("stages_completed", [])) | |
| return { | |
| "stage": stage or self.cfg["stage"], "step": step, "tokens_seen": self.tokens_seen if stage != "init" else 0, | |
| "task_target_tokens": dict(task_tokens), "stage_task_target_tokens": dict(stage_tokens), | |
| "stages_completed": done, "train_config": {k: v for k, v in self.cfg.items()}, | |
| "num_params": self.model.num_params(), "precision": self.precision, | |
| "image_128_trained": bool(self.prev_meta.get('image_128_trained') or getattr(self,'image_128_target_tokens',0)>0), | |
| "image_128_target_tokens": getattr(self,'image_128_target_tokens',0), | |
| "data": {"sources": stats.get("sources"), "vocab": stats.get("vocab"), "media": stats.get("media"), "text": stats.get("text"), | |
| "preparation": stats if self.universal else None}, | |
| "env": {"torch": torch.__version__, "cuda": torch.version.cuda, "python": platform.python_version(), | |
| "gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None}, | |
| } | |
| def _save(self, name: str, step: int, with_state: bool = True, final: bool = False) -> None: | |
| meta = self._meta(step, self.task_tokens, self.stage_tokens) | |
| if final: | |
| meta["stages_completed"] = meta["stages_completed"] + [self.cfg["stage"]] | |
| state = None | |
| if with_state: | |
| state = {"optimizer": self.opt.state_dict(), "scheduler": self.sched.state_dict(), "step": step, "rng": rng_state(), | |
| "tokens_seen": self.tokens_seen, "task_tokens": dict(self.task_tokens), "stage_tokens": dict(self.stage_tokens), | |
| "micro_tokens": self.cfg["micro_tokens"], "grad_accum": self.cfg["grad_accum"]} | |
| state['image_128_target_tokens'] = self.image_128_target_tokens | |
| if self.validation_guard: | |
| state['validation_guard'] = self.validation_guard.state | |
| save_checkpoint(self.dir / name, self.model, self.vocab, self.tok_path, self.cfg["vq"], meta, state) | |
| def sources(self, split: str, seq_len: int) -> dict[str, TaskSources]: | |
| """Built-in cache plus any imported user cache at <cache>/user (must share the vocabulary).""" | |
| cache = Path(self.cfg["cache"]) | |
| if self.universal: | |
| return {"": UniversalSources(cache, split, self.vocab, seq_len)} | |
| out = {"": TaskSources(cache, split, self.vocab, self.tok, seq_len)} | |
| user = cache / "user" | |
| if (user / "vocab.json").exists(): | |
| if json.loads((user / "vocab.json").read_text()) != self.vocab.to_dict(): | |
| raise RuntimeError(f"{user} was imported with a different tokenizer/vocab; re-run generate_dataset.py --combine") | |
| out["user"] = TaskSources(user, split, self.vocab, self.tok, seq_len) | |
| return out | |
| def _guard_validation(self, step: int, evaluation: dict) -> bool: | |
| """Called after a complete optimizer step with gradients cleared. | |
| On stop, preserve the last valid best checkpoint and save the actual latest | |
| optimizer/RNG state. A stopped run is never labeled final or completed. | |
| """ | |
| if not self.validation_guard: | |
| return False | |
| decision = self.validation_guard.observe(step, evaluation['val_loss']) | |
| self.log.log({'event': 'validation_guard', 'step': step, **decision}) | |
| if decision['save_best']: | |
| self._save('best', step) | |
| if decision['stop']: | |
| self._save('latest', step) | |
| self._save('stopped', step) | |
| self.log.log({'event': 'early_stopped', 'step': step, **decision, **gpu_memory()}) | |
| return True | |
| return False | |
| def evaluate(self, batches: dict) -> dict: | |
| self.model.eval() | |
| out = {} | |
| for task, bl in batches.items(): | |
| tot, n = 0.0, 0 | |
| for inp, lab in bl: | |
| with self._amp(): | |
| loss, k = self.model.loss(inp.to(self.dev), lab.to(self.dev), include_aux=False) | |
| tot += loss.item() * k.item() | |
| n += k.item() | |
| out[task] = round(tot / max(n, 1), 4) | |
| mod = defaultdict(list) | |
| for t, l in out.items(): | |
| src, base = split_task(t) | |
| modality = {"t2a": "audio", "a2t": "audio", "t2m": "mesh", "m2t": "mesh", "tools": "tools", "coding": "coding", "mixed": "multimodal"}.get(base, TASK_MODALITY.get(base, base)) | |
| mod[(src + "/" if src else "") + modality].append(l) | |
| self.model.train() | |
| return {"val_loss": out, "val_modality_loss": {m: round(sum(v) / len(v), 4) for m, v in mod.items()}} | |
| def train(self) -> Path: | |
| cfg = self.cfg | |
| seq_len = self.model.cfg.max_seq_len | |
| train_src, val_src = self.sources("train", seq_len), self.sources("val", seq_len) | |
| eval_batches = fixed_eval_batches(val_src, available_tasks(val_src), cfg["micro_tokens"], cfg["eval_batches"]) | |
| weights = cfg["task_weights"] | |
| self.log.log({"event": "start", "stage": cfg["stage"], "params": self.model.num_params(), | |
| "pid": os.getpid(), "resume_step": self.start_step, | |
| "compile": bool(cfg["compile"]), "compile_backend": cfg["compile_backend"] if cfg["compile"] else None, | |
| "compile_dynamic": cfg["compile_dynamic"], "compile_buckets": cfg["compile"] and cfg["compile_buckets"], | |
| "params_non_embedding": self.model.num_params(False), "mixture": cfg["mixture"], "precision": self.precision, | |
| "micro_tokens": cfg["micro_tokens"], "grad_accum": cfg["grad_accum"], "steps": cfg["steps"]}) | |
| if self.start_step == 0: | |
| initial_eval = self.evaluate(eval_batches) | |
| self.eval_log.log({"step": 0, **initial_eval}) | |
| if self.validation_guard: | |
| decision = self.validation_guard.observe(0, initial_eval['val_loss']) | |
| if decision['stop']: | |
| raise RuntimeError('Initial validation guard failed') | |
| self._save('best', 0) | |
| self.model.train() | |
| if cfg["compile"] and cfg["compile_buckets"] and self.universal: | |
| # Warm real cached examples through every supported static shape. | |
| # Backward passes initialize kernels without taking optimizer steps; | |
| # warmup timing is separate from sustained training measurements. | |
| lengths = sorted({min(seq_len, length) for length in (128,256,512,1024) if min(seq_len,length) <= cfg["micro_tokens"]}) | |
| warmup_samples = real_warmup_samples(train_src, lengths) | |
| for length in lengths: | |
| source_name, sample = warmup_samples[length] | |
| inp, lab = collate([sample], self.vocab.pad, target_length=length, | |
| batch_size=cfg["micro_tokens"]//length) | |
| self.opt.zero_grad(set_to_none=True) | |
| if self.dev.type == "cuda": torch.cuda.synchronize() | |
| started = time.perf_counter() | |
| with self._amp(): | |
| loss, n = self.fwd(inp.to(self.dev), lab.to(self.dev)) | |
| loss.backward() | |
| norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), cfg["clip"]) | |
| if not torch.isfinite(norm) or not torch.isfinite(loss): | |
| raise RuntimeError("Nonfinite loss/gradients during real-data compiler warmup") | |
| if self.dev.type == "cuda": torch.cuda.synchronize() | |
| self.log.log({"event":"compile_warmup", "shape":list(inp.shape), "optimizer_steps":0,"source":source_name, | |
| "elapsed_s":round(time.perf_counter()-started,3), "targets":int(n.item()), | |
| "loss":round(loss.item(),4), "grad_norm":round(norm.item(),4), **gpu_memory()}) | |
| self.opt.zero_grad(set_to_none=True) | |
| step = self.start_step | |
| meter = Meter() | |
| meter_steps = 0 | |
| if self.dev.type == "cuda": | |
| torch.cuda.reset_peak_memory_stats() | |
| while step < cfg["steps"]: | |
| limits = cfg.get("max_task_target_tokens", {}) | |
| active_mixture = {t:w for t,w in cfg["mixture"].items() if t not in limits or self.task_tokens[t] < limits[t]} | |
| if not any(w > 0 for w in active_mixture.values()): | |
| raise RuntimeError("all task token budgets exhausted; no remaining training mixture") | |
| loader = MixtureLoader(train_src, active_mixture, cfg["micro_tokens"], cfg["seed"], | |
| compile_buckets=cfg["compile"] and cfg["compile_buckets"]) | |
| it = loader.iterate(step, cfg["grad_accum"]) | |
| try: | |
| while step < cfg["steps"]: | |
| for m in range(cfg["grad_accum"]): | |
| s, mi, task, inp, lab = next(it) | |
| assert (s, mi) == (step, m) | |
| inp, lab = inp.to(self.dev, non_blocking=True), lab.to(self.dev, non_blocking=True) | |
| with self._amp(): | |
| loss, n = self.fwd(inp, lab) | |
| scaled = loss * weights.get(task, 1.0) / cfg["grad_accum"] | |
| (self.scaler.scale(scaled) if self.scaler else scaled).backward() | |
| n = int(n.item()) | |
| meter.add(task, loss.item(), inp.numel(), n) | |
| self.tokens_seen += inp.numel() | |
| self.task_tokens[task] += n | |
| self.stage_tokens[task] += n | |
| if (task == 't2i' and getattr(self.vocab,'schema_version',0)==3 | |
| and bool((lab == self.vocab.special('resolution:128')).any().item())): | |
| self.image_128_target_tokens += n | |
| if self.scaler: | |
| self.scaler.unscale_(self.opt) | |
| gn = torch.nn.utils.clip_grad_norm_(self.model.parameters(), cfg["clip"]) | |
| if not torch.isfinite(gn): | |
| self.log.log({"event": "nonfinite_grad", "step": step}) | |
| raise RuntimeError("Nonfinite gradients; refusing an invalid optimizer update") | |
| if self.scaler: | |
| self.scaler.step(self.opt) | |
| self.scaler.update() | |
| else: | |
| self.opt.step() | |
| self.opt.zero_grad(set_to_none=True) | |
| self.sched.step() | |
| step += 1 | |
| meter_steps += 1 | |
| if step % cfg["log_every"] == 0 or step == 1: | |
| self.log.log({"step": step, **meter.summary(meter_steps), "lr": round(self.sched.get_last_lr()[0], 7), | |
| "grad_norm": round(gn.item(), 4), "tokens_seen": self.tokens_seen, **gpu_memory()}) | |
| meter.reset() | |
| meter_steps = 0 | |
| if step % cfg["eval_every"] == 0 or step == cfg["steps"]: | |
| evaluation = self.evaluate(eval_batches) | |
| self.eval_log.log({"step": step, **evaluation}) | |
| if self._guard_validation(step, evaluation): | |
| return self.dir / 'stopped' | |
| if step % cfg["save_every"] == 0 and step < cfg["steps"]: | |
| self._save("latest", step) | |
| exhausted = [t for t in loader.tasks if t in limits and self.task_tokens[t] >= limits[t]] | |
| if exhausted: | |
| self.log.log({"event": "task_budget_exhausted", "step": step, "tasks": exhausted}) | |
| it.close() # stop prefetch; remove capped tasks at the next optimizer-step boundary | |
| break | |
| except torch.cuda.OutOfMemoryError: | |
| # Recover: drop the partial step, halve micro-batch tokens, double accumulation (same effective batch). | |
| self.opt.zero_grad(set_to_none=True) | |
| torch.cuda.empty_cache() | |
| if cfg["micro_tokens"] <= 1024: | |
| raise | |
| cfg["micro_tokens"] //= 2 | |
| cfg["grad_accum"] *= 2 | |
| self.log.log({"event": "oom_recovered", "step": step, "micro_tokens": cfg["micro_tokens"], "grad_accum": cfg["grad_accum"]}) | |
| finally: | |
| it.close() | |
| self._save("final", step, with_state=True, final=True) | |
| self.log.log({"event": "done", "step": step, **gpu_memory()}) | |
| return self.dir / "final" | |