"""Checkpoint I/O, weight-soup interpolation, and lightweight inference stripping.""" from __future__ import annotations import os from pathlib import Path import torch def atomic_save(value: object, path: Path | str) -> None: """Write a torch object safely using a temporary sibling file and atomic replace.""" target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) temporary = target.with_suffix(target.suffix + ".tmp") torch.save(value, temporary) os.replace(temporary, target) def soup_checkpoints( ckpt_a: Path | str, ckpt_b: Path | str, out_path: Path | str, alpha: float = 0.5, ) -> Path: """Interpolate ``(1 - alpha) * a + alpha * b`` across all floating-point ``model`` weights.""" a = torch.load(ckpt_a, map_location="cpu", weights_only=True) b = torch.load(ckpt_b, map_location="cpu", weights_only=True) sd_a, sd_b = a["model"], b["model"] if set(sd_a.keys()) != set(sd_b.keys()): raise ValueError("checkpoints do not have identical model keys for souping") w_a = 1.0 - float(alpha) w_b = float(alpha) merged = {} for k in sd_a: ta, tb = sd_a[k], sd_b[k] if torch.is_floating_point(ta): merged[k] = (w_a * ta.float() + w_b * tb.float()).to(ta.dtype) else: merged[k] = ta.clone() out = dict(a) out["model"] = merged out["soup"] = {"alpha": float(alpha), "source_a": Path(ckpt_a).name, "source_b": Path(ckpt_b).name} atomic_save(out, out_path) return Path(out_path) def strip_legacy_vocoder( ckpt_path: Path | str, out_path: Path | str, fp16: bool = False, ) -> Path: """Strip unused legacy Vocos weights from a BigVGAN-space CFM checkpoint for distribution.""" state = torch.load(ckpt_path, map_location="cpu", weights_only=True) sd = state["model"] cleaned = {} for k, v in sd.items(): if k.startswith("vocoder.") and k not in ("vocoder.mel_mean", "vocoder.mel_scale"): continue cleaned[k] = v.half() if (fp16 and torch.is_floating_point(v)) else v.clone() out = dict(state) out["model"] = cleaned out["stripped_legacy_vocoder"] = True atomic_save(out, out_path) return Path(out_path)