Spaces:
Runtime error
Runtime error
Upload 9 files
Browse files- README.md +11 -13
- app.py +512 -228
- optimization.py +85 -12
- optimization_utils.py +28 -17
- requirements.txt +11 -5
README.md
CHANGED
|
@@ -1,14 +1,12 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo: gray
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.29.1
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned:
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
---
|
| 13 |
-
|
| 14 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Wan 2 2 First Last Frame
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: gray
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.29.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
|
|
|
|
|
|
| 12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
|
@@ -1,228 +1,512 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
|
| 4 |
-
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
from
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
image
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
gr.
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
gr.
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
# PyTorch 2.8 (temporary hack)
|
| 3 |
+
os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
|
| 4 |
+
|
| 5 |
+
# --- 1. Model Download and Setup (Diffusers Backend) ---
|
| 6 |
+
try:
|
| 7 |
+
import spaces
|
| 8 |
+
except:
|
| 9 |
+
class spaces():
|
| 10 |
+
def GPU(*args, **kwargs):
|
| 11 |
+
def decorator(function):
|
| 12 |
+
return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
|
| 13 |
+
return decorator
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 17 |
+
from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
|
| 18 |
+
from diffusers.models.transformers.transformer_wan import WanTransformer3DModel
|
| 19 |
+
from diffusers.utils.export_utils import export_to_video
|
| 20 |
+
import gradio as gr
|
| 21 |
+
import tempfile
|
| 22 |
+
import time
|
| 23 |
+
from datetime import datetime
|
| 24 |
+
import numpy as np
|
| 25 |
+
from PIL import Image
|
| 26 |
+
import random
|
| 27 |
+
import math
|
| 28 |
+
import gc
|
| 29 |
+
from gradio_client import Client, handle_file # Import for API call
|
| 30 |
+
|
| 31 |
+
# Import the optimization function from the separate file
|
| 32 |
+
from optimization import optimize_pipeline_
|
| 33 |
+
|
| 34 |
+
# --- Constants and Model Loading ---
|
| 35 |
+
MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
|
| 36 |
+
|
| 37 |
+
# --- NEW: Flexible Dimension Constants ---
|
| 38 |
+
MAX_DIMENSION = 832
|
| 39 |
+
MIN_DIMENSION = 480
|
| 40 |
+
DIMENSION_MULTIPLE = 16
|
| 41 |
+
SQUARE_SIZE = 480
|
| 42 |
+
|
| 43 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 44 |
+
|
| 45 |
+
FIXED_FPS = 24
|
| 46 |
+
MIN_FRAMES_MODEL = 8
|
| 47 |
+
MAX_FRAMES_MODEL = 81
|
| 48 |
+
|
| 49 |
+
MIN_DURATION = round(MIN_FRAMES_MODEL/FIXED_FPS, 1)
|
| 50 |
+
MAX_DURATION = round(MAX_FRAMES_MODEL/FIXED_FPS, 1)
|
| 51 |
+
|
| 52 |
+
input_image_debug_value = [None]
|
| 53 |
+
end_image_debug_value = [None]
|
| 54 |
+
prompt_debug_value = [None]
|
| 55 |
+
total_second_length_debug_value = [None]
|
| 56 |
+
|
| 57 |
+
default_negative_prompt = "Vibrant colors, overexposure, static, blurred details, subtitles, error, style, artwork, painting, image, still, overall gray, worst quality, low quality, JPEG compression residue, ugly, mutilated, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, malformed limbs, fused fingers, still image, cluttered background, three legs, many people in the background, walking backwards, overexposure, jumpcut, crossfader, "
|
| 58 |
+
|
| 59 |
+
print("Loading transformer...")
|
| 60 |
+
|
| 61 |
+
transformer = WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
| 62 |
+
subfolder='transformer',
|
| 63 |
+
torch_dtype=torch.bfloat16,
|
| 64 |
+
device_map='cuda',
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
print("Loadingtransformer 2...")
|
| 68 |
+
|
| 69 |
+
transformer_2 = WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
| 70 |
+
subfolder='transformer_2',
|
| 71 |
+
torch_dtype=torch.bfloat16,
|
| 72 |
+
device_map='cuda',
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
print("Loading models into memory. This may take a few minutes...")
|
| 76 |
+
|
| 77 |
+
pipe = WanImageToVideoPipeline.from_pretrained(
|
| 78 |
+
MODEL_ID,
|
| 79 |
+
transformer = transformer,
|
| 80 |
+
transformer_2 = transformer_2,
|
| 81 |
+
torch_dtype=torch.bfloat16,
|
| 82 |
+
)
|
| 83 |
+
print("Loading scheduler...")
|
| 84 |
+
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, shift=8.0)
|
| 85 |
+
pipe.to('cuda')
|
| 86 |
+
|
| 87 |
+
print("Clean cache...")
|
| 88 |
+
for i in range(3):
|
| 89 |
+
gc.collect()
|
| 90 |
+
torch.cuda.synchronize()
|
| 91 |
+
torch.cuda.empty_cache()
|
| 92 |
+
|
| 93 |
+
print("Optimizing pipeline...")
|
| 94 |
+
|
| 95 |
+
optimize_pipeline_(pipe,
|
| 96 |
+
image=Image.new('RGB', (MAX_DIMENSION, MIN_DIMENSION)),
|
| 97 |
+
prompt='prompt',
|
| 98 |
+
height=MIN_DIMENSION,
|
| 99 |
+
width=MAX_DIMENSION,
|
| 100 |
+
num_frames=MAX_FRAMES_MODEL,
|
| 101 |
+
)
|
| 102 |
+
print("All models loaded and optimized. Gradio app is ready.")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# --- 2. Image Processing and Application Logic ---
|
| 106 |
+
def generate_end_frame(start_img, gen_prompt, progress=gr.Progress(track_tqdm=True)):
|
| 107 |
+
"""Calls an external Gradio API to generate an image."""
|
| 108 |
+
if start_img is None:
|
| 109 |
+
raise gr.Error("Please provide a Start Frame first.")
|
| 110 |
+
|
| 111 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 112 |
+
if not hf_token:
|
| 113 |
+
raise gr.Error("HF_TOKEN not found in environment variables. Please set it in your Space secrets.")
|
| 114 |
+
|
| 115 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
|
| 116 |
+
start_img.save(tmpfile.name)
|
| 117 |
+
tmp_path = tmpfile.name
|
| 118 |
+
|
| 119 |
+
progress(0.1, desc="Connecting to image generation API...")
|
| 120 |
+
client = Client("multimodalart/nano-banana-private")
|
| 121 |
+
|
| 122 |
+
progress(0.5, desc=f"Generating with prompt: '{gen_prompt}'...")
|
| 123 |
+
try:
|
| 124 |
+
result = client.predict(
|
| 125 |
+
prompt=gen_prompt,
|
| 126 |
+
images=[
|
| 127 |
+
{"image": handle_file(tmp_path)}
|
| 128 |
+
],
|
| 129 |
+
manual_token=hf_token,
|
| 130 |
+
api_name="/unified_image_generator"
|
| 131 |
+
)
|
| 132 |
+
finally:
|
| 133 |
+
os.remove(tmp_path)
|
| 134 |
+
|
| 135 |
+
progress(1.0, desc="Done!")
|
| 136 |
+
print(result)
|
| 137 |
+
return result
|
| 138 |
+
|
| 139 |
+
def switch_to_upload_tab():
|
| 140 |
+
"""Returns a gr.Tabs update to switch to the first tab."""
|
| 141 |
+
return gr.Tabs(selected="upload_tab")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def process_image_for_video(image: Image.Image) -> Image.Image:
|
| 145 |
+
"""
|
| 146 |
+
Resizes an image based on the following rules for video generation:
|
| 147 |
+
1. The longest side will be scaled down to MAX_DIMENSION if it's larger.
|
| 148 |
+
2. The shortest side will be scaled up to MIN_DIMENSION if it's smaller.
|
| 149 |
+
3. The final dimensions will be rounded to the nearest multiple of DIMENSION_MULTIPLE.
|
| 150 |
+
4. Square images are resized to a fixed SQUARE_SIZE.
|
| 151 |
+
The aspect ratio is preserved as closely as possible.
|
| 152 |
+
"""
|
| 153 |
+
width, height = image.size
|
| 154 |
+
|
| 155 |
+
# Rule 4: Handle square images
|
| 156 |
+
if width == height:
|
| 157 |
+
return image.resize((SQUARE_SIZE, SQUARE_SIZE), Image.Resampling.LANCZOS)
|
| 158 |
+
|
| 159 |
+
# Determine target dimensions while preserving aspect ratio
|
| 160 |
+
aspect_ratio = width / height
|
| 161 |
+
new_width, new_height = width, height
|
| 162 |
+
|
| 163 |
+
# Rule 1: Scale down if too large
|
| 164 |
+
if new_width > MAX_DIMENSION or new_height > MAX_DIMENSION:
|
| 165 |
+
if aspect_ratio > 1: # Landscape
|
| 166 |
+
scale = MAX_DIMENSION / new_width
|
| 167 |
+
else: # Portrait
|
| 168 |
+
scale = MAX_DIMENSION / new_height
|
| 169 |
+
new_width *= scale
|
| 170 |
+
new_height *= scale
|
| 171 |
+
|
| 172 |
+
# Rule 2: Scale up if too small
|
| 173 |
+
if new_width < MIN_DIMENSION or new_height < MIN_DIMENSION:
|
| 174 |
+
if aspect_ratio > 1: # Landscape
|
| 175 |
+
scale = MIN_DIMENSION / new_height
|
| 176 |
+
else: # Portrait
|
| 177 |
+
scale = MIN_DIMENSION / new_width
|
| 178 |
+
new_width *= scale
|
| 179 |
+
new_height *= scale
|
| 180 |
+
|
| 181 |
+
# Rule 3: Round to the nearest multiple of DIMENSION_MULTIPLE
|
| 182 |
+
final_width = int(round(new_width / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 183 |
+
final_height = int(round(new_height / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 184 |
+
|
| 185 |
+
# Ensure final dimensions are at least the minimum
|
| 186 |
+
final_width = max(final_width, MIN_DIMENSION if aspect_ratio < 1 else SQUARE_SIZE)
|
| 187 |
+
final_height = max(final_height, MIN_DIMENSION if aspect_ratio > 1 else SQUARE_SIZE)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
return image.resize((final_width, final_height), Image.Resampling.LANCZOS)
|
| 191 |
+
|
| 192 |
+
def resize_and_crop_to_match(target_image, reference_image):
|
| 193 |
+
"""Resizes and center-crops the target image to match the reference image's dimensions."""
|
| 194 |
+
ref_width, ref_height = reference_image.size
|
| 195 |
+
target_width, target_height = target_image.size
|
| 196 |
+
scale = max(ref_width / target_width, ref_height / target_height)
|
| 197 |
+
new_width, new_height = int(target_width * scale), int(target_height * scale)
|
| 198 |
+
resized = target_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 199 |
+
left, top = (new_width - ref_width) // 2, (new_height - ref_height) // 2
|
| 200 |
+
return resized.crop((left, top, left + ref_width, top + ref_height))
|
| 201 |
+
|
| 202 |
+
def init_view():
|
| 203 |
+
return gr.update(interactive = True)
|
| 204 |
+
|
| 205 |
+
def generate_video(
|
| 206 |
+
start_image_pil,
|
| 207 |
+
end_image_pil,
|
| 208 |
+
prompt,
|
| 209 |
+
negative_prompt=default_negative_prompt,
|
| 210 |
+
duration_seconds=2.1,
|
| 211 |
+
steps=8,
|
| 212 |
+
guidance_scale=1,
|
| 213 |
+
guidance_scale_2=1,
|
| 214 |
+
seed=42,
|
| 215 |
+
randomize_seed=True,
|
| 216 |
+
progress=gr.Progress(track_tqdm=True)
|
| 217 |
+
):
|
| 218 |
+
start = time.time()
|
| 219 |
+
allocation_time = 120
|
| 220 |
+
factor = 1
|
| 221 |
+
|
| 222 |
+
if input_image_debug_value[0] is not None or end_image_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None:
|
| 223 |
+
start_image_pil = input_image_debug_value[0]
|
| 224 |
+
end_image_pil = end_image_debug_value[0]
|
| 225 |
+
prompt = prompt_debug_value[0]
|
| 226 |
+
duration_seconds = total_second_length_debug_value[0]
|
| 227 |
+
allocation_time = min(duration_seconds * 60 * 100, 10 * 60)
|
| 228 |
+
factor = 3.1
|
| 229 |
+
|
| 230 |
+
if start_image_pil is None or end_image_pil is None:
|
| 231 |
+
raise gr.Error("Please upload both a start and an end image.")
|
| 232 |
+
|
| 233 |
+
# Step 1: Process the start image to get our target dimensions based on the new rules.
|
| 234 |
+
processed_start_image = process_image_for_video(start_image_pil)
|
| 235 |
+
|
| 236 |
+
# Step 2: Make the end image match the *exact* dimensions of the processed start image.
|
| 237 |
+
processed_end_image = resize_and_crop_to_match(end_image_pil, processed_start_image)
|
| 238 |
+
|
| 239 |
+
target_height, target_width = processed_start_image.height, processed_start_image.width
|
| 240 |
+
|
| 241 |
+
# Handle seed and frame count
|
| 242 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 243 |
+
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
| 244 |
+
|
| 245 |
+
progress(0.2, desc=f"Generating {num_frames} frames at {target_width}x{target_height} (seed: {current_seed})...")
|
| 246 |
+
|
| 247 |
+
progress(0.1, desc="Preprocessing images...")
|
| 248 |
+
output_video, download_button, seed_input = generate_video_on_gpu(
|
| 249 |
+
start_image_pil,
|
| 250 |
+
end_image_pil,
|
| 251 |
+
prompt,
|
| 252 |
+
negative_prompt,
|
| 253 |
+
duration_seconds,
|
| 254 |
+
steps,
|
| 255 |
+
guidance_scale,
|
| 256 |
+
guidance_scale_2,
|
| 257 |
+
seed,
|
| 258 |
+
randomize_seed,
|
| 259 |
+
progress,
|
| 260 |
+
allocation_time,
|
| 261 |
+
factor,
|
| 262 |
+
target_height,
|
| 263 |
+
target_width,
|
| 264 |
+
current_seed,
|
| 265 |
+
num_frames,
|
| 266 |
+
processed_start_image,
|
| 267 |
+
processed_end_image
|
| 268 |
+
)
|
| 269 |
+
progress(1.0, desc="Done!")
|
| 270 |
+
end = time.time()
|
| 271 |
+
secondes = int(end - start)
|
| 272 |
+
minutes = math.floor(secondes / 60)
|
| 273 |
+
secondes = secondes - (minutes * 60)
|
| 274 |
+
hours = math.floor(minutes / 60)
|
| 275 |
+
minutes = minutes - (hours * 60)
|
| 276 |
+
information = ("Start the process again if you want a different result. " if randomize_seed else "") + \
|
| 277 |
+
"The video been generated in " + \
|
| 278 |
+
((str(hours) + " h, ") if hours != 0 else "") + \
|
| 279 |
+
((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
|
| 280 |
+
str(secondes) + " sec. " + \
|
| 281 |
+
"The video resolution is " + str(target_width) + \
|
| 282 |
+
" pixels large and " + str(target_height) + \
|
| 283 |
+
" pixels high, so a resolution of " + f'{target_width * target_height:,}' + " pixels."
|
| 284 |
+
return [output_video, download_button, seed_input, gr.update(value = information, visible = True), gr.update(interactive = False)]
|
| 285 |
+
|
| 286 |
+
def get_duration(
|
| 287 |
+
start_image_pil,
|
| 288 |
+
end_image_pil,
|
| 289 |
+
prompt,
|
| 290 |
+
negative_prompt,
|
| 291 |
+
duration_seconds,
|
| 292 |
+
steps,
|
| 293 |
+
guidance_scale,
|
| 294 |
+
guidance_scale_2,
|
| 295 |
+
seed,
|
| 296 |
+
randomize_seed,
|
| 297 |
+
progress,
|
| 298 |
+
allocation_time,
|
| 299 |
+
factor,
|
| 300 |
+
target_height,
|
| 301 |
+
target_width,
|
| 302 |
+
current_seed,
|
| 303 |
+
num_frames,
|
| 304 |
+
processed_start_image,
|
| 305 |
+
processed_end_image
|
| 306 |
+
):
|
| 307 |
+
return allocation_time
|
| 308 |
+
|
| 309 |
+
@spaces.GPU(duration=get_duration)
|
| 310 |
+
def generate_video_on_gpu(
|
| 311 |
+
start_image_pil,
|
| 312 |
+
end_image_pil,
|
| 313 |
+
prompt,
|
| 314 |
+
negative_prompt,
|
| 315 |
+
duration_seconds,
|
| 316 |
+
steps,
|
| 317 |
+
guidance_scale,
|
| 318 |
+
guidance_scale_2,
|
| 319 |
+
seed,
|
| 320 |
+
randomize_seed,
|
| 321 |
+
progress,
|
| 322 |
+
allocation_time,
|
| 323 |
+
factor,
|
| 324 |
+
target_height,
|
| 325 |
+
target_width,
|
| 326 |
+
current_seed,
|
| 327 |
+
num_frames,
|
| 328 |
+
processed_start_image,
|
| 329 |
+
processed_end_image
|
| 330 |
+
):
|
| 331 |
+
"""
|
| 332 |
+
Generates a video by interpolating between a start and end image, guided by a text prompt,
|
| 333 |
+
using the diffusers Wan2.2 pipeline.
|
| 334 |
+
"""
|
| 335 |
+
print("Generate a video with the prompt: " + prompt)
|
| 336 |
+
|
| 337 |
+
output_frames_list = pipe(
|
| 338 |
+
image=processed_start_image,
|
| 339 |
+
last_image=processed_end_image,
|
| 340 |
+
prompt=prompt,
|
| 341 |
+
negative_prompt=negative_prompt,
|
| 342 |
+
height=target_height,
|
| 343 |
+
width=target_width,
|
| 344 |
+
num_frames=int(num_frames * factor),
|
| 345 |
+
guidance_scale=float(guidance_scale),
|
| 346 |
+
guidance_scale_2=float(guidance_scale_2),
|
| 347 |
+
num_inference_steps=int(steps),
|
| 348 |
+
generator=torch.Generator(device="cuda").manual_seed(current_seed),
|
| 349 |
+
).frames[0]
|
| 350 |
+
|
| 351 |
+
progress(0.9, desc="Encoding and saving video...")
|
| 352 |
+
|
| 353 |
+
video_path = 'wan_' + datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f") + '.mp4'
|
| 354 |
+
|
| 355 |
+
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
| 356 |
+
print("Video exported: " + video_path)
|
| 357 |
+
|
| 358 |
+
return video_path, gr.update(value = video_path, visible = True), current_seed
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
# --- 3. Gradio User Interface ---
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
js = """
|
| 366 |
+
function createGradioAnimation() {
|
| 367 |
+
window.addEventListener("beforeunload", function(e) {
|
| 368 |
+
if (document.getElementById('dummy_button_id') && !document.getElementById('dummy_button_id').disabled) {
|
| 369 |
+
var confirmationMessage = 'A process is still running. '
|
| 370 |
+
+ 'If you leave before saving, your changes will be lost.';
|
| 371 |
+
|
| 372 |
+
(e || window.event).returnValue = confirmationMessage;
|
| 373 |
+
}
|
| 374 |
+
return confirmationMessage;
|
| 375 |
+
});
|
| 376 |
+
return 'Animation created';
|
| 377 |
+
}
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
# Gradio interface
|
| 381 |
+
with gr.Blocks(js=js) as app:
|
| 382 |
+
gr.Markdown("# Wan 2.2 First/Last Frame Video Fast")
|
| 383 |
+
gr.Markdown("Based on the [Wan 2.2 First/Last Frame workflow](https://www.reddit.com/r/StableDiffusion/comments/1me4306/psa_wan_22_does_first_frame_last_frame_out_of_the/), applied to 🧨 Diffusers + [lightx2v/Wan2.2-Lightning](https://huggingface.co/lightx2v/Wan2.2-Lightning) 8-step LoRA")
|
| 384 |
+
|
| 385 |
+
with gr.Row(elem_id="general_items"):
|
| 386 |
+
with gr.Column():
|
| 387 |
+
with gr.Group(elem_id="group_all"):
|
| 388 |
+
with gr.Row():
|
| 389 |
+
start_image = gr.Image(type="pil", label="Start Frame", sources=["upload", "clipboard"])
|
| 390 |
+
# Capture the Tabs component in a variable and assign IDs to tabs
|
| 391 |
+
with gr.Tabs(elem_id="group_tabs") as tabs:
|
| 392 |
+
with gr.TabItem("Upload", id="upload_tab"):
|
| 393 |
+
end_image = gr.Image(type="pil", label="End Frame", sources=["upload", "clipboard"])
|
| 394 |
+
with gr.TabItem("Generate", id="generate_tab"):
|
| 395 |
+
generate_5seconds = gr.Button("Generate scene 5 seconds in the future", elem_id="fivesec")
|
| 396 |
+
gr.Markdown("Generate a custom end-frame with an edit model like [Nano Banana](https://huggingface.co/spaces/multimodalart/nano-banana) or [Qwen Image Edit](https://huggingface.co/spaces/multimodalart/Qwen-Image-Edit-Fast)", elem_id="or_item")
|
| 397 |
+
prompt = gr.Textbox(label="Prompt", info="Describe the transition between the two images")
|
| 398 |
+
|
| 399 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 400 |
+
duration_seconds_input = gr.Slider(minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=2.1, label="Video Duration (seconds)", info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.")
|
| 401 |
+
negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
|
| 402 |
+
steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=8, label="Inference Steps")
|
| 403 |
+
guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1.0, label="Guidance Scale - high noise")
|
| 404 |
+
guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1.0, label="Guidance Scale - low noise")
|
| 405 |
+
with gr.Row():
|
| 406 |
+
seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
|
| 407 |
+
randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True)
|
| 408 |
+
|
| 409 |
+
generate_button = gr.Button("Generate Video", variant="primary")
|
| 410 |
+
dummy_button = gr.Button(elem_id = "dummy_button_id", visible = False, interactive = False)
|
| 411 |
+
|
| 412 |
+
with gr.Column():
|
| 413 |
+
output_video = gr.Video(label="Generated Video", autoplay = True, loop = True)
|
| 414 |
+
download_button = gr.DownloadButton(label="Download", visible = True)
|
| 415 |
+
video_information = gr.HTML(value = "", visible = True)
|
| 416 |
+
|
| 417 |
+
# Main video generation button
|
| 418 |
+
ui_inputs = [
|
| 419 |
+
start_image,
|
| 420 |
+
end_image,
|
| 421 |
+
prompt,
|
| 422 |
+
negative_prompt_input,
|
| 423 |
+
duration_seconds_input,
|
| 424 |
+
steps_slider,
|
| 425 |
+
guidance_scale_input,
|
| 426 |
+
guidance_scale_2_input,
|
| 427 |
+
seed_input,
|
| 428 |
+
randomize_seed_checkbox
|
| 429 |
+
]
|
| 430 |
+
ui_outputs = [output_video, download_button, seed_input, video_information, dummy_button]
|
| 431 |
+
|
| 432 |
+
generate_button.click(fn = init_view, inputs = [], outputs = [dummy_button], queue = False, show_progress = False).success(
|
| 433 |
+
fn = generate_video,
|
| 434 |
+
inputs = ui_inputs,
|
| 435 |
+
outputs = ui_outputs
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
generate_5seconds.click(
|
| 439 |
+
fn=switch_to_upload_tab,
|
| 440 |
+
inputs=None,
|
| 441 |
+
outputs=[tabs]
|
| 442 |
+
).then(
|
| 443 |
+
fn=lambda img: generate_end_frame(img, "this image is a still frame from a movie. generate a new frame with what happens on this scene 5 seconds in the future"),
|
| 444 |
+
inputs=[start_image],
|
| 445 |
+
outputs=[end_image]
|
| 446 |
+
).success(
|
| 447 |
+
fn=generate_video,
|
| 448 |
+
inputs=ui_inputs,
|
| 449 |
+
outputs=ui_outputs
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
with gr.Row(visible=False):
|
| 453 |
+
prompt_debug=gr.Textbox(label="Prompt Debug")
|
| 454 |
+
input_image_debug=gr.Image(type="pil", label="Image Debug")
|
| 455 |
+
end_image_debug=gr.Image(type="pil", label="End Image Debug")
|
| 456 |
+
total_second_length_debug=gr.Slider(label="Additional Video Length to Generate (seconds) Debug", minimum=1, maximum=120, value=10, step=0.1)
|
| 457 |
+
gr.Examples(
|
| 458 |
+
examples=[["Schoolboy_without_backpack.webp", "Schoolboy_with_backpack.webp", "The schoolboy puts on his schoolbag."]],
|
| 459 |
+
inputs=[start_image, end_image, prompt],
|
| 460 |
+
outputs=ui_outputs,
|
| 461 |
+
fn=generate_video,
|
| 462 |
+
run_on_click=True,
|
| 463 |
+
cache_examples=True,
|
| 464 |
+
cache_mode='lazy',
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
gr.Examples(
|
| 468 |
+
label = "Examples from demo",
|
| 469 |
+
examples = [
|
| 470 |
+
["poli_tower.png", "tower_takes_off.png", "The man turns around."],
|
| 471 |
+
["ugly_sonic.jpeg", "squatting_sonic.png", "पात्रं क्षेपणास्त्रं चकमाति।"],
|
| 472 |
+
["Schoolboy_without_backpack.webp", "Schoolboy_with_backpack.webp", "The schoolboy puts on his schoolbag."],
|
| 473 |
+
],
|
| 474 |
+
inputs = [start_image, end_image, prompt],
|
| 475 |
+
outputs = ui_outputs,
|
| 476 |
+
fn = generate_video,
|
| 477 |
+
cache_examples = False,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
def handle_field_debug_change(input_image_debug_data, end_image_debug_data, prompt_debug_data, total_second_length_debug_data):
|
| 481 |
+
input_image_debug_value[0] = input_image_debug_data
|
| 482 |
+
end_image_debug_value[0] = end_image_debug_data
|
| 483 |
+
prompt_debug_value[0] = prompt_debug_data
|
| 484 |
+
total_second_length_debug_value[0] = total_second_length_debug_data
|
| 485 |
+
return []
|
| 486 |
+
|
| 487 |
+
input_image_debug.upload(
|
| 488 |
+
fn=handle_field_debug_change,
|
| 489 |
+
inputs=[input_image_debug, end_image_debug, prompt_debug, total_second_length_debug],
|
| 490 |
+
outputs=[]
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
end_image_debug.upload(
|
| 494 |
+
fn=handle_field_debug_change,
|
| 495 |
+
inputs=[input_image_debug, end_image_debug, prompt_debug, total_second_length_debug],
|
| 496 |
+
outputs=[]
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
prompt_debug.change(
|
| 500 |
+
fn=handle_field_debug_change,
|
| 501 |
+
inputs=[input_image_debug, end_image_debug, prompt_debug, total_second_length_debug],
|
| 502 |
+
outputs=[]
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
total_second_length_debug.change(
|
| 506 |
+
fn=handle_field_debug_change,
|
| 507 |
+
inputs=[input_image_debug, end_image_debug, prompt_debug, total_second_length_debug],
|
| 508 |
+
outputs=[]
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
if __name__ == "__main__":
|
| 512 |
+
app.launch(mcp_server=True, share=True)
|
optimization.py
CHANGED
|
@@ -8,21 +8,49 @@ from typing import ParamSpec
|
|
| 8 |
import spaces
|
| 9 |
import torch
|
| 10 |
from torch.utils._pytree import tree_map_only
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
from optimization_utils import capture_component_call
|
| 13 |
from optimization_utils import aoti_compile
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
P = ParamSpec('P')
|
| 17 |
|
|
|
|
| 18 |
|
| 19 |
-
|
|
|
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
| 22 |
-
'hidden_states': {
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
| 24 |
}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
INDUCTOR_CONFIGS = {
|
| 27 |
'conv_1x1_as_mm': True,
|
| 28 |
'epilogue_fusion': False,
|
|
@@ -37,24 +65,69 @@ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kw
|
|
| 37 |
|
| 38 |
@spaces.GPU(duration=1500)
|
| 39 |
def compile_transformer():
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
with capture_component_call(pipeline, 'transformer') as call:
|
| 42 |
pipeline(*args, **kwargs)
|
| 43 |
-
|
| 44 |
dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
|
| 45 |
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
mod=pipeline.transformer,
|
| 51 |
args=call.args,
|
| 52 |
kwargs=call.kwargs,
|
| 53 |
dynamic_shapes=dynamic_shapes,
|
| 54 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
pipeline.
|
| 60 |
-
pipeline.transformer.config = transformer_config # pyright: ignore[reportAttributeAccessIssue]
|
|
|
|
| 8 |
import spaces
|
| 9 |
import torch
|
| 10 |
from torch.utils._pytree import tree_map_only
|
| 11 |
+
from torchao.quantization import quantize_
|
| 12 |
+
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig
|
| 13 |
+
from torchao.quantization import Int8WeightOnlyConfig
|
| 14 |
|
| 15 |
from optimization_utils import capture_component_call
|
| 16 |
from optimization_utils import aoti_compile
|
| 17 |
+
from optimization_utils import drain_module_parameters
|
| 18 |
|
| 19 |
|
| 20 |
P = ParamSpec('P')
|
| 21 |
|
| 22 |
+
# --- CORRECTED DYNAMIC SHAPING ---
|
| 23 |
|
| 24 |
+
# VAE temporal scale factor is 1, latent_frames = num_frames. Range is [8, 81].
|
| 25 |
+
LATENT_FRAMES_DIM = torch.export.Dim('num_latent_frames', min=8, max=81)
|
| 26 |
|
| 27 |
+
# The transformer has a patch_size of (1, 2, 2), which means the input latent height and width
|
| 28 |
+
# are effectively divided by 2. This creates constraints that fail if the symbolic tracer
|
| 29 |
+
# assumes odd numbers are possible.
|
| 30 |
+
#
|
| 31 |
+
# To solve this, we define the dynamic dimension for the *patched* (i.e., post-division) size,
|
| 32 |
+
# and then express the input shape as 2 * this dimension. This mathematically guarantees
|
| 33 |
+
# to the compiler that the input latent dimensions are always even, satisfying the constraints.
|
| 34 |
+
|
| 35 |
+
# App range for pixel dimensions: [480, 832]. VAE scale factor is 8.
|
| 36 |
+
# Latent dimension range: [480/8, 832/8] = [60, 104].
|
| 37 |
+
# Patched latent dimension range: [60/2, 104/2] = [30, 52].
|
| 38 |
+
LATENT_PATCHED_HEIGHT_DIM = torch.export.Dim('latent_patched_height', min=30, max=52)
|
| 39 |
+
LATENT_PATCHED_WIDTH_DIM = torch.export.Dim('latent_patched_width', min=30, max=52)
|
| 40 |
+
|
| 41 |
+
# Now, we define the dynamic shapes for the transformer's `hidden_states` input,
|
| 42 |
+
# which has the shape (batch_size, channels, num_frames, height, width).
|
| 43 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
| 44 |
+
'hidden_states': {
|
| 45 |
+
2: LATENT_FRAMES_DIM,
|
| 46 |
+
3: 2 * LATENT_PATCHED_HEIGHT_DIM, # Guarantees even height
|
| 47 |
+
4: 2 * LATENT_PATCHED_WIDTH_DIM, # Guarantees even width
|
| 48 |
+
},
|
| 49 |
}
|
| 50 |
|
| 51 |
+
# --- END OF CORRECTION ---
|
| 52 |
+
|
| 53 |
+
|
| 54 |
INDUCTOR_CONFIGS = {
|
| 55 |
'conv_1x1_as_mm': True,
|
| 56 |
'epilogue_fusion': False,
|
|
|
|
| 65 |
|
| 66 |
@spaces.GPU(duration=1500)
|
| 67 |
def compile_transformer():
|
| 68 |
+
|
| 69 |
+
# This LoRA fusion part remains the same
|
| 70 |
+
pipeline.load_lora_weights(
|
| 71 |
+
"Kijai/WanVideo_comfy",
|
| 72 |
+
weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",
|
| 73 |
+
adapter_name="lightx2v"
|
| 74 |
+
)
|
| 75 |
+
kwargs_lora = {}
|
| 76 |
+
kwargs_lora["load_into_transformer_2"] = True
|
| 77 |
+
pipeline.load_lora_weights(
|
| 78 |
+
"Kijai/WanVideo_comfy",
|
| 79 |
+
weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",
|
| 80 |
+
adapter_name="lightx2v_2", **kwargs_lora
|
| 81 |
+
)
|
| 82 |
+
pipeline.set_adapters(["lightx2v", "lightx2v_2"], adapter_weights=[1., 1.])
|
| 83 |
+
pipeline.fuse_lora(adapter_names=["lightx2v"], lora_scale=3., components=["transformer"])
|
| 84 |
+
pipeline.fuse_lora(adapter_names=["lightx2v_2"], lora_scale=1., components=["transformer_2"])
|
| 85 |
+
pipeline.unload_lora_weights()
|
| 86 |
+
|
| 87 |
+
# Capture a single call to get the args/kwargs structure
|
| 88 |
with capture_component_call(pipeline, 'transformer') as call:
|
| 89 |
pipeline(*args, **kwargs)
|
| 90 |
+
|
| 91 |
dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
|
| 92 |
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
| 93 |
|
| 94 |
+
# Quantization remains the same
|
| 95 |
+
quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 96 |
+
quantize_(pipeline.transformer_2, Float8DynamicActivationFloat8WeightConfig())
|
| 97 |
+
|
| 98 |
+
# --- SIMPLIFIED COMPILATION ---
|
| 99 |
+
|
| 100 |
+
exported_1 = torch.export.export(
|
| 101 |
mod=pipeline.transformer,
|
| 102 |
args=call.args,
|
| 103 |
kwargs=call.kwargs,
|
| 104 |
dynamic_shapes=dynamic_shapes,
|
| 105 |
)
|
| 106 |
+
|
| 107 |
+
exported_2 = torch.export.export(
|
| 108 |
+
mod=pipeline.transformer_2,
|
| 109 |
+
args=call.args,
|
| 110 |
+
kwargs=call.kwargs,
|
| 111 |
+
dynamic_shapes=dynamic_shapes,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
compiled_1 = aoti_compile(exported_1, INDUCTOR_CONFIGS)
|
| 115 |
+
compiled_2 = aoti_compile(exported_2, INDUCTOR_CONFIGS)
|
| 116 |
+
|
| 117 |
+
# Return the two compiled models
|
| 118 |
+
return compiled_1, compiled_2
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# Quantize text encoder (same as before)
|
| 122 |
+
quantize_(pipeline.text_encoder, Int8WeightOnlyConfig())
|
| 123 |
+
|
| 124 |
+
# Get the two dynamically-shaped compiled models
|
| 125 |
+
compiled_transformer_1, compiled_transformer_2 = compile_transformer()
|
| 126 |
|
| 127 |
+
# --- SIMPLIFIED ASSIGNMENT ---
|
| 128 |
+
|
| 129 |
+
pipeline.transformer.forward = compiled_transformer_1
|
| 130 |
+
drain_module_parameters(pipeline.transformer)
|
| 131 |
|
| 132 |
+
pipeline.transformer_2.forward = compiled_transformer_2
|
| 133 |
+
drain_module_parameters(pipeline.transformer_2)
|
|
|
optimization_utils.py
CHANGED
|
@@ -10,7 +10,6 @@ from unittest.mock import patch
|
|
| 10 |
import torch
|
| 11 |
from torch._inductor.package.package import package_aoti
|
| 12 |
from torch.export.pt2_archive._package import AOTICompiledModel
|
| 13 |
-
from torch.export.pt2_archive._package_weights import TensorProperties
|
| 14 |
from torch.export.pt2_archive._package_weights import Weights
|
| 15 |
|
| 16 |
|
|
@@ -21,31 +20,33 @@ INDUCTOR_CONFIGS_OVERRIDES = {
|
|
| 21 |
}
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
class ZeroGPUCompiledModel:
|
| 25 |
-
def __init__(self, archive_file: torch.types.FileLike, weights:
|
| 26 |
self.archive_file = archive_file
|
| 27 |
self.weights = weights
|
| 28 |
-
if cuda:
|
| 29 |
-
self.weights_to_cuda_()
|
| 30 |
self.compiled_model: ContextVar[AOTICompiledModel | None] = ContextVar('compiled_model', default=None)
|
| 31 |
-
def weights_to_cuda_(self):
|
| 32 |
-
for name in self.weights:
|
| 33 |
-
tensor, properties = self.weights.get_weight(name)
|
| 34 |
-
self.weights[name] = (tensor.to('cuda'), properties)
|
| 35 |
def __call__(self, *args, **kwargs):
|
| 36 |
if (compiled_model := self.compiled_model.get()) is None:
|
| 37 |
-
constants_map = {name: value[0] for name, value in self.weights.items()}
|
| 38 |
compiled_model = cast(AOTICompiledModel, torch._inductor.aoti_load_package(self.archive_file))
|
| 39 |
-
compiled_model.load_constants(constants_map, check_full_update=True, user_managed=True)
|
| 40 |
self.compiled_model.set(compiled_model)
|
| 41 |
return compiled_model(*args, **kwargs)
|
| 42 |
def __reduce__(self):
|
| 43 |
-
|
| 44 |
-
for name in self.weights:
|
| 45 |
-
tensor, properties = self.weights.get_weight(name)
|
| 46 |
-
tensor_ = torch.empty_like(tensor, device='cpu').pin_memory()
|
| 47 |
-
weight_dict[name] = (tensor_.copy_(tensor).detach().share_memory_(), properties)
|
| 48 |
-
return ZeroGPUCompiledModel, (self.archive_file, Weights(weight_dict), True)
|
| 49 |
|
| 50 |
|
| 51 |
def aoti_compile(
|
|
@@ -61,7 +62,8 @@ def aoti_compile(
|
|
| 61 |
files: list[str | Weights] = [file for file in artifacts if isinstance(file, str)]
|
| 62 |
package_aoti(archive_file, files)
|
| 63 |
weights, = (artifact for artifact in artifacts if isinstance(artifact, Weights))
|
| 64 |
-
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
@contextlib.contextmanager
|
|
@@ -94,3 +96,12 @@ def capture_component_call(
|
|
| 94 |
except CapturedCallException as e:
|
| 95 |
captured_call.args = e.args
|
| 96 |
captured_call.kwargs = e.kwargs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import torch
|
| 11 |
from torch._inductor.package.package import package_aoti
|
| 12 |
from torch.export.pt2_archive._package import AOTICompiledModel
|
|
|
|
| 13 |
from torch.export.pt2_archive._package_weights import Weights
|
| 14 |
|
| 15 |
|
|
|
|
| 20 |
}
|
| 21 |
|
| 22 |
|
| 23 |
+
class ZeroGPUWeights:
|
| 24 |
+
def __init__(self, constants_map: dict[str, torch.Tensor], to_cuda: bool = False):
|
| 25 |
+
if to_cuda:
|
| 26 |
+
self.constants_map = {name: tensor.to('cuda') for name, tensor in constants_map.items()}
|
| 27 |
+
else:
|
| 28 |
+
self.constants_map = constants_map
|
| 29 |
+
def __reduce__(self):
|
| 30 |
+
constants_map: dict[str, torch.Tensor] = {}
|
| 31 |
+
for name, tensor in self.constants_map.items():
|
| 32 |
+
tensor_ = torch.empty_like(tensor, device='cpu').pin_memory()
|
| 33 |
+
constants_map[name] = tensor_.copy_(tensor).detach().share_memory_()
|
| 34 |
+
return ZeroGPUWeights, (constants_map, True)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
class ZeroGPUCompiledModel:
|
| 38 |
+
def __init__(self, archive_file: torch.types.FileLike, weights: ZeroGPUWeights):
|
| 39 |
self.archive_file = archive_file
|
| 40 |
self.weights = weights
|
|
|
|
|
|
|
| 41 |
self.compiled_model: ContextVar[AOTICompiledModel | None] = ContextVar('compiled_model', default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def __call__(self, *args, **kwargs):
|
| 43 |
if (compiled_model := self.compiled_model.get()) is None:
|
|
|
|
| 44 |
compiled_model = cast(AOTICompiledModel, torch._inductor.aoti_load_package(self.archive_file))
|
| 45 |
+
compiled_model.load_constants(self.weights.constants_map, check_full_update=True, user_managed=True)
|
| 46 |
self.compiled_model.set(compiled_model)
|
| 47 |
return compiled_model(*args, **kwargs)
|
| 48 |
def __reduce__(self):
|
| 49 |
+
return ZeroGPUCompiledModel, (self.archive_file, self.weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def aoti_compile(
|
|
|
|
| 62 |
files: list[str | Weights] = [file for file in artifacts if isinstance(file, str)]
|
| 63 |
package_aoti(archive_file, files)
|
| 64 |
weights, = (artifact for artifact in artifacts if isinstance(artifact, Weights))
|
| 65 |
+
zerogpu_weights = ZeroGPUWeights({name: weights.get_weight(name)[0] for name in weights})
|
| 66 |
+
return ZeroGPUCompiledModel(archive_file, zerogpu_weights)
|
| 67 |
|
| 68 |
|
| 69 |
@contextlib.contextmanager
|
|
|
|
| 96 |
except CapturedCallException as e:
|
| 97 |
captured_call.args = e.args
|
| 98 |
captured_call.kwargs = e.kwargs
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def drain_module_parameters(module: torch.nn.Module):
|
| 102 |
+
state_dict_meta = {name: {'device': tensor.device, 'dtype': tensor.dtype} for name, tensor in module.state_dict().items()}
|
| 103 |
+
state_dict = {name: torch.nn.Parameter(torch.empty_like(tensor, device='cpu')) for name, tensor in module.state_dict().items()}
|
| 104 |
+
module.load_state_dict(state_dict, assign=True)
|
| 105 |
+
for name, param in state_dict.items():
|
| 106 |
+
meta = state_dict_meta[name]
|
| 107 |
+
param.data = torch.Tensor([]).to(**meta)
|
requirements.txt
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/linoytsaban/diffusers.git@wan22-loras
|
| 2 |
+
|
| 3 |
+
transformers==4.57.1
|
| 4 |
+
accelerate==1.11.0
|
| 5 |
+
safetensors==0.6.2
|
| 6 |
+
sentencepiece==0.2.1
|
| 7 |
+
peft==0.17.1
|
| 8 |
+
ftfy==6.3.1
|
| 9 |
+
imageio-ffmpeg==0.6.0
|
| 10 |
+
opencv-python==4.12.0.88
|
| 11 |
+
torchao==0.11.0
|