"""Sweep candidate ckpts (across the full lbkb1h5z + dbdxldk4 chain) and compute test-set MSE loss for each. Outputs JSON with {ckpt: test_loss}. Test loss = the same MSE that training_step computes (matched per-objective: v-pred or rectified-flow target). Computed under no_grad with deterministic per-batch noise + timesteps so different ckpts are compared apples-to-apples. Usage: python eval_sa_test_loss.py \\ --ckpts ... \\ --out best_ckpts_sa.json \\ [--limit 500] # cap test pairs for fast iteration Steps to evaluate are selected by passing --ckpts; the sbat submits a representative grid across both runs. """ import argparse, json, os, sys, time from pathlib import Path import numpy as np import torch import torch.nn.functional as F from huggingface_hub import hf_hub_download SA_ROOT = Path("/nfs/turbo/coe-ahowens-nobackup/dingqy/friendly-stable-audio-tools") sys.path.insert(0, str(SA_ROOT)) from stable_audio_tools.models import create_model_from_config # noqa from stable_audio_tools.models.utils import load_ckpt_state_dict # noqa from stable_audio_tools.training import create_training_wrapper_from_config # noqa from stable_audio_tools.inference.sampling import get_alphas_sigmas # noqa from stable_audio_tools.data.dataset import HidingSoundManifestDataset # noqa from torch.utils.data import DataLoader HF_REPO = "AE-W/ckpt" CACHE = os.environ.get("HF_CACHE", "/nfs/turbo/coe-ahowens-nobackup/dingqy/.cache/huggingface") def collate_metadata(batch): """Default DataLoader collate would dict-merge metadata; instead keep it as a list of dicts because the SA conditioner expects metadata: list[dict].""" audios = torch.stack([item[0] for item in batch], dim=0) metas = [item[1] for item in batch] return audios, metas @torch.no_grad() def test_loss_for_ckpt(wrapper, test_loader, device, num_batches=None, seed_base=42): """Mean per-sample MSE between model output and the v / rfm target on the test loader. Mirrors `DiffusionCondTrainingWrapper.training_step` minus log/backprop; deterministic per-batch noise + timesteps so multiple ckpts are compared on the same noising pattern.""" wrapper.eval() obj = wrapper.diffusion_objective total = 0.0 n = 0 t0 = time.time() for i, batch in enumerate(test_loader): if num_batches and i >= num_batches: break reals, metadata = batch reals = reals.to(device, non_blocking=True) if reals.ndim == 4 and reals.shape[0] == 1: reals = reals[0] # Deterministic noise + timestep — same across ckpts. seed = base + i # so every batch has its own noise, but consistent run-to-run. gen = torch.Generator(device=device).manual_seed(seed_base + i) with torch.cuda.amp.autocast(): wrapper.diffusion.conditioner.set_device(device) conditioning = wrapper.diffusion.conditioner(metadata) if wrapper.diffusion.pretransform: with torch.cuda.amp.autocast(): diffusion_input = wrapper.diffusion.pretransform.encode(reals) else: diffusion_input = reals t = torch.rand(reals.shape[0], generator=gen, device=device) if obj == "v": alphas, sigmas = get_alphas_sigmas(t) elif obj == "rectified_flow": alphas, sigmas = 1 - t, t else: raise ValueError(f"unknown diffusion_objective: {obj}") alphas = alphas[:, None, None] sigmas = sigmas[:, None, None] noise = torch.randn(diffusion_input.shape, generator=gen, device=device) noised = diffusion_input * alphas + noise * sigmas if obj == "v": targets = noise * alphas - diffusion_input * sigmas elif obj == "rectified_flow": targets = noise - diffusion_input output = wrapper.diffusion(noised, t, cond=conditioning, cfg_dropout_prob=0.0) loss = F.mse_loss(output.float(), targets.float(), reduction='mean') bs = reals.shape[0] total += float(loss.item()) * bs n += bs if i % 50 == 0: print(f" batch {i:>4} cum_n={n} rolling_loss={total/n:.5f} ({time.time()-t0:.0f}s)", flush=True) return total / max(n, 1), n def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpts", nargs="+", required=True, help="HF paths under AE-W/ckpt, e.g. sa_open_bg2fg_rebalance/lbkb1h5z/epoch=0-step=10000.ckpt") ap.add_argument("--out", default="/nfs/turbo/coe-ahowens-nobackup/dingqy/sa_test_loss_sweep.json") ap.add_argument("--model-config", default=str(SA_ROOT / "stable_audio_tools/configs/model_configs/txt2audio/stable_audio_open_1_0_bg2fg_rebalance.json")) ap.add_argument("--dataset-config", default=str(SA_ROOT / "stable_audio_tools/configs/dataset_configs/hidingsound_sa_open_bg2fg_rebalance.json")) ap.add_argument("--batch-size", type=int, default=8) ap.add_argument("--num-workers", type=int, default=4) ap.add_argument("--limit", type=int, default=0, help="cap test pairs (0 = all). Use ~500 for a quick first pass.") ap.add_argument("--seed-base", type=int, default=42) args = ap.parse_args() print(f"loading model config: {args.model_config}") mc = json.load(open(args.model_config)) print(f"loading dataset config: {args.dataset_config}") ds_cfg = json.load(open(args.dataset_config)) print("instantiating model + training wrapper (one time)...", flush=True) base_model = create_model_from_config(mc) wrapper = create_training_wrapper_from_config(mc, base_model) wrapper = wrapper.cuda() # Build TEST dataset print(f"building test dataset from manifest: {ds_cfg['manifest_path']}") ds = HidingSoundManifestDataset( manifest_path=ds_cfg["manifest_path"], data_root=ds_cfg.get("data_root"), split="test", sample_size=mc["sample_size"], sample_rate=mc["sample_rate"], random_crop=False, # deterministic rebalance_enabled=False, prompt_stats_path=None, smoothing=0.0, ) if args.limit: ds.pairs = ds.pairs[: args.limit] print(f" {len(ds)} test pairs") test_loader = DataLoader( ds, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, collate_fn=collate_metadata, pin_memory=True, ) results = {} if Path(args.out).exists(): results = json.load(open(args.out)) for ckpt_rel in args.ckpts: if ckpt_rel in results: print(f"\n[skip] {ckpt_rel} (cached test_loss={results[ckpt_rel]['test_loss']:.5f})", flush=True) continue print(f"\n=== {ckpt_rel} ===", flush=True) if os.path.isabs(ckpt_rel) and os.path.exists(ckpt_rel): # Local file (e.g. the pretrained sa_open_1_0_bg_expanded.ckpt # baseline) — skip the HF download path. local = ckpt_rel else: local = hf_hub_download(repo_id=HF_REPO, filename=ckpt_rel, repo_type="dataset", cache_dir=CACHE) sd = load_ckpt_state_dict(local) # Two ckpt formats coexist: # - Lightning ckpt (saved during training): keys = diffusion.* / diffusion_ema.* # - Stability raw inner-model save (pretrained baseline): keys = model.model.* # Lightning's load_state_dict handles the first; the second needs to # go via copy_state_dict on wrapper.diffusion (which itself is a # ConditionedDiffusionModelWrapper with native model.model.* keys). is_raw_inner_save = any(k.startswith("model.model.") for k in sd.keys()) \ and not any(k.startswith("diffusion.") for k in sd.keys()) if is_raw_inner_save: from stable_audio_tools.utils.torch_common import copy_state_dict copy_state_dict(wrapper.diffusion, sd) print(f" copy_state_dict into wrapper.diffusion (raw inner-model save)") ema_loaded = False else: missing, unexpected = wrapper.load_state_dict(sd, strict=False) print(f" load_state_dict: missing={len(missing)} unexpected={len(unexpected)}") ema_loaded = any(k.startswith("diffusion_ema") for k in sd.keys()) if ema_loaded and getattr(wrapper, "diffusion_ema", None) is not None: wrapper.diffusion.model = wrapper.diffusion_ema.ema_model print(" using EMA weights") else: print(f" using non-EMA (raw) weights (ema_loaded={ema_loaded})") wrapper = wrapper.cuda().eval() loss, n = test_loss_for_ckpt(wrapper, test_loader, device="cuda", seed_base=args.seed_base) print(f" test_loss = {loss:.5f} (n={n})", flush=True) results[ckpt_rel] = {"test_loss": loss, "n": n} with open(args.out, "w") as f: json.dump(results, f, indent=2) print(f" saved → {args.out}", flush=True) # Final summary print("\n=== summary (sorted by test_loss) ===") sorted_results = sorted(results.items(), key=lambda x: x[1]["test_loss"]) for ckpt_rel, info in sorted_results: print(f" {info['test_loss']:.5f} (n={info['n']}) {ckpt_rel}") if sorted_results: best = sorted_results[0] print(f"\n>>> best ckpt: {best[0]} test_loss={best[1]['test_loss']:.5f}") if __name__ == "__main__": main()