Quasar / quasar /training /checkpoint.py
Atlas Ai
Upload evaluated Quasar weights with portable inference and pinned codecs
d2a1a41 verified
Raw History Blame Contribute Delete
3.47 kB
"""Portable, self-contained checkpoints.
<ckpt>/model.safetensors weights (safetensors; tied weights stored once)
<ckpt>/config.json model config, unified vocab layout, training metadata
<ckpt>/tokenizers/ copies of the text BPE and the frozen visual tokenizer
<ckpt>/trainer_state.pt optimizer, scheduler, step, RNG states (torch.load(weights_only=True))
Directories are written to a temp name and swapped in, so an interrupted save never corrupts
the previous checkpoint.
"""
from __future__ import annotations
import json
import os
import shutil
from pathlib import Path
import torch
from safetensors.torch import load_model, save_model
from ..model.config import ModelConfig
from ..model.transformer import Quasar
from ..tokenizers.multimodal import UnifiedVocab
from ..tokenizers.universal import UniversalVocab
def save_checkpoint(path: str | Path, model: Quasar, vocab: UnifiedVocab, text_tokenizer: str | Path, vq_dir: str | Path,
meta: dict, trainer_state: dict | None = None) -> Path:
path = Path(path)
tmp = path.with_name(path.name + ".tmp")
shutil.rmtree(tmp, ignore_errors=True)
(tmp / "tokenizers" / "vq").mkdir(parents=True)
save_model(model, str(tmp / "model.safetensors"))
(tmp / "config.json").write_text(json.dumps({"model": model.cfg.to_dict(), "vocab": vocab.to_dict(), "meta": meta}, indent=2))
shutil.copy2(text_tokenizer, tmp / "tokenizers" / "text_tokenizer.json")
for f in ("vq.safetensors", "vq_config.json"):
shutil.copy2(Path(vq_dir) / f, tmp / "tokenizers" / "vq" / f)
if trainer_state is not None:
torch.save(trainer_state, tmp / "trainer_state.pt")
old = path.with_name(path.name + ".old")
shutil.rmtree(old, ignore_errors=True)
if path.exists():
os.replace(path, old)
os.replace(tmp, path)
shutil.rmtree(old, ignore_errors=True)
return path
def read_config(path: str | Path) -> dict:
return json.loads((Path(path) / "config.json").read_text())
def load_quasar(path: str | Path, device: str | torch.device = "cpu") -> tuple[Quasar, UnifiedVocab, dict]:
"""Load model weights + vocab + metadata from a checkpoint directory."""
path = Path(path)
if not (path / "model.safetensors").exists():
raise FileNotFoundError(f"{path} is not a Quasar checkpoint (no model.safetensors)")
cfg = read_config(path)
model = Quasar(ModelConfig.from_dict(cfg["model"]))
missing, unexpected = load_model(model, str(path / "model.safetensors"), strict=False)
if unexpected or [k for k in missing if k != "head.weight"]:
raise RuntimeError(f"checkpoint mismatch: missing={missing} unexpected={unexpected}")
v = cfg["vocab"]
vocab = UniversalVocab(**v) if v.get("schema_version") in (2, 3) else UnifiedVocab.from_dict(v)
return model.to(device), vocab, cfg["meta"]
def load_trainer_state(path: str | Path) -> dict:
return torch.load(Path(path) / "trainer_state.pt", map_location="cpu", weights_only=True)
def rng_state() -> dict:
s = {"torch": torch.get_rng_state()}
if torch.cuda.is_available():
s["cuda"] = torch.cuda.get_rng_state_all()
return s
def set_rng_state(s: dict) -> None:
torch.set_rng_state(s["torch"])
if "cuda" in s and torch.cuda.is_available():
torch.cuda.set_rng_state_all(s["cuda"])