import subprocess # not sure why it works in the original space but says "pip not found" in mine #subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True) from huggingface_hub import snapshot_download, hf_hub_download snapshot_download( repo_id="Wan-AI/Wan2.1-T2V-1.3B", local_dir="wan_models/Wan2.1-T2V-1.3B", local_dir_use_symlinks=False, resume_download=True, repo_type="model" ) hf_hub_download( repo_id="gdhe17/Self-Forcing", filename="checkpoints/self_forcing_dmd.pt", local_dir=".", local_dir_use_symlinks=False ) import os import re import random import argparse import hashlib import urllib.request import time from PIL import Image import torch import gradio as gr from omegaconf import OmegaConf from tqdm import tqdm import imageio import av import uuid from pipeline import CausalInferencePipeline from demo_utils.constant import ZERO_VAE_CACHE from demo_utils.vae_block3 import VAEDecoderWrapper from utils.wan_wrapper import WanDiffusionWrapper, WanTextEncoder from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM #, BitsAndBytesConfig import numpy as np device = "cuda" if torch.cuda.is_available() else "cpu" # --- Argument Parsing --- parser = argparse.ArgumentParser(description="Gradio Demo for Self-Forcing with Frame Streaming") parser.add_argument('--port', type=int, default=7860, help="Port to run the Gradio app on.") parser.add_argument('--host', type=str, default='0.0.0.0', help="Host to bind the Gradio app to.") parser.add_argument("--checkpoint_path", type=str, default='./checkpoints/self_forcing_dmd.pt', help="Path to the model checkpoint.") parser.add_argument("--config_path", type=str, default='./configs/self_forcing_dmd.yaml', help="Path to the model config.") parser.add_argument('--share', action='store_true', help="Create a public Gradio link.") parser.add_argument('--trt', action='store_true', help="Use TensorRT optimized VAE decoder.") parser.add_argument('--fps', type=float, default=15.0, help="Playback FPS for frame streaming.") args = parser.parse_args() gpu = "cuda" try: config = OmegaConf.load(args.config_path) default_config = OmegaConf.load("configs/default_config.yaml") config = OmegaConf.merge(default_config, config) except FileNotFoundError as e: print(f"Error loading config file: {e}\n. Please ensure config files are in the correct path.") exit(1) # Initialize Models print("Initializing models...") text_encoder = WanTextEncoder() transformer = WanDiffusionWrapper(is_causal=True) try: state_dict = torch.load(args.checkpoint_path, map_location="cpu") transformer.load_state_dict(state_dict.get('generator_ema', state_dict.get('generator'))) except FileNotFoundError as e: print(f"Error loading checkpoint: {e}\nPlease ensure the checkpoint '{args.checkpoint_path}' exists.") exit(1) text_encoder.eval().to(dtype=torch.float16).requires_grad_(False) transformer.eval().to(dtype=torch.float16).requires_grad_(False) text_encoder.to(gpu) transformer.to(gpu) APP_STATE = { "torch_compile_applied": False, "fp8_applied": False, "current_use_taehv": False, "current_vae_decoder": None, } # I've tried to enable it, but I didn't notice a significant performance improvement.. ENABLE_TORCH_COMPILATION = False # “default”: The default mode, used when no mode parameter is specified. It provides a good balance between performance and overhead. # “reduce-overhead”: Minimizes Python-related overhead using CUDA graphs. However, it may increase memory usage. # “max-autotune”: Uses Triton or template-based matrix multiplications on supported devices. It takes longer to compile but optimizes for the fastest possible execution. On GPUs it enables CUDA graphs by default. # “max-autotune-no-cudagraphs”: Similar to “max-autotune”, but without CUDA graphs. TORCH_COMPILATION_MODE = "default" # Apply torch.compile for maximum performance if not APP_STATE["torch_compile_applied"] and ENABLE_TORCH_COMPILATION: print("🚀 Applying torch.compile for speed optimization...") transformer.compile(mode=TORCH_COMPILATION_MODE) APP_STATE["torch_compile_applied"] = True print("✅ torch.compile applied to transformer") def frames_to_ts_file(frames, filepath, fps = 15): """ Convert frames directly to .ts file using PyAV. Args: frames: List of numpy arrays (HWC, RGB, uint8) filepath: Output file path fps: Frames per second Returns: The filepath of the created file """ if not frames: return filepath height, width = frames[0].shape[:2] # Create container for MPEG-TS format container = av.open(filepath, mode='w', format='mpegts') # Add video stream with optimized settings for streaming stream = container.add_stream('h264', rate=fps) stream.width = width stream.height = height stream.pix_fmt = 'yuv420p' # Optimize for low latency streaming stream.options = { 'preset': 'ultrafast', 'tune': 'zerolatency', 'crf': '23', 'profile': 'baseline', 'level': '3.0' } try: for frame_np in frames: frame = av.VideoFrame.from_ndarray(frame_np, format='rgb24') frame = frame.reformat(format=stream.pix_fmt) for packet in stream.encode(frame): container.mux(packet) for packet in stream.encode(): container.mux(packet) finally: container.close() return filepath def initialize_vae_decoder(use_taehv=False, use_trt=False): if use_trt: from demo_utils.vae import VAETRTWrapper print("Initializing TensorRT VAE Decoder...") vae_decoder = VAETRTWrapper() APP_STATE["current_use_taehv"] = False elif use_taehv: print("Initializing TAEHV VAE Decoder...") from demo_utils.taehv import TAEHV taehv_checkpoint_path = "checkpoints/taew2_1.pth" if not os.path.exists(taehv_checkpoint_path): print(f"Downloading TAEHV checkpoint to {taehv_checkpoint_path}...") os.makedirs("checkpoints", exist_ok=True) download_url = "https://github.com/madebyollin/taehv/raw/main/taew2_1.pth" try: urllib.request.urlretrieve(download_url, taehv_checkpoint_path) except Exception as e: raise RuntimeError(f"Failed to download taew2_1.pth: {e}") class DotDict(dict): __getattr__ = dict.get class TAEHVDiffusersWrapper(torch.nn.Module): def __init__(self): super().__init__() self.dtype = torch.float16 self.taehv = TAEHV(checkpoint_path=taehv_checkpoint_path).to(self.dtype) self.config = DotDict(scaling_factor=1.0) def decode(self, latents, return_dict=None): return self.taehv.decode_video(latents, parallel=not LOW_MEMORY).mul_(2).sub_(1) vae_decoder = TAEHVDiffusersWrapper() APP_STATE["current_use_taehv"] = True else: print("Initializing Default VAE Decoder...") vae_decoder = VAEDecoderWrapper() try: vae_state_dict = torch.load('wan_models/Wan2.1-T2V-1.3B/Wan2.1_VAE.pth', map_location="cpu") decoder_state_dict = {k: v for k, v in vae_state_dict.items() if 'decoder.' in k or 'conv2' in k} vae_decoder.load_state_dict(decoder_state_dict) except FileNotFoundError: print("Warning: Default VAE weights not found.") APP_STATE["current_use_taehv"] = False vae_decoder.eval().to(dtype=torch.float16).requires_grad_(False).to(gpu) # Apply torch.compile to VAE decoder if enabled (following demo.py pattern) if APP_STATE["torch_compile_applied"] and not use_taehv and not use_trt: print("🚀 Applying torch.compile to VAE decoder...") vae_decoder.compile(mode=TORCH_COMPILATION_MODE) print("✅ torch.compile applied to VAE decoder") APP_STATE["current_vae_decoder"] = vae_decoder print(f"✅ VAE decoder initialized: {'TAEHV' if use_taehv else 'Default VAE'}") # Initialize with default VAE initialize_vae_decoder(use_taehv=False, use_trt=args.trt) pipeline = CausalInferencePipeline( config, device=gpu, generator=transformer, text_encoder=text_encoder, vae=APP_STATE["current_vae_decoder"] ) pipeline.to(dtype=torch.float16).to(gpu) @torch.no_grad() def video_generation_handler_streaming(prompt, seed=42, fps=15, width=400, height=224, duration=5, buffering=2): """ Generator function that yields .ts video chunks using PyAV for streaming. Now optimized for block-based processing. """ if seed == -1: seed = random.randint(0, 2**32 - 1) print(f"🎬 Starting PyAV streaming: '{prompt}', seed: {seed}, duration: {duration}s, buffering: {buffering}s") # Buffering delay if buffering > 0: buffering_status_html = ( f"
⏳ Buffering...
" f"Waiting {buffering} seconds before starting stream
" f"Generating Video...
" f" " f"" f" Block {idx+1}/{num_blocks} | Frame {total_frames_yielded} | {total_progress:.1f}%" f"
" f"" f" 📊 Generated {total_frames_yielded} frames across {num_blocks} blocks" f"
" f"" f" 🎬 Playback: {fps} FPS • 📁 Format: MPEG-TS/H.264" f"
" f"