"""Model loading and inference plumbing for the VidDub Space. Ports the release path from the authors' scripts/infer.py: download base Wan2.1-VACE-1.3B + Whisper-small assets, load the trained DiT/VACE/audio adapter from AIPeanutman/VidDub, and run the paper-selected two-step full-context sampler over 81-frame windows. """ import json from pathlib import Path import decord import librosa import numpy as np import torch from huggingface_hub import snapshot_download from safetensors.torch import load_file from viddub.causal.model import CausalConfig, CausalWanDub from viddub.causal.runtime import autocast from viddub.causal.sampling import rollout, schedule from viddub.full_context import runtime as fc_runtime from viddub.full_context.audio import DubAudioAdapter from viddub.full_context.inference import dub_video from viddub.full_context.runtime import FPS, SR, ZeroLatents, write_mp4 MODEL_ID = "AIPeanutman/VidDub" BASE_ID = "Wan-AI/Wan2.1-VACE-1.3B" WHISPER_ID = "openai/whisper-small" # Populated by init(). RUNTIME = {} def log(message): print(f"[viddub] {message}", flush=True) def init(device="cuda"): """Load all model components once at module scope (ZeroGPU pack step).""" if RUNTIME: return RUNTIME cache = Path("/tmp/viddub_weights") base_dir = snapshot_download(BASE_ID, allow_patterns=[ "diffusion_pytorch_model.safetensors", "Wan2.1_VAE.pth", "models_t5_umt5-xxl-enc-bf16.pth", "google/umt5-xxl/*", ]) whisper_dir = snapshot_download(WHISPER_ID, allow_patterns=[ "*.json", "*.model", "model.safetensors", "*.txt", ]) model_dir = snapshot_download(MODEL_ID, allow_patterns=[ "*.json", "*.md", "*.safetensors", "dit/*", "vace/*", "audio_adapter/*", ]) fc_runtime.WEIGHTS = cache # Bind the module-level globals load_models actually reads. fc_runtime.VACE_DIR = Path(base_dir) fc_runtime.WEIGHTS = cache # The release runtime expects whisper under WEIGHTS/whisper-small. whisper_link = cache / "whisper-small" if not whisper_link.exists(): whisper_link.parent.mkdir(parents=True, exist_ok=True) whisper_link.symlink_to(Path(whisper_dir).resolve()) log(f"base: {base_dir}") log(f"whisper: {whisper_dir}") config_path = Path(model_dir) / "config.json" config = json.loads(config_path.read_text()) paths = {name: Path(model_dir) / relative for name, relative in config["components"].items()} missing = [str(p) for p in paths.values() if not p.is_file()] if missing: raise FileNotFoundError(f"Missing model files: {missing}") torch_device = torch.device(device) pipe, whisper = fc_runtime.load_models(torch_device) # Load state dicts on CPU, then .to(device) through the ZeroGPU hijack. # (safetensors' CUDA open path initializes CUDA before a GPU is attached.) pipe.dit.load_state_dict(load_file(str(paths["dit"])), strict=True) pipe.vace.load_state_dict(load_file(str(paths["vace"])), strict=True) pipe.dit.to(torch_device) pipe.vace.to(torch_device) adapter = DubAudioAdapter().to(torch_device) adapter.load_state_dict(load_file(str(paths["audio_adapter"])), strict=True) adapter.eval() zero = ZeroLatents(pipe) inference_model = CausalWanDub( pipe.dit, pipe.vace, adapter, CausalConfig( int(config["latent_chunk_size"]), int(config["num_reference_latents"]), float(config["fps"]), ), causal=bool(config.get("causal", False)), ).eval().requires_grad_(False) RUNTIME.update({ "models": (pipe, whisper, adapter, zero), "config": config, "steps": int(config["student_steps"]), "sample_fn": two_step_sampler(inference_model, config), }) log("all model components loaded") return RUNTIME def two_step_sampler(model, config): """The release two-step (FULL2_DMD_R4) sampler. Mirrors infer.py.""" @torch.no_grad() def sample(pipe, whisper, adapter, zero, clip, audio, steps=None, audio_cfg=1.0, seed=0, fps=FPS): trained_steps = int(config["student_steps"]) if steps is not None and int(steps) != trained_steps: raise ValueError( f"This checkpoint was trained for {trained_steps} steps; got {steps}") if float(audio_cfg) != 1.0: raise ValueError("VidDub DMD checkpoints require audio CFG 1") num_frames = len(clip["frames"]) video = fc_runtime.to_video_tensor(clip["frames"], pipe) keep = torch.from_numpy(~clip["mask"]).to(video)[None, None, None] latents = { "x0": pipe.vae.encode(video, device=pipe.device)[0], "inactive": pipe.vae.encode(video * keep, device=pipe.device)[0], "ref": pipe.vae.encode( fc_runtime.to_video_tensor(clip["ref"][None], pipe), device=pipe.device)[0], } x0, vace_context, context = fc_runtime.build_inputs( latents, clip["mask"], num_frames, zero, drop_ref=int(config["num_reference_latents"]) == 0) whisper_hs = whisper([audio], pipe.device, torch.bfloat16) model.config = CausalConfig( int(config["latent_chunk_size"]), int(config["num_reference_latents"]), float(fps)) conditions = { "context": context.to(torch.bfloat16), "vace_context": vace_context.to(torch.bfloat16), "whisper_hs": whisper_hs.to(torch.bfloat16), "num_frames": num_frames, } noise = torch.randn( x0.shape, generator=torch.Generator(device=x0.device).manual_seed(seed), device=x0.device, dtype=torch.bfloat16) with autocast(x0.device, "bf16"): output = rollout( model, x0.to(torch.bfloat16), conditions, schedule(trained_steps, float(config["shift"]), x0.device), noise=noise, use_cache=bool(config.get("causal", False)), audio_cfg=1.0) video = pipe.vae.decode( output[:, :, int(config["num_reference_latents"]):].to(pipe.torch_dtype), device=pipe.device) return ((video[0].permute(1, 2, 3, 0).float().clamp(-1, 1) + 1) * 127.5).round().byte().cpu().numpy() return sample def infer_file(video, audio, output, seed=0, mode="auto", overlap=17, feather=15, harmonize=True): """Run one media pair with the loaded runtime. Mirrors infer.py.""" video, audio, output = str(video), str(audio), Path(output) reader = decord.VideoReader(video, num_threads=2) fps = float(reader.get_avg_fps()) frames = reader[:].asnumpy() waveform = librosa.load(audio, sr=SR, mono=True)[0] audio_samples = round(len(frames) / fps * SR) waveform = np.pad( waveform[:audio_samples], (0, max(0, audio_samples - len(waveform))), ) rt = RUNTIME generated = dub_video( rt["models"], frames, waveform, steps=rt["steps"], audio_cfg=1.0, feather=feather, seed=seed, fps=fps, overlap=overlap, mode=mode, harmonize=harmonize, sample_fn=rt["sample_fn"], log=log, ) output.parent.mkdir(parents=True, exist_ok=True) write_mp4(output, generated, waveform, fps=fps) return output