"""Export either trained LoRA through the same pinned Causal-Forcing sampler.""" import argparse import gc import json import os from pathlib import Path import random import sys import time from scripts.causal_baselines_b200.eval_common import checkpoint_path, selected_plan, records, sha256, write_json def build_pipeline(plan, checkpoint, device): import torch from omegaconf import OmegaConf from peft import LoraConfig, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict from baselines.astrolabe.bootstrap import install_short_video_pipeline if sha256(plan['student_checkpoint']) != plan['student_checkpoint_sha256']: raise ValueError('Official Causal-Forcing checkpoint changed after preparation') source = Path(plan["upstream_dir"]) sys.path.insert(0, str(source)) os.chdir(plan["pipeline_cwd"]) install_short_video_pipeline(source) from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder, WanVAEWrapper from pipeline.causal_inference import CausalInferencePipeline args = OmegaConf.create(plan["pipeline_args"]) generator = WanDiffusionWrapper(**dict(args.model_kwargs), is_causal=True) base = torch.load(plan["student_checkpoint"], map_location="cpu", weights_only=False) state = base for key in ("generator_ema", "generator", "model", "state_dict"): if key in base: state = base[key] break clean = {} for key, value in state.items(): if key.startswith("model."): key = key[6:] if key.startswith("diffusion_model."): key = key[16:] clean[key] = value generator.model.load_state_dict(clean, strict=True) del base, state, clean generator.to(device, dtype=torch.bfloat16) generator.model.gradient_checkpointing = False targets = set() for name, module in generator.model.named_modules(): if module.__class__.__name__ == "CausalWanAttentionBlock": targets.update(f"{name}.{child}" for child, layer in module.named_modules() if isinstance(layer, torch.nn.Linear)) generator.model = get_peft_model(generator.model, LoraConfig( r=plan["lora_rank"], lora_alpha=plan["lora_alpha"], lora_dropout=0.0, target_modules=sorted(targets), bias="none")) if plan["method"] == "astrolabe": cfg = json.loads(checkpoint.with_name("adapter_config.json").read_text()) if (cfg["r"], cfg["lora_alpha"]) != (plan["lora_rank"], plan["lora_alpha"]): raise ValueError("Astrolabe LoRA configuration changed") weights = torch.load(checkpoint, map_location="cpu", weights_only=True) else: saved = torch.load(checkpoint, map_location="cpu", weights_only=True) expected_cfg = json.loads((Path(plan["checkpoint_run_dir"]) / "config.json").read_text()) if saved["step"] != plan["checkpoint_step"] or saved["config"] != expected_cfg: raise ValueError("AdvDMD checkpoint step/config does not match the evaluation plan") weights = saved["generator_lora"] expected = get_peft_model_state_dict(generator.model) if set(weights) != set(expected) or any(weights[key].shape != expected[key].shape for key in weights): raise ValueError("LoRA tensor names/shapes do not match the common Causal-Forcing backend") if not all(torch.isfinite(value).all().item() for value in weights.values()): raise ValueError("Non-finite LoRA checkpoint") set_peft_model_state_dict(generator.model, weights) count = len(weights) del expected, weights if plan["method"] == "advdmd": del saved generator.eval().requires_grad_(False) text = WanTextEncoder().to(device, dtype=torch.bfloat16).eval().requires_grad_(False) vae = WanVAEWrapper().to(device, dtype=torch.bfloat16).eval().requires_grad_(False) pipe = CausalInferencePipeline(args, device, generator=generator, text_encoder=text, vae=vae) gc.collect() return pipe, count def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--plan", type=Path, required=True) args = parser.parse_args() plan = selected_plan(args.plan) import torch import numpy as np import imageio.v2 as imageio rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1)) local = int(os.environ.get("LOCAL_RANK", 0)) if world != plan["generation_world_size"]: raise ValueError("Generation world size differs from the prepared plan") torch.cuda.set_device(local) device = torch.device("cuda", local) if "B200" not in torch.cuda.get_device_name(device): raise RuntimeError("This generation environment was configured for B200") checkpoint = Path(plan["selected_checkpoint"]) if "selected_checkpoint" in plan else checkpoint_path(plan) fingerprint = sha256(checkpoint) if "selected_checkpoint_sha256" in plan and fingerprint != plan["selected_checkpoint_sha256"]: raise ValueError("Selected checkpoint changed before generation") output = Path(plan["output_dir"]) (output / "videos").mkdir(parents=True, exist_ok=True) assigned = records(plan)[rank::world] journal = output / f"generation-rank{rank}.jsonl" completed = set() receipts = {} if journal.exists(): for line in journal.read_text().splitlines(): try: item = json.loads(line) except json.JSONDecodeError: continue if item.get("checkpoint_sha256") != fingerprint: raise ValueError("Existing generation belongs to a different checkpoint") completed.add((item["prompt"], item["replica"])) receipts[(item['prompt'],item['replica'])]=item pending = [item for item in assigned if (item["prompt"], item["replica"]) not in completed or not Path(item["video"]).is_file() or Path(item["video"]).stat().st_size == 0 or sha256(item['video']) != receipts[(item['prompt'],item['replica'])].get('video_sha256')] print(json.dumps({"method": plan["method"], "rank": rank, "assigned": len(assigned), "pending": len(pending), "checkpoint": str(checkpoint)}), flush=True) started = time.monotonic() count = 600 if pending: pipe, count = build_pipeline(plan, checkpoint, device) for ordinal, item in enumerate(pending, 1): torch.manual_seed(item["seed"]) random.seed(item["seed"]) np.random.seed(item["seed"]) with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): noise = torch.randn((1, 21, 16, 60, 104), device=device, dtype=torch.bfloat16) video = pipe.inference(noise=noise, text_prompts=[item["prompt"]], return_latents=False) if tuple(video.shape) != (1, 81, 3, 480, 832) or not torch.isfinite(video).all(): raise RuntimeError(f"Invalid generated video shape/values: {video.shape}") frames = (video[0].permute(0, 2, 3, 1).float().clamp(0, 1) * 255).round().to(torch.uint8).cpu().numpy() target = Path(item["video"]) temporary = target.with_name(target.stem + ".partial.mp4") from scripts.causal_baselines_b200.encode import encode encode(temporary, frames, output / ".encoding", fps=plan["fps"]) temporary.replace(target) record = {**item, "checkpoint_sha256": fingerprint, "frames": 81, "fps": 16, "height": 480, "width": 832, "bytes": target.stat().st_size, "video_sha256": sha256(target)} with journal.open("a") as handle: handle.write(json.dumps(record, ensure_ascii=False) + "\n") print(json.dumps({"rank": rank, "done": ordinal, "pending_total": len(pending), "prompt_index": item["prompt_index"], "replica": item["replica"]}), flush=True) del video, frames, noise write_json(output / f"generation-rank{rank}.json", { "passed": True, "method": plan["method"], "rank": rank, "world_size": world, "assigned_videos": len(assigned), "new_videos": len(pending), "checkpoint": str(checkpoint), "checkpoint_step": plan["checkpoint_step"], "checkpoint_sha256": fingerprint, "lora_tensor_count": count, "seconds": time.monotonic() - started, "generator_family": "causal_forcing", "sampler": plan["sampler"]}) if __name__ == "__main__": main()