TTS_10M / utils /checkpoint.py
ViuAI's picture
Push audited codebase, regression tests (10/10 pass) & AUDIT.md
79b2661 verified
Raw History Blame Contribute Delete
7.79 kB
"""
Checkpointing and Hugging Face Model Hub Publishing Utilities.
Uses safe, modern .safetensors format for weights and companion trainer_state.pt for resume.
"""
import os
import json
import hashlib
import math
import shutil
import tempfile
import uuid
from pathlib import Path
from safetensors import safe_open
import torch
from safetensors.torch import save_file, load_file
from huggingface_hub import HfApi, login, create_repo
from typing import Optional, Dict, Any
def _atomic_write(path, writer):
fd, temp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
os.close(fd)
try:
writer(temp)
os.replace(temp, path)
finally:
Path(temp).unlink(missing_ok=True)
def _publish_alias(source, target):
def copy_or_link(temp):
os.unlink(temp)
try:
os.link(source, temp)
except OSError:
shutil.copyfile(source, temp)
_atomic_write(target, copy_or_link)
def find_checkpoint():
for path in ("checkpoints/model_best.safetensors", "checkpoints/model.safetensors",
"checkpoints/model_final.safetensors", "model.safetensors"):
if Path(path).is_file():
return path
return None
def save_checkpoint(
model, optimizer, step, output_dir, prefix="model", scheduler=None, scaler=None,
epoch=0, best_val_loss=None, save_latest=True, batch_in_epoch=None,
batches_per_epoch=None, batch_size=None,
):
directory = Path(output_dir)
directory.mkdir(parents=True, exist_ok=True)
stem = "model_best" if prefix == "model_best" else f"{prefix}_{step}"
weights = directory / f"{stem}.safetensors"
state_path = directory / f"{stem}.trainer.pt"
identity = uuid.uuid4().hex
acoustic = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()
if not k.startswith("vocoder.")}
_atomic_write(weights, lambda temp: save_file(acoustic, temp, metadata={"checkpoint_id": identity}))
if optimizer is not None:
state = dict(step=step, epoch=epoch, best_val_loss=best_val_loss, checkpoint_id=identity,
batch_in_epoch=batch_in_epoch, batches_per_epoch=batches_per_epoch,
batch_size=batch_size, optimizer=optimizer.state_dict(),
cpu_rng=torch.get_rng_state())
if torch.cuda.is_initialized():
state["cuda_rng"] = torch.cuda.get_rng_state_all()
if scheduler is not None:
state["scheduler"] = scheduler.state_dict()
if scaler is not None:
state["scaler"] = scaler.state_dict()
_atomic_write(state_path, lambda temp: torch.save(state, temp))
if save_latest:
_publish_alias(weights, directory / "model.safetensors")
if optimizer is not None:
_publish_alias(state_path, directory / "trainer_state.pt")
meta = {"step": step, "epoch": epoch, "best_val_loss": best_val_loss}
if best_val_loss is not None and not math.isfinite(best_val_loss):
meta["best_val_loss"] = None
_atomic_write(directory / "metadata.json", lambda temp: Path(temp).write_text(
json.dumps(meta, indent=2), encoding="utf-8"))
print(f"Checkpoint saved at step {step} -> {weights}")
def load_checkpoint(model: torch.nn.Module, checkpoint_path: str, device: str = "cpu"):
path = Path(checkpoint_path)
if path.suffix == ".safetensors":
weights = load_file(str(path), device=device)
else:
weights = torch.load(path, map_location=device, weights_only=True)
acoustic = {}
for name, tensor in weights.items():
if name.startswith("vocoder."):
continue
if name.startswith("vector_field."):
name = "cfm.vf." + name.removeprefix("vector_field.")
if name in weights:
continue
acoustic[name] = tensor
expected = {k for k in model.state_dict() if not k.startswith("vocoder.")}
missing, extra = expected - acoustic.keys(), acoustic.keys() - expected
if missing or extra:
raise ValueError(f"Incompatible acoustic checkpoint {path}: missing {sorted(missing)}, unexpected {sorted(extra)}")
model.load_state_dict(acoustic, strict=False)
return model
def load_trainer_state(checkpoint_dir, optimizer, scheduler=None, scaler=None, device="cpu",
*, checkpoint_path=None):
directory = Path(checkpoint_dir)
weights = Path(checkpoint_path) if checkpoint_path is not None else directory / "model.safetensors"
state_path = weights.with_suffix(".trainer.pt")
if not state_path.exists():
state_path = directory / "trainer_state.pt"
if not state_path.is_file():
raise FileNotFoundError(f"No trainer state for {weights.name}. Use --init_from for weights only.")
state = torch.load(state_path, map_location="cpu", weights_only=True)
identity = None
if weights.suffix == ".safetensors":
with safe_open(str(weights), framework="pt") as f:
identity = (f.metadata() or {}).get("checkpoint_id")
if identity or state.get("checkpoint_id"):
matches = identity == state.get("checkpoint_id")
else:
# Legacy format used one mutable sidecar. Only pair weights whose numbered
# snapshot can be linked to its step, including latest/best aliases.
snapshots = [directory / f"{prefix}_{state['step']}.safetensors"
for prefix in ("model", "model_final")]
def digest(path):
with path.open("rb") as f:
h = hashlib.sha256()
for block in iter(lambda: f.read(1024 * 1024), b""):
h.update(block)
return h.digest()
matches = any(p.is_file() and (p == weights or digest(p) == digest(weights)) for p in snapshots)
if not matches and weights.name == "model.safetensors" and not any(p.exists() for p in snapshots):
# Older Hub backups only contain aliases, with no verifiable pairing.
raise ValueError("Legacy backup has no numbered weights to verify resume. Use --init_from.")
if not matches:
raise ValueError(f"Trainer state does not match {weights.name}. Use matching files or --init_from.")
if optimizer is not None:
optimizer.load_state_dict(state["optimizer"])
if scheduler is not None and "scheduler" in state:
scheduler.load_state_dict(state["scheduler"])
if scaler is not None and "scaler" in state:
scaler.load_state_dict(state["scaler"])
if "cpu_rng" in state:
torch.set_rng_state(state["cpu_rng"])
if torch.device(device).type == "cuda" and "cuda_rng" in state:
torch.cuda.set_rng_state_all(state["cuda_rng"])
print(f"Resumed {weights.name} from epoch {state['epoch']}, step {state['step']}.")
return state
def push_to_huggingface_hub(
repo_id: str,
folder_path: str,
token: Optional[str] = None,
private: bool = False,
commit_message: str = "Upload 10M Modern TTS model",
):
"""Pushes model checkpoints, configs, and README to Hugging Face Model Hub."""
if token:
login(token=token)
api = HfApi()
print(f"Ensuring repository exists on Hugging Face: {repo_id}...")
create_repo(repo_id, repo_type="model", private=private, exist_ok=True)
print(f"Uploading files from {folder_path} to {repo_id}...")
api.upload_folder(
folder_path=folder_path,
repo_id=repo_id,
repo_type="model",
commit_message=commit_message,
)
print(f"\nModel successfully published to: https://huggingface.co/{repo_id}\n")