ckpt / code /eval_audioldm2_test_loss.py
AE-W's picture
archive loose scripts/configs
219f052 verified
Raw
History Blame Contribute Delete
12.2 kB
"""Sweep audioldm2 ckpts (concat + controlnet variants) and compute test-set
MSE loss for each. Outputs JSON with {ckpt: test_loss}.
Mirrors `train_concat.py:val_loss` and `train_controlnet.py:val_loss` exactly:
fp16 forward, predicted noise vs gt noise MSE, deterministic per-batch
(noise, timesteps) so different ckpts are compared apples-to-apples.
Architecture is auto-detected from the ckpt path:
- `audioldm2_bg2fg_controlnet_rebalance/.../controlnet.pt` → ControlNet sidebranch
- `audioldm2_bg2fg_rebalance/.../unet/diffusion_pytorch_model.safetensors` → 16-ch concat UNet
Usage:
python eval_audioldm2_test_loss.py --ckpts <hf_path1> <hf_path2> ... --out <json>
"""
import argparse, json, os, re, sys, time
from pathlib import Path
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download, snapshot_download
from torch.utils.data import DataLoader
from safetensors.torch import load_file
ROOT = Path("/nfs/turbo/coe-ahowens-nobackup/dingqy/AudioLDM-training-finetuning")
sys.path.insert(0, str(ROOT))
from diffusers import AudioLDM2Pipeline, DDPMScheduler # noqa
from audioldm2_v2.dataset import BG2FGDataset, waveform_to_log_mel # noqa
from audioldm2_v2.empty_prompt_cache import expand_to_batch, load_cache # noqa
from audioldm2_v2.model_concat import expand_unet_conv_in # noqa
from audioldm2_v2.model_controlnet import (
AudioLDM2ControlNet, unet_forward_with_residuals, # noqa
)
HF_REPO = "AE-W/ckpt"
CACHE = os.environ.get("HF_CACHE",
"/nfs/turbo/coe-ahowens-nobackup/dingqy/.cache/huggingface")
def detect_arch(ckpt_rel: str) -> str:
"""Returns 'controlnet' or 'concat' based on HF path conventions.
For a local abs path (the audioldm2_bg2fg_controlnet_rebalance/.../step_*
dir), peek at what file is inside to disambiguate."""
if os.path.isabs(ckpt_rel):
if (Path(ckpt_rel) / "controlnet.pt").exists():
return "controlnet"
if (Path(ckpt_rel) / "unet").is_dir():
return "concat"
if "controlnet" in ckpt_rel:
return "controlnet"
return "concat"
def download_ckpt_dir(ckpt_rel: str) -> Path:
"""ckpt_rel is the HF dir path like
`audioldm2_bg2fg_controlnet_rebalance/step_00010000` — or an absolute
path to a local step_NNNNNNNN dir (used when HF mirror is missing a step
that's still on turbo)."""
if os.path.isabs(ckpt_rel) and Path(ckpt_rel).is_dir():
return Path(ckpt_rel)
arch = detect_arch(ckpt_rel)
if arch == "controlnet":
local = hf_hub_download(repo_id=HF_REPO,
filename=f"{ckpt_rel}/controlnet.pt",
repo_type="dataset", cache_dir=CACHE)
return Path(local).parent
else:
# concat: needs unet/diffusion_pytorch_model.safetensors
local = hf_hub_download(repo_id=HF_REPO,
filename=f"{ckpt_rel}/unet/diffusion_pytorch_model.safetensors",
repo_type="dataset", cache_dir=CACHE)
return Path(local).parent.parent # the step_NNNN dir
def collate_test(batch):
"""Stack fg_wav and bg_wav, drop other fields."""
fg = torch.stack([item["fg_wav"] for item in batch], dim=0)
bg = torch.stack([item["bg_wav"] for item in batch], dim=0)
return {"fg_wav": fg, "bg_wav": bg}
@torch.no_grad()
def encode_batch(pipe, fg_wav, bg_wav, vae_scale, device):
fg_wav = fg_wav.to(device, non_blocking=True)
bg_wav = bg_wav.to(device, non_blocking=True)
mel_fg = waveform_to_log_mel(fg_wav)
mel_bg = waveform_to_log_mel(bg_wav)
z_fg = pipe.vae.encode(mel_fg).latent_dist.mean * vae_scale
z_bg = pipe.vae.encode(mel_bg).latent_dist.mean * vae_scale
return z_fg, z_bg
@torch.no_grad()
def forward_concat(pipe, z_fg, z_bg, noise, t, cond, noise_scheduler):
z_noisy = noise_scheduler.add_noise(z_fg, noise, t)
z_in = torch.cat([z_noisy, z_bg], dim=1)
eps = pipe.unet(
z_in, t,
encoder_hidden_states=cond["encoder_hidden_states"],
encoder_hidden_states_1=cond["encoder_hidden_states_1"],
encoder_attention_mask_1=cond["encoder_attention_mask_1"],
return_dict=False,
)[0]
return eps
@torch.no_grad()
def forward_controlnet(pipe, controlnet, z_fg, z_bg, noise, t, cond, noise_scheduler):
z_noisy = noise_scheduler.add_noise(z_fg, noise, t)
down_res, mid_res = controlnet(
z_bg, t,
encoder_hidden_states=cond["encoder_hidden_states"],
encoder_hidden_states_1=cond["encoder_hidden_states_1"],
encoder_attention_mask_1=cond["encoder_attention_mask_1"],
)
eps = unet_forward_with_residuals(
pipe.unet, z_noisy, t,
encoder_hidden_states=cond["encoder_hidden_states"],
encoder_hidden_states_1=cond["encoder_hidden_states_1"],
encoder_attention_mask_1=cond["encoder_attention_mask_1"],
down_block_additional_residuals=down_res,
mid_block_additional_residual=mid_res,
)
return eps
@torch.no_grad()
def test_loss_one(arch, pipe, controlnet, test_loader, cache, noise_scheduler,
vae_scale, device, num_train_timesteps=1000, seed_base=42):
pipe.unet.eval()
if controlnet is not None:
controlnet.eval()
total = 0.0
n = 0
t0 = time.time()
for i, batch in enumerate(test_loader):
with torch.cuda.amp.autocast(dtype=torch.float16):
z_fg, z_bg = encode_batch(pipe, batch["fg_wav"], batch["bg_wav"],
vae_scale, device)
bs = z_fg.shape[0]
gen = torch.Generator(device=device).manual_seed(seed_base + i)
noise = torch.randn(z_fg.shape, generator=gen, device=device, dtype=z_fg.dtype)
timesteps = torch.randint(0, num_train_timesteps, (bs,),
generator=gen, device=device, dtype=torch.long)
cond = expand_to_batch(cache, bs)
with torch.cuda.amp.autocast(dtype=torch.float16):
if arch == "concat":
eps = forward_concat(pipe, z_fg, z_bg, noise, timesteps, cond,
noise_scheduler)
else:
eps = forward_controlnet(pipe, controlnet, z_fg, z_bg, noise,
timesteps, cond, noise_scheduler)
loss = F.mse_loss(eps.float(), noise.float(), reduction="mean")
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 dir paths under AE-W/ckpt, e.g. audioldm2_bg2fg_controlnet_rebalance/step_00010000")
ap.add_argument("--out", required=True)
ap.add_argument("--manifest",
default="/nfs/turbo/coe-ahowens-nobackup/ymdou/hidingsound/data/noise_guidance_out_latent/manifest.json")
ap.add_argument("--empty-cache",
default=str(ROOT / "audioldm2_v2/empty_prompt_cache_large.pt"))
ap.add_argument("--model-id", default="cvssp/audioldm2-large")
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)")
ap.add_argument("--seed-base", type=int, default=42)
args = ap.parse_args()
device = "cuda"
print(f"loading pipeline {args.model_id}...", flush=True)
# Mirror training-time setup (train_controlnet.py:384-393): pipe in fp32,
# AudioLDM2ControlNet built on CPU first (its __init__ runs a CPU dummy
# through base_unet.time_embedding/conv_in to size zero-convs), THEN
# both moved to device. Pre-moving pipe.unet to GPU breaks the builder.
pipe = AudioLDM2Pipeline.from_pretrained(args.model_id)
pipe.vae.eval(); pipe.unet.eval()
vae_scale = pipe.vae.config.scaling_factor
noise_scheduler = DDPMScheduler.from_pretrained(args.model_id, subfolder="scheduler")
num_T = noise_scheduler.config.num_train_timesteps
cache = load_cache(args.empty_cache, device=device)
print(f"loading test split from {args.manifest}", flush=True)
test_ds = BG2FGDataset(
manifest_path=args.manifest,
split="test",
prompt_stats_path=None,
load_prompts_for_weights=False,
)
if args.limit:
test_ds.pairs = test_ds.pairs[: args.limit]
print(f" {len(test_ds)} test pairs", flush=True)
test_loader = DataLoader(
test_ds, batch_size=args.batch_size, shuffle=False,
num_workers=args.num_workers, collate_fn=collate_test, pin_memory=True,
)
results = {}
if Path(args.out).exists():
results = json.load(open(args.out))
# Track current architecture state — pipe.unet's conv_in is mutated when
# we switch from controlnet (8-ch) to concat (16-ch). We don't switch
# back, so process all controlnet ckpts FIRST, then all concat.
sorted_ckpts = sorted(args.ckpts, key=lambda c: (detect_arch(c) != "controlnet", c))
pipe_is_concat = False
controlnet_module = None
for ckpt_rel in sorted_ckpts:
if ckpt_rel in results:
print(f"\n[skip] {ckpt_rel} (cached test_loss={results[ckpt_rel]['test_loss']:.5f})",
flush=True)
continue
arch = detect_arch(ckpt_rel)
print(f"\n=== {ckpt_rel} ({arch}) ===", flush=True)
ckpt_dir = download_ckpt_dir(ckpt_rel)
if arch == "controlnet":
assert not pipe_is_concat, "can't go concat→controlnet without re-init"
sd = torch.load(ckpt_dir / "controlnet.pt", map_location="cpu",
weights_only=False)
if controlnet_module is None:
# Build on CPU first (matches train_controlnet.py order), then
# move both to GPU together.
controlnet_module = AudioLDM2ControlNet(pipe.unet)
pipe.to(device)
controlnet_module = controlnet_module.to(device)
print(f" built controlnet shell + moved pipe+cn to {device}")
controlnet_module.load_state_dict(sd)
controlnet_module.eval()
print(f" controlnet.pt loaded ({sum(v.numel() for v in sd.values()):,} params)")
del sd
else:
if not pipe_is_concat:
expand_unet_conv_in(pipe.unet, new_in_channels=16)
pipe.to(device)
pipe_is_concat = True
controlnet_module = None # not used for concat
print(f" expanded conv_in 8→16, moved pipe to {device}")
sd = load_file(str(ckpt_dir / "unet" / "diffusion_pytorch_model.safetensors"))
pipe.unet.load_state_dict(sd)
pipe.unet.eval()
print(f" unet weights loaded ({sum(v.numel() for v in sd.values()):,} params)")
del sd
loss, n = test_loss_one(arch, pipe, controlnet_module, test_loader,
cache, noise_scheduler, vae_scale, device,
num_train_timesteps=num_T,
seed_base=args.seed_base)
print(f" test_loss = {loss:.5f} (n={n})", flush=True)
results[ckpt_rel] = {"test_loss": loss, "n": n, "arch": arch}
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} ({info['arch']:>10}) {ckpt_rel}")
if sorted_results:
best = sorted_results[0]
print(f"\n>>> best: {best[0]} test_loss={best[1]['test_loss']:.5f}")
if __name__ == "__main__":
main()