Spaces:
Runtime error
Runtime error
Upload 8 files
Browse files- README.md +6 -4
- app.py +218 -612
- optimization.py +60 -156
- optimization_utils.py +96 -166
- requirements.txt +5 -12
README.md
CHANGED
|
@@ -1,12 +1,14 @@
|
|
| 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 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: FLUX.1 Kontext
|
| 3 |
+
emoji: ⚡
|
| 4 |
+
colorFrom: green
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.29.1
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: 'Kontext image editing on FLUX[dev] '
|
| 12 |
---
|
| 13 |
|
| 14 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 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 |
-
#
|
| 6 |
try:
|
| 7 |
import spaces
|
| 8 |
except:
|
|
@@ -12,662 +12,268 @@ except:
|
|
| 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 imageio_ffmpeg
|
| 22 |
-
import tempfile
|
| 23 |
-
import shutil
|
| 24 |
-
import subprocess
|
| 25 |
-
import time
|
| 26 |
-
from datetime import datetime
|
| 27 |
import numpy as np
|
| 28 |
-
|
| 29 |
import random
|
| 30 |
-
import
|
| 31 |
-
import traceback
|
| 32 |
-
import gc
|
| 33 |
-
from gradio_client import Client, handle_file # Import for API call
|
| 34 |
-
import zipfile
|
| 35 |
-
|
| 36 |
-
# Import optimization and access compiled artifacts
|
| 37 |
-
import optimization
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
|
| 45 |
-
|
| 46 |
-
MAX_DIMENSION = 832
|
| 47 |
-
MIN_DIMENSION = 480
|
| 48 |
-
DIMENSION_MULTIPLE = 16
|
| 49 |
-
SQUARE_SIZE = 480
|
| 50 |
|
| 51 |
MAX_SEED = np.iinfo(np.int32).max
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
MAX_FRAMES_MODEL = 81
|
| 56 |
-
|
| 57 |
-
MIN_DURATION = round(MIN_FRAMES_MODEL/FIXED_FPS, 1)
|
| 58 |
-
MAX_DURATION = round(MAX_FRAMES_MODEL/FIXED_FPS, 1)
|
| 59 |
|
| 60 |
input_image_debug_value = [None]
|
| 61 |
-
end_image_debug_value = [None]
|
| 62 |
prompt_debug_value = [None]
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
factor_debug_value = [None]
|
| 66 |
-
allocation_time_debug_value = [None]
|
| 67 |
-
|
| 68 |
-
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, "
|
| 69 |
-
|
| 70 |
-
transformer = WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
| 71 |
-
subfolder='transformer',
|
| 72 |
-
torch_dtype=torch.bfloat16,
|
| 73 |
-
device_map='cuda',
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
transformer_2 = WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
| 77 |
-
subfolder='transformer_2',
|
| 78 |
-
torch_dtype=torch.bfloat16,
|
| 79 |
-
device_map='cuda',
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
pipe = WanImageToVideoPipeline.from_pretrained(
|
| 83 |
-
MODEL_ID,
|
| 84 |
-
transformer = transformer,
|
| 85 |
-
transformer_2 = transformer_2,
|
| 86 |
-
torch_dtype=torch.bfloat16,
|
| 87 |
-
)
|
| 88 |
-
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, shift=8.0)
|
| 89 |
-
pipe.to('cuda')
|
| 90 |
-
|
| 91 |
-
for i in range(3):
|
| 92 |
-
gc.collect()
|
| 93 |
-
torch.cuda.synchronize()
|
| 94 |
-
torch.cuda.empty_cache()
|
| 95 |
-
|
| 96 |
-
optimize_pipeline_(pipe,
|
| 97 |
-
image=Image.new('RGB', (MAX_DIMENSION, MIN_DIMENSION)),
|
| 98 |
-
prompt='prompt',
|
| 99 |
-
height=MIN_DIMENSION,
|
| 100 |
-
width=MAX_DIMENSION,
|
| 101 |
-
num_frames=MAX_FRAMES_MODEL,
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
def _escape_html(s: str) -> str:
|
| 105 |
-
return (s.replace("&", "&").replace("<", "<").replace(">", ">"))
|
| 106 |
-
|
| 107 |
-
def _error_to_html(err: BaseException) -> str:
|
| 108 |
-
tb = traceback.format_exc()
|
| 109 |
-
return (
|
| 110 |
-
"<div style='padding:12px;border:1px solid #ff4d4f;background:#fff1f0;color:#a8071a;border-radius:8px;'>"
|
| 111 |
-
"<b>Generation failed</b><br/>"
|
| 112 |
-
f"<b>{_escape_html(type(err).__name__)}</b>: {_escape_html(str(err))}"
|
| 113 |
-
"<details style='margin-top:8px;'>"
|
| 114 |
-
"<summary>Show traceback</summary>"
|
| 115 |
-
f"<pre style='white-space:pre-wrap;margin-top:8px;'>{_escape_html(tb)}</pre>"
|
| 116 |
-
"</details>"
|
| 117 |
-
"</div>"
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
# 20250508 pftq: for saving prompt to mp4 metadata comments
|
| 121 |
-
def set_mp4_comments_imageio_ffmpeg(input_file, comments):
|
| 122 |
-
try:
|
| 123 |
-
# Get the path to the bundled FFmpeg binary from imageio-ffmpeg
|
| 124 |
-
ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
|
| 125 |
-
|
| 126 |
-
# Check if input file exists
|
| 127 |
-
if not os.path.exists(input_file):
|
| 128 |
-
#print(f"Error: Input file {input_file} does not exist")
|
| 129 |
-
return False
|
| 130 |
-
|
| 131 |
-
# Create a temporary file path
|
| 132 |
-
temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
| 133 |
-
|
| 134 |
-
# FFmpeg command using the bundled binary
|
| 135 |
-
command = [
|
| 136 |
-
ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
|
| 137 |
-
'-i', input_file, # input file
|
| 138 |
-
'-metadata', f'comment={comments}', # set comment metadata
|
| 139 |
-
'-c:v', 'copy', # copy video stream without re-encoding
|
| 140 |
-
'-c:a', 'copy', # copy audio stream without re-encoding
|
| 141 |
-
'-y', # overwrite output file if it exists
|
| 142 |
-
temp_file # temporary output file
|
| 143 |
-
]
|
| 144 |
-
|
| 145 |
-
# Run the FFmpeg command
|
| 146 |
-
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 147 |
-
|
| 148 |
-
if result.returncode == 0:
|
| 149 |
-
# Replace the original file with the modified one
|
| 150 |
-
shutil.move(temp_file, input_file)
|
| 151 |
-
#print(f"Successfully added comments to {input_file}")
|
| 152 |
-
return True
|
| 153 |
-
else:
|
| 154 |
-
# Clean up temp file if FFmpeg fails
|
| 155 |
-
if os.path.exists(temp_file):
|
| 156 |
-
os.remove(temp_file)
|
| 157 |
-
#print(f"Error: FFmpeg failed with message:\n{result.stderr}")
|
| 158 |
-
return False
|
| 159 |
-
|
| 160 |
-
except Exception as e:
|
| 161 |
-
# Clean up temp file in case of other errors
|
| 162 |
-
if 'temp_file' in locals() and os.path.exists(temp_file):
|
| 163 |
-
os.remove(temp_file)
|
| 164 |
-
print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
|
| 165 |
-
return False
|
| 166 |
-
|
| 167 |
-
# --- 2. Image Processing and Application Logic ---
|
| 168 |
-
def generate_end_frame(start_img, gen_prompt, progress=gr.Progress(track_tqdm=True)):
|
| 169 |
-
"""Calls an external Gradio API to generate an image."""
|
| 170 |
-
if start_img is None:
|
| 171 |
-
raise gr.Error("Please provide a Start Frame first.")
|
| 172 |
-
|
| 173 |
-
hf_token = os.getenv("HF_TOKEN")
|
| 174 |
-
if not hf_token:
|
| 175 |
-
raise gr.Error("HF_TOKEN not found in environment variables. Please set it in your Space secrets.")
|
| 176 |
-
|
| 177 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
|
| 178 |
-
start_img.save(tmpfile.name)
|
| 179 |
-
tmp_path = tmpfile.name
|
| 180 |
-
|
| 181 |
-
progress(0.1, desc="Connecting to image generation API...")
|
| 182 |
-
client = Client("multimodalart/nano-banana-private")
|
| 183 |
-
|
| 184 |
-
progress(0.5, desc=f"Generating with prompt: '{gen_prompt}'...")
|
| 185 |
-
try:
|
| 186 |
-
result = client.predict(
|
| 187 |
-
prompt=gen_prompt,
|
| 188 |
-
images=[
|
| 189 |
-
{"image": handle_file(tmp_path)}
|
| 190 |
-
],
|
| 191 |
-
manual_token=hf_token,
|
| 192 |
-
api_name="/unified_image_generator"
|
| 193 |
-
)
|
| 194 |
-
finally:
|
| 195 |
-
os.remove(tmp_path)
|
| 196 |
-
|
| 197 |
-
progress(1.0, desc="Done!")
|
| 198 |
-
print(result)
|
| 199 |
-
return result
|
| 200 |
-
|
| 201 |
-
def switch_to_upload_tab():
|
| 202 |
-
"""Returns a gr.Tabs update to switch to the first tab."""
|
| 203 |
-
return gr.Tabs(selected="upload_tab")
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
def process_image_for_video(image: Image.Image, resolution: int) -> Image.Image:
|
| 207 |
"""
|
| 208 |
-
|
|
|
|
| 209 |
"""
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
scale = ((MIN_DIMENSION**2) / (width * height))**(.5)
|
| 221 |
-
new_width = width * scale
|
| 222 |
-
new_height = height * scale
|
| 223 |
-
final_width = int(math.ceil(new_width / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 224 |
-
final_height = int(math.ceil(new_height / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 225 |
-
|
| 226 |
-
else:
|
| 227 |
-
final_width = int(round(width / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 228 |
-
final_height = int(round(height / DIMENSION_MULTIPLE) * DIMENSION_MULTIPLE)
|
| 229 |
-
|
| 230 |
-
return image.resize((final_width, final_height), Image.Resampling.LANCZOS)
|
| 231 |
-
|
| 232 |
-
def resize_and_crop_to_match(target_image, reference_image):
|
| 233 |
-
"""Resizes the target image to match the reference image's dimensions."""
|
| 234 |
-
ref_width, ref_height = reference_image.size
|
| 235 |
-
return target_image.resize((ref_width, ref_height), Image.Resampling.LANCZOS)
|
| 236 |
-
|
| 237 |
-
def crop_to_match(target_image, reference_image):
|
| 238 |
-
"""Resizes and center-crops the target image to match the reference image's dimensions."""
|
| 239 |
-
ref_width, ref_height = reference_image.size
|
| 240 |
-
target_width, target_height = target_image.size
|
| 241 |
-
scale = max(ref_width / target_width, ref_height / target_height)
|
| 242 |
-
new_width, new_height = int(target_width * scale), int(target_height * scale)
|
| 243 |
-
resized = target_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 244 |
-
left, top = (new_width - ref_width) // 2, (new_height - ref_height) // 2
|
| 245 |
-
return resized.crop((left, top, left + ref_width, top + ref_height))
|
| 246 |
-
|
| 247 |
-
def init_view():
|
| 248 |
-
return gr.update(interactive = True)
|
| 249 |
-
|
| 250 |
-
def output_video_change(output_video):
|
| 251 |
-
print('Log output: ' + str(output_video))
|
| 252 |
-
return [gr.update(visible = True)] * 2
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
prompt,
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
steps=
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
seed=42,
|
| 265 |
-
randomize_seed=True,
|
| 266 |
progress=gr.Progress(track_tqdm=True)
|
| 267 |
):
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
factor = 1
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
prompt = prompt_debug_value[0]
|
| 276 |
-
duration_seconds = total_second_length_debug_value[0]
|
| 277 |
-
resolution = resolution_debug_value[0]
|
| 278 |
-
factor = factor_debug_value[0]
|
| 279 |
-
allocation_time = allocation_time_debug_value[0]
|
| 280 |
-
|
| 281 |
-
if start_image_pil is None or end_image_pil is None:
|
| 282 |
-
raise gr.Error("Please upload both a start and an end image.")
|
| 283 |
-
|
| 284 |
-
# Step 1: Process the start image to get our target dimensions based on the new rules.
|
| 285 |
-
processed_start_image = process_image_for_video(start_image_pil, resolution)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
progress(0.2, desc=f"Generating {num_frames} frames at {target_width}x{target_height} (seed: {current_seed})...")
|
| 297 |
-
|
| 298 |
-
progress(0.1, desc="Preprocessing images...")
|
| 299 |
-
print("Generate a video with the prompt: " + prompt)
|
| 300 |
-
output_frames_list = None
|
| 301 |
-
caught_error = None
|
| 302 |
-
while factor >= 1 and int(allocation_time) > 0:
|
| 303 |
-
try:
|
| 304 |
-
output_frames_list = generate_video_on_gpu(
|
| 305 |
-
start_image_pil,
|
| 306 |
-
end_image_pil,
|
| 307 |
-
prompt,
|
| 308 |
-
negative_prompt,
|
| 309 |
-
int(steps),
|
| 310 |
-
float(guidance_scale),
|
| 311 |
-
float(guidance_scale_2),
|
| 312 |
-
progress,
|
| 313 |
-
allocation_time,
|
| 314 |
-
target_height,
|
| 315 |
-
target_width,
|
| 316 |
-
current_seed,
|
| 317 |
-
(int(((num_frames * factor) - 1) / 4) * 4) + 1,
|
| 318 |
-
processed_start_image,
|
| 319 |
-
processed_end_image
|
| 320 |
-
)
|
| 321 |
-
factor = 0
|
| 322 |
-
caught_error = None
|
| 323 |
-
except BaseException as err:
|
| 324 |
-
print("An exception occurred: " + str(err))
|
| 325 |
-
caught_error = err
|
| 326 |
-
try:
|
| 327 |
-
print('e.message: ' + err.message) # No GPU is currently available for you after 60s
|
| 328 |
-
except Exception as e2:
|
| 329 |
-
print('Failure')
|
| 330 |
-
if not str(err).startswith("No GPU is currently available for you after 60s"):
|
| 331 |
-
factor -= .003
|
| 332 |
-
allocation_time = int(allocation_time) - 1
|
| 333 |
-
except:
|
| 334 |
-
print("An error occurred")
|
| 335 |
-
caught_error = None
|
| 336 |
-
if not str(e).startswith("No GPU is currently available for you after 60s"):
|
| 337 |
-
factor -= .003
|
| 338 |
-
allocation_time = int(allocation_time) - 1
|
| 339 |
-
|
| 340 |
-
if caught_error is not None:
|
| 341 |
-
return [gr.skip(), gr.skip(), gr.skip(), gr.update(value=_error_to_html(caught_error), visible=True), gr.skip()]
|
| 342 |
-
|
| 343 |
-
input_image_debug_value[0] = end_image_debug_value[0] = prompt_debug_value[0] = total_second_length_debug_value[0] = allocation_time_debug_value[0] = factor_debug_value[0] = None
|
| 344 |
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
"The video has " + str(int(num_frames * factor)) + " frames. " + \
|
| 366 |
-
"The video resolution is " + str(target_width) + \
|
| 367 |
-
" pixels large and " + str(target_height) + \
|
| 368 |
-
" pixels high, so a resolution of " + f'{target_width * target_height:,}' + " pixels." + \
|
| 369 |
-
" Your prompt is saved into the metadata of the video."
|
| 370 |
-
return [video_path, gr.update(value = video_path, visible = True, interactive = True), current_seed, gr.update(value = information, visible = True), gr.update(interactive = False)]
|
| 371 |
-
|
| 372 |
-
def get_duration(
|
| 373 |
-
start_image_pil,
|
| 374 |
-
end_image_pil,
|
| 375 |
-
prompt,
|
| 376 |
-
negative_prompt,
|
| 377 |
-
steps,
|
| 378 |
-
guidance_scale,
|
| 379 |
-
guidance_scale_2,
|
| 380 |
-
progress,
|
| 381 |
-
allocation_time,
|
| 382 |
-
target_height,
|
| 383 |
-
target_width,
|
| 384 |
-
current_seed,
|
| 385 |
-
num_frames,
|
| 386 |
-
processed_start_image,
|
| 387 |
-
processed_end_image
|
| 388 |
-
):
|
| 389 |
-
return allocation_time
|
| 390 |
-
|
| 391 |
-
@torch.no_grad()
|
| 392 |
-
@spaces.GPU(duration=get_duration)
|
| 393 |
-
def generate_video_on_gpu(
|
| 394 |
-
start_image_pil,
|
| 395 |
-
end_image_pil,
|
| 396 |
-
prompt,
|
| 397 |
-
negative_prompt,
|
| 398 |
-
steps,
|
| 399 |
-
guidance_scale,
|
| 400 |
-
guidance_scale_2,
|
| 401 |
-
progress,
|
| 402 |
-
allocation_time,
|
| 403 |
-
target_height,
|
| 404 |
-
target_width,
|
| 405 |
-
current_seed,
|
| 406 |
-
num_frames,
|
| 407 |
-
processed_start_image,
|
| 408 |
-
processed_end_image
|
| 409 |
-
):
|
| 410 |
-
"""
|
| 411 |
-
Generates a video by interpolating between a start and end image, guided by a text prompt,
|
| 412 |
-
using the diffusers Wan2.2 pipeline.
|
| 413 |
-
"""
|
| 414 |
-
|
| 415 |
-
output_frames_list = pipe(
|
| 416 |
-
image=processed_start_image,
|
| 417 |
-
last_image=processed_end_image,
|
| 418 |
-
prompt=prompt,
|
| 419 |
-
negative_prompt=negative_prompt,
|
| 420 |
-
height=target_height,
|
| 421 |
-
width=target_width,
|
| 422 |
-
num_frames=num_frames,
|
| 423 |
-
guidance_scale=guidance_scale,
|
| 424 |
-
guidance_scale_2=guidance_scale_2,
|
| 425 |
-
num_inference_steps=steps,
|
| 426 |
-
generator=torch.Generator(device="cuda").manual_seed(current_seed),
|
| 427 |
-
).frames[0]
|
| 428 |
-
|
| 429 |
-
return output_frames_list
|
| 430 |
-
|
| 431 |
-
def export_compiled_transformers_to_zip() -> str:
|
| 432 |
-
"""
|
| 433 |
-
Bundle compiled_transformer_1 and compiled_transformer_2 into a zip file and return the file path.
|
| 434 |
-
"""
|
| 435 |
-
ct1 = getattr(optimization, "COMPILED_TRANSFORMER_1", None)
|
| 436 |
-
ct2 = getattr(optimization, "COMPILED_TRANSFORMER_2", None)
|
| 437 |
-
|
| 438 |
-
if ct1 is None or ct2 is None:
|
| 439 |
-
raise gr.Error("Compiled transformers are not available yet (compilation may have failed).")
|
| 440 |
-
|
| 441 |
-
payload_1 = ct1.to_serializable_dict()
|
| 442 |
-
payload_2 = ct2.to_serializable_dict()
|
| 443 |
-
|
| 444 |
-
tmp_zip = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
|
| 445 |
-
tmp_zip.close()
|
| 446 |
-
|
| 447 |
-
with zipfile.ZipFile(tmp_zip.name, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
| 448 |
-
# store with torch.save so users can load easily with torch.load()
|
| 449 |
-
buf1 = tempfile.NamedTemporaryFile(suffix=".pt", delete=False)
|
| 450 |
-
buf1.close()
|
| 451 |
-
torch.save(payload_1, buf1.name)
|
| 452 |
-
|
| 453 |
-
buf2 = tempfile.NamedTemporaryFile(suffix=".pt", delete=False)
|
| 454 |
-
buf2.close()
|
| 455 |
-
torch.save(payload_2, buf2.name)
|
| 456 |
-
|
| 457 |
-
zf.write(buf1.name, arcname="compiled_transformer_1.pt")
|
| 458 |
-
zf.write(buf2.name, arcname="compiled_transformer_2.pt")
|
| 459 |
-
|
| 460 |
-
# cleanup intermediate .pt
|
| 461 |
try:
|
| 462 |
-
|
| 463 |
-
|
|
|
|
|
|
|
|
|
|
| 464 |
except:
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
return tmp_zip.name
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
# --- 3. Gradio User Interface ---
|
| 471 |
-
|
| 472 |
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
if (document.getElementById('dummy_button_id') && !document.getElementById('dummy_button_id').disabled) {
|
| 478 |
-
var confirmationMessage = 'A process is still running. '
|
| 479 |
-
+ 'If you leave before saving, your changes will be lost.';
|
| 480 |
-
|
| 481 |
-
(e || window.event).returnValue = confirmationMessage;
|
| 482 |
-
}
|
| 483 |
-
return confirmationMessage;
|
| 484 |
-
});
|
| 485 |
-
return 'Animation created';
|
| 486 |
}
|
| 487 |
"""
|
| 488 |
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
gr.
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
with gr.
|
| 496 |
-
with gr.
|
|
|
|
| 497 |
with gr.Row():
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
prompt = gr.Textbox(label="Prompt", info="Describe the transition between the two images", placeholder="The creature starts to move")
|
| 507 |
-
|
| 508 |
with gr.Accordion("Advanced Settings", open=False):
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
end_image,
|
| 559 |
-
prompt,
|
| 560 |
-
negative_prompt_input,
|
| 561 |
-
resolution,
|
| 562 |
-
duration_seconds_input,
|
| 563 |
-
steps_slider,
|
| 564 |
-
guidance_scale_input,
|
| 565 |
-
guidance_scale_2_input,
|
| 566 |
-
seed_input,
|
| 567 |
-
randomize_seed_checkbox
|
| 568 |
-
]
|
| 569 |
-
ui_outputs = [output_video, download_button, seed_input, video_information, dummy_button]
|
| 570 |
-
|
| 571 |
-
generate_button.click(fn = init_view, inputs = [], outputs = [dummy_button], queue = False, show_progress = False).success(
|
| 572 |
-
fn = generate_video,
|
| 573 |
-
inputs = ui_inputs,
|
| 574 |
-
outputs = ui_outputs
|
| 575 |
-
)
|
| 576 |
-
|
| 577 |
-
generate_5seconds.click(
|
| 578 |
-
fn=switch_to_upload_tab,
|
| 579 |
-
inputs=None,
|
| 580 |
-
outputs=[tabs]
|
| 581 |
-
).then(
|
| 582 |
-
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"),
|
| 583 |
-
inputs=[start_image],
|
| 584 |
-
outputs=[end_image]
|
| 585 |
-
).success(
|
| 586 |
-
fn=generate_video,
|
| 587 |
-
inputs=ui_inputs,
|
| 588 |
-
outputs=ui_outputs
|
| 589 |
-
)
|
| 590 |
-
|
| 591 |
-
output_video.change(
|
| 592 |
-
fn=output_video_change,
|
| 593 |
-
inputs=[output_video],
|
| 594 |
-
outputs=[download_button, video_information],
|
| 595 |
-
js="document.getElementById('download_btn').click()"
|
| 596 |
-
)
|
| 597 |
|
| 598 |
with gr.Row(visible=False):
|
|
|
|
| 599 |
gr.Examples(
|
| 600 |
-
examples=[
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
|
|
|
|
|
|
| 604 |
run_on_click=True,
|
| 605 |
cache_examples=True,
|
| 606 |
-
cache_mode='lazy'
|
| 607 |
)
|
| 608 |
prompt_debug=gr.Textbox(label="Prompt Debug")
|
| 609 |
input_image_debug=gr.Image(type="pil", label="Image Debug")
|
| 610 |
-
|
| 611 |
-
total_second_length_debug=gr.Slider(label="Duration Debug", minimum=1, maximum=120, value=5, step=0.1)
|
| 612 |
-
resolution_debug = gr.Dropdown([
|
| 613 |
-
["400,000 px", 400000],
|
| 614 |
-
["465,920 px", 465920],
|
| 615 |
-
["495,616 px", 495616],
|
| 616 |
-
["500,000 px", 500000],
|
| 617 |
-
["600,000 px", 600000],
|
| 618 |
-
["700,000 px", 700000],
|
| 619 |
-
["800,000 px", 800000],
|
| 620 |
-
["900,000 px", 900000],
|
| 621 |
-
["1,000,000 px", 1000000],
|
| 622 |
-
["1,100,000 px", 1100000],
|
| 623 |
-
["1,200,000 px", 1200000],
|
| 624 |
-
["1,300,000 px", 1300000],
|
| 625 |
-
["1,400,000 px", 1400000],
|
| 626 |
-
["1,500,000 px", 1500000]
|
| 627 |
-
], value=500000, label="Resolution Debug")
|
| 628 |
-
factor_debug=gr.Slider(label="Factor Debug", minimum=1, maximum=100, value=3.2, step=0.1)
|
| 629 |
-
allocation_time_debug=gr.Slider(label="Allocation Debug", minimum=1, maximum=60 * 20, value=720, step=1)
|
| 630 |
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
|
|
|
|
|
|
| 642 |
prompt_debug_value[0] = prompt_debug_data
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
factor_debug_value[0] = factor_debug_data
|
| 646 |
-
allocation_time_debug_value[0] = allocation_time_debug_data
|
| 647 |
return []
|
| 648 |
|
| 649 |
-
inputs_debug=[input_image_debug,
|
| 650 |
|
| 651 |
input_image_debug.upload(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 652 |
-
end_image_debug.upload(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 653 |
prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
]
|
| 666 |
-
inputs = [start_image, end_image, prompt],
|
| 667 |
-
outputs = ui_outputs,
|
| 668 |
-
fn = generate_video,
|
| 669 |
-
cache_examples = False,
|
| 670 |
)
|
| 671 |
|
| 672 |
-
|
| 673 |
-
app.launch(mcp_server=True, share=True)
|
|
|
|
|
|
|
| 1 |
# PyTorch 2.8 (temporary hack)
|
| 2 |
+
import os
|
| 3 |
os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
|
| 4 |
|
| 5 |
+
# Actual demo code
|
| 6 |
try:
|
| 7 |
import spaces
|
| 8 |
except:
|
|
|
|
| 12 |
return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
|
| 13 |
return decorator
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
import random
|
| 19 |
+
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import tempfile
|
| 23 |
+
import shutil
|
| 24 |
+
from pathlib import Path
|
| 25 |
|
| 26 |
+
from diffusers import FluxKontextPipeline
|
| 27 |
+
from diffusers.utils import load_image
|
| 28 |
|
| 29 |
+
from optimization import optimize_pipeline_
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
MAX_SEED = np.iinfo(np.int32).max
|
| 32 |
|
| 33 |
+
pipe = FluxKontextPipeline.from_pretrained("yuvraj108c/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
|
| 34 |
+
optimize_pipeline_(pipe, image=Image.new("RGB", (512, 512)), prompt='prompt')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
input_image_debug_value = [None]
|
|
|
|
| 37 |
prompt_debug_value = [None]
|
| 38 |
+
number_debug_value = [None]
|
| 39 |
+
def save_on_path(img: Image, filename: str, format_: str = None) -> Path:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"""
|
| 41 |
+
Save `img` in a unique temporary folder under the given `filename`
|
| 42 |
+
and return its absolute path.
|
| 43 |
"""
|
| 44 |
+
# 1) unique temporary folder
|
| 45 |
+
tmp_dir = Path(tempfile.mkdtemp(prefix="pil_tmp_"))
|
| 46 |
+
|
| 47 |
+
# 2) full path of the future file
|
| 48 |
+
file_path = tmp_dir / filename
|
| 49 |
+
|
| 50 |
+
# 3) save
|
| 51 |
+
img.save(file_path, format=format_ or img.format)
|
| 52 |
+
|
| 53 |
+
return file_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
@spaces.GPU(duration=40)
|
| 56 |
+
def infer(
|
| 57 |
+
input_image,
|
| 58 |
prompt,
|
| 59 |
+
seed = 42,
|
| 60 |
+
randomize_seed = False,
|
| 61 |
+
guidance_scale = 2.5,
|
| 62 |
+
steps = 28,
|
| 63 |
+
width = -1,
|
| 64 |
+
height = -1,
|
|
|
|
|
|
|
| 65 |
progress=gr.Progress(track_tqdm=True)
|
| 66 |
):
|
| 67 |
+
"""
|
| 68 |
+
Perform image editing using the FLUX.1 Kontext pipeline.
|
|
|
|
| 69 |
|
| 70 |
+
This function takes an input image and a text prompt to generate a modified version
|
| 71 |
+
of the image based on the provided instructions. It uses the FLUX.1 Kontext model
|
| 72 |
+
for contextual image editing tasks.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
Args:
|
| 75 |
+
input_image (PIL.Image.Image): The input image to be edited. Will be converted
|
| 76 |
+
to RGB format if not already in that format.
|
| 77 |
+
prompt (str): Text description of the desired edit to apply to the image.
|
| 78 |
+
Examples: "Remove glasses", "Add a hat", "Change background to beach".
|
| 79 |
+
seed (int, optional): Random seed for reproducible generation. Defaults to 42.
|
| 80 |
+
Must be between 0 and MAX_SEED (2^31 - 1).
|
| 81 |
+
randomize_seed (bool, optional): If True, generates a random seed instead of
|
| 82 |
+
using the provided seed value. Defaults to False.
|
| 83 |
+
guidance_scale (float, optional): Controls how closely the model follows the
|
| 84 |
+
prompt. Higher values mean stronger adherence to the prompt but may reduce
|
| 85 |
+
image quality. Range: 1.0-10.0. Defaults to 2.5.
|
| 86 |
+
steps (int, optional): Controls how many steps to run the diffusion model for.
|
| 87 |
+
Range: 1-30. Defaults to 28.
|
| 88 |
+
progress (gr.Progress, optional): Gradio progress tracker for monitoring
|
| 89 |
+
generation progress. Defaults to gr.Progress(track_tqdm=True).
|
| 90 |
|
| 91 |
+
Returns:
|
| 92 |
+
tuple: A 3-tuple containing:
|
| 93 |
+
- PIL.Image.Image: The generated/edited image
|
| 94 |
+
- int: The seed value used for generation (useful when randomize_seed=True)
|
| 95 |
+
- gr.update: Gradio update object to make the reuse button visible
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
Example:
|
| 98 |
+
>>> edited_image, used_seed, button_update = infer(
|
| 99 |
+
... input_image=my_image,
|
| 100 |
+
... prompt="Add sunglasses",
|
| 101 |
+
... seed=123,
|
| 102 |
+
... randomize_seed=False,
|
| 103 |
+
... guidance_scale=2.5
|
| 104 |
+
... )
|
| 105 |
+
"""
|
| 106 |
+
if randomize_seed:
|
| 107 |
+
seed = random.randint(0, MAX_SEED)
|
| 108 |
|
| 109 |
+
if input_image:
|
| 110 |
+
input_image = input_image.convert("RGB")
|
| 111 |
+
image = pipe(
|
| 112 |
+
image=input_image,
|
| 113 |
+
prompt=prompt,
|
| 114 |
+
guidance_scale=guidance_scale,
|
| 115 |
+
width = input_image.size[0] if width == -1 else width,
|
| 116 |
+
height = input_image.size[1] if height == -1 else height,
|
| 117 |
+
num_inference_steps=steps,
|
| 118 |
+
generator=torch.Generator().manual_seed(seed),
|
| 119 |
+
).images[0]
|
| 120 |
+
else:
|
| 121 |
+
image = pipe(
|
| 122 |
+
prompt=prompt,
|
| 123 |
+
guidance_scale=guidance_scale,
|
| 124 |
+
num_inference_steps=steps,
|
| 125 |
+
generator=torch.Generator().manual_seed(seed),
|
| 126 |
+
).images[0]
|
| 127 |
|
| 128 |
+
image_filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f") + '.webp'
|
| 129 |
+
path = save_on_path(image, image_filename, format_="WEBP")
|
| 130 |
+
return path, gr.update(value=path, visible=True), seed, gr.update(visible=True)
|
| 131 |
+
|
| 132 |
+
def infer_example(input_image, prompt):
|
| 133 |
+
number=1
|
| 134 |
+
if input_image_debug_value[0] is not None or prompt_debug_value[0] is not None or number_debug_value[0] is not None:
|
| 135 |
+
input_image=input_image_debug_value[0]
|
| 136 |
+
prompt=prompt_debug_value[0]
|
| 137 |
+
number=number_debug_value[0]
|
| 138 |
+
#input_image_debug_value[0]=prompt_debug_value[0]=prompt_debug_value[0]=None
|
| 139 |
+
gallery = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
try:
|
| 141 |
+
for i in range(number):
|
| 142 |
+
print("Generating #" + str(i + 1) + " image...")
|
| 143 |
+
seed = random.randint(0, MAX_SEED)
|
| 144 |
+
image, download_button, seed, _ = infer(input_image, prompt, seed, True)
|
| 145 |
+
gallery.append(image)
|
| 146 |
except:
|
| 147 |
+
print("Error")
|
| 148 |
+
return gallery, seed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
css="""
|
| 151 |
+
#col-container {
|
| 152 |
+
margin: 0 auto;
|
| 153 |
+
max-width: 960px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
}
|
| 155 |
"""
|
| 156 |
|
| 157 |
+
with gr.Blocks(css=css) as demo:
|
| 158 |
+
|
| 159 |
+
with gr.Column(elem_id="col-container"):
|
| 160 |
+
gr.Markdown(f"""# FLUX.1 Kontext [dev]
|
| 161 |
+
Image editing and manipulation model guidance-distilled from FLUX.1 Kontext [pro], [[blog]](https://bfl.ai/announcements/flux-1-kontext-dev) [[model]](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev)
|
| 162 |
+
""")
|
| 163 |
+
with gr.Row():
|
| 164 |
+
with gr.Column():
|
| 165 |
+
input_image = gr.Image(label="Upload the image for editing", type="pil")
|
| 166 |
with gr.Row():
|
| 167 |
+
prompt = gr.Text(
|
| 168 |
+
label="Prompt",
|
| 169 |
+
show_label=False,
|
| 170 |
+
max_lines=1,
|
| 171 |
+
placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",
|
| 172 |
+
container=False,
|
| 173 |
+
)
|
| 174 |
+
run_button = gr.Button(value="🚀 Edit", variant = "primary", scale=0)
|
|
|
|
|
|
|
| 175 |
with gr.Accordion("Advanced Settings", open=False):
|
| 176 |
+
|
| 177 |
+
seed = gr.Slider(
|
| 178 |
+
label="Seed",
|
| 179 |
+
minimum=0,
|
| 180 |
+
maximum=MAX_SEED,
|
| 181 |
+
step=1,
|
| 182 |
+
value=0,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 186 |
+
|
| 187 |
+
guidance_scale = gr.Slider(
|
| 188 |
+
label="Guidance Scale",
|
| 189 |
+
minimum=1,
|
| 190 |
+
maximum=10,
|
| 191 |
+
step=0.1,
|
| 192 |
+
value=2.5,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
steps = gr.Slider(
|
| 196 |
+
label="Steps",
|
| 197 |
+
minimum=1,
|
| 198 |
+
maximum=30,
|
| 199 |
+
value=30,
|
| 200 |
+
step=1
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
width = gr.Slider(
|
| 204 |
+
label="Output width",
|
| 205 |
+
info="-1 = original width",
|
| 206 |
+
minimum=-1,
|
| 207 |
+
maximum=1024,
|
| 208 |
+
value=-1,
|
| 209 |
+
step=1
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
height = gr.Slider(
|
| 213 |
+
label="Output height",
|
| 214 |
+
info="-1 = original height",
|
| 215 |
+
minimum=-1,
|
| 216 |
+
maximum=1024,
|
| 217 |
+
value=-1,
|
| 218 |
+
step=1
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
with gr.Column():
|
| 222 |
+
result = gr.Image(label="Result", show_label=False, interactive=False)
|
| 223 |
+
download_button = gr.DownloadButton(elem_id="download_btn", visible=False)
|
| 224 |
+
reuse_button = gr.Button("Reuse this image", visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
with gr.Row(visible=False):
|
| 227 |
+
result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
|
| 228 |
gr.Examples(
|
| 229 |
+
examples=[
|
| 230 |
+
["monster.png", "Make this monster ride a skateboard on the beach"]
|
| 231 |
+
],
|
| 232 |
+
inputs=[input_image, prompt],
|
| 233 |
+
outputs=[result_gallery, seed],
|
| 234 |
+
fn=infer_example,
|
| 235 |
run_on_click=True,
|
| 236 |
cache_examples=True,
|
| 237 |
+
cache_mode='lazy'
|
| 238 |
)
|
| 239 |
prompt_debug=gr.Textbox(label="Prompt Debug")
|
| 240 |
input_image_debug=gr.Image(type="pil", label="Image Debug")
|
| 241 |
+
number_debug=gr.Slider(label="Number Debug", minimum=1, maximum=50, step=1, value=50)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
+
gr.Examples(
|
| 244 |
+
label = "Examples from demo",
|
| 245 |
+
examples=[
|
| 246 |
+
["flowers.png", "turn the flowers into sunflowers"],
|
| 247 |
+
["monster.png", "make this monster ride a skateboard on the beach"],
|
| 248 |
+
["cat.png", "make this cat happy"]
|
| 249 |
+
],
|
| 250 |
+
inputs=[input_image, prompt],
|
| 251 |
+
outputs=[result, download_button, seed],
|
| 252 |
+
fn=infer
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def handle_field_debug_change(input_image_debug_data, prompt_debug_data, number_debug_data):
|
| 256 |
prompt_debug_value[0] = prompt_debug_data
|
| 257 |
+
input_image_debug_value[0] = input_image_debug_data
|
| 258 |
+
number_debug_value[0] = number_debug_data
|
|
|
|
|
|
|
| 259 |
return []
|
| 260 |
|
| 261 |
+
inputs_debug=[input_image_debug, prompt_debug, number_debug]
|
| 262 |
|
| 263 |
input_image_debug.upload(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
|
|
|
| 264 |
prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 265 |
+
number_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 266 |
+
|
| 267 |
+
gr.on(
|
| 268 |
+
triggers=[run_button.click, prompt.submit],
|
| 269 |
+
fn = infer,
|
| 270 |
+
inputs = [input_image, prompt, seed, randomize_seed, guidance_scale, steps, width, height],
|
| 271 |
+
outputs = [result, download_button, seed, reuse_button]
|
| 272 |
+
)
|
| 273 |
+
reuse_button.click(
|
| 274 |
+
fn = lambda image: image,
|
| 275 |
+
inputs = [result],
|
| 276 |
+
outputs = [input_image]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
)
|
| 278 |
|
| 279 |
+
demo.launch(mcp_server=True)
|
|
|
optimization.py
CHANGED
|
@@ -1,156 +1,60 @@
|
|
| 1 |
-
"""
|
| 2 |
-
"""
|
| 3 |
-
|
| 4 |
-
from typing import Any
|
| 5 |
-
from typing import Callable
|
| 6 |
-
from typing import ParamSpec
|
| 7 |
-
|
| 8 |
-
import
|
| 9 |
-
import
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
from
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 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 |
-
path_1 = hf_hub_download(repo_id=repo_id, filename=filename_1)
|
| 62 |
-
path_2 = hf_hub_download(repo_id=repo_id, filename=filename_2)
|
| 63 |
-
|
| 64 |
-
payload_1 = torch.load(path_1, map_location="cpu", weights_only=False)
|
| 65 |
-
payload_2 = torch.load(path_2, map_location="cpu", weights_only=False)
|
| 66 |
-
|
| 67 |
-
if not isinstance(payload_1, dict) or not isinstance(payload_2, dict):
|
| 68 |
-
raise TypeError("Precompiled files are not payload dicts. Please re-export them with to_serializable_dict().")
|
| 69 |
-
|
| 70 |
-
compiled_1 = ZeroGPUCompiledModelFromDict(payload_1, device=device)
|
| 71 |
-
compiled_2 = ZeroGPUCompiledModelFromDict(payload_2, device=device)
|
| 72 |
-
return compiled_1, compiled_2
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _strtobool(v: str | None, default: bool = True) -> bool:
|
| 76 |
-
if v is None:
|
| 77 |
-
return default
|
| 78 |
-
return v.strip().lower() in ("1", "true", "yes", "y", "on")
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
| 82 |
-
global COMPILED_TRANSFORMER_1, COMPILED_TRANSFORMER_2
|
| 83 |
-
|
| 84 |
-
@spaces.GPU(duration=1500)
|
| 85 |
-
def compile_transformer():
|
| 86 |
-
pipeline.load_lora_weights(
|
| 87 |
-
"Kijai/WanVideo_comfy",
|
| 88 |
-
weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",
|
| 89 |
-
adapter_name="lightx2v",
|
| 90 |
-
)
|
| 91 |
-
kwargs_lora = {"load_into_transformer_2": True}
|
| 92 |
-
pipeline.load_lora_weights(
|
| 93 |
-
"Kijai/WanVideo_comfy",
|
| 94 |
-
weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",
|
| 95 |
-
adapter_name="lightx2v_2",
|
| 96 |
-
**kwargs_lora,
|
| 97 |
-
)
|
| 98 |
-
pipeline.set_adapters(["lightx2v", "lightx2v_2"], adapter_weights=[1.0, 1.0])
|
| 99 |
-
pipeline.fuse_lora(adapter_names=["lightx2v"], lora_scale=3.0, components=["transformer"])
|
| 100 |
-
pipeline.fuse_lora(adapter_names=["lightx2v_2"], lora_scale=1.0, components=["transformer_2"])
|
| 101 |
-
pipeline.unload_lora_weights()
|
| 102 |
-
|
| 103 |
-
with capture_component_call(pipeline, "transformer") as call:
|
| 104 |
-
pipeline(*args, **kwargs)
|
| 105 |
-
|
| 106 |
-
dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
|
| 107 |
-
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
| 108 |
-
|
| 109 |
-
quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 110 |
-
quantize_(pipeline.transformer_2, Float8DynamicActivationFloat8WeightConfig())
|
| 111 |
-
|
| 112 |
-
exported_1 = torch.export.export(
|
| 113 |
-
mod=pipeline.transformer,
|
| 114 |
-
args=call.args,
|
| 115 |
-
kwargs=call.kwargs,
|
| 116 |
-
dynamic_shapes=dynamic_shapes,
|
| 117 |
-
)
|
| 118 |
-
exported_2 = torch.export.export(
|
| 119 |
-
mod=pipeline.transformer_2,
|
| 120 |
-
args=call.args,
|
| 121 |
-
kwargs=call.kwargs,
|
| 122 |
-
dynamic_shapes=dynamic_shapes,
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
compiled_1 = aoti_compile(exported_1, INDUCTOR_CONFIGS)
|
| 126 |
-
compiled_2 = aoti_compile(exported_2, INDUCTOR_CONFIGS)
|
| 127 |
-
return compiled_1, compiled_2
|
| 128 |
-
|
| 129 |
-
# Quantize text encoder
|
| 130 |
-
quantize_(pipeline.text_encoder, Int8WeightOnlyConfig())
|
| 131 |
-
|
| 132 |
-
use_precompiled = False
|
| 133 |
-
precompiled_repo = os.getenv("WAN_PRECOMPILED_REPO", "Fabrice-TIERCELIN/Wan_2.2_compiled")
|
| 134 |
-
|
| 135 |
-
if use_precompiled:
|
| 136 |
-
try:
|
| 137 |
-
compiled_transformer_1, compiled_transformer_2 = load_compiled_transformers_from_hub(
|
| 138 |
-
repo_id=precompiled_repo,
|
| 139 |
-
device="cuda",
|
| 140 |
-
)
|
| 141 |
-
except Exception as e:
|
| 142 |
-
# fallback if payload format is wrong / outdated
|
| 143 |
-
print(f"[WARN] Failed to load precompiled artifacts ({e}). Falling back to GPU compilation.")
|
| 144 |
-
compiled_transformer_1, compiled_transformer_2 = compile_transformer()
|
| 145 |
-
else:
|
| 146 |
-
compiled_transformer_1, compiled_transformer_2 = compile_transformer()
|
| 147 |
-
|
| 148 |
-
# expose for downloads
|
| 149 |
-
COMPILED_TRANSFORMER_1 = compiled_transformer_1
|
| 150 |
-
COMPILED_TRANSFORMER_2 = compiled_transformer_2
|
| 151 |
-
|
| 152 |
-
pipeline.transformer.forward = compiled_transformer_1
|
| 153 |
-
drain_module_parameters(pipeline.transformer)
|
| 154 |
-
|
| 155 |
-
pipeline.transformer_2.forward = compiled_transformer_2
|
| 156 |
-
drain_module_parameters(pipeline.transformer_2)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
from typing import Callable
|
| 6 |
+
from typing import ParamSpec
|
| 7 |
+
|
| 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 |
+
TRANSFORMER_HIDDEN_DIM = torch.export.Dim('hidden', min=4096, max=8212)
|
| 20 |
+
|
| 21 |
+
TRANSFORMER_DYNAMIC_SHAPES = {
|
| 22 |
+
'hidden_states': {1: TRANSFORMER_HIDDEN_DIM},
|
| 23 |
+
'img_ids': {0: TRANSFORMER_HIDDEN_DIM},
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
INDUCTOR_CONFIGS = {
|
| 27 |
+
'conv_1x1_as_mm': True,
|
| 28 |
+
'epilogue_fusion': False,
|
| 29 |
+
'coordinate_descent_tuning': True,
|
| 30 |
+
'coordinate_descent_check_all_directions': True,
|
| 31 |
+
'max_autotune': True,
|
| 32 |
+
'triton.cudagraphs': True,
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
| 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 |
+
pipeline.transformer.fuse_qkv_projections()
|
| 48 |
+
|
| 49 |
+
exported = torch.export.export(
|
| 50 |
+
mod=pipeline.transformer,
|
| 51 |
+
args=call.args,
|
| 52 |
+
kwargs=call.kwargs,
|
| 53 |
+
dynamic_shapes=dynamic_shapes,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
return aoti_compile(exported, INDUCTOR_CONFIGS)
|
| 57 |
+
|
| 58 |
+
transformer_config = pipeline.transformer.config
|
| 59 |
+
pipeline.transformer = compile_transformer()
|
| 60 |
+
pipeline.transformer.config = transformer_config # pyright: ignore[reportAttributeAccessIssue]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
optimization_utils.py
CHANGED
|
@@ -1,166 +1,96 @@
|
|
| 1 |
-
"""
|
| 2 |
-
"""
|
| 3 |
-
import contextlib
|
| 4 |
-
from contextvars import ContextVar
|
| 5 |
-
from io import BytesIO
|
| 6 |
-
from typing import Any
|
| 7 |
-
from typing import cast
|
| 8 |
-
from unittest.mock import patch
|
| 9 |
-
|
| 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
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
'aot_inductor.
|
| 19 |
-
'aot_inductor.
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
for name
|
| 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 |
-
|
| 97 |
-
def __call__(self, *args, **kwargs):
|
| 98 |
-
if (compiled_model := self.compiled_model.get()) is None:
|
| 99 |
-
compiled_model = cast(AOTICompiledModel, torch._inductor.aoti_load_package(self.archive_file))
|
| 100 |
-
self.compiled_model.set(compiled_model)
|
| 101 |
-
|
| 102 |
-
if not self._loaded_constants:
|
| 103 |
-
# Move constants to target device (cuda) and keep dtype as-is (bf16)
|
| 104 |
-
constants_map = {k: v.to(device="cuda", dtype=torch.bfloat16).contiguous() for k, v in self.constants_map_cpu.items()}
|
| 105 |
-
compiled_model.load_constants(constants_map, check_full_update=True, user_managed=True)
|
| 106 |
-
self._loaded_constants = True
|
| 107 |
-
|
| 108 |
-
return compiled_model(*args, **kwargs)
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
def aoti_compile(
|
| 112 |
-
exported_program: torch.export.ExportedProgram,
|
| 113 |
-
inductor_configs: dict[str, Any] | None = None,
|
| 114 |
-
):
|
| 115 |
-
inductor_configs = (inductor_configs or {}) | INDUCTOR_CONFIGS_OVERRIDES
|
| 116 |
-
gm = cast(torch.fx.GraphModule, exported_program.module())
|
| 117 |
-
assert exported_program.example_inputs is not None
|
| 118 |
-
args, kwargs = exported_program.example_inputs
|
| 119 |
-
artifacts = torch._inductor.aot_compile(gm, args, kwargs, options=inductor_configs)
|
| 120 |
-
archive_file = BytesIO()
|
| 121 |
-
files: list[str | Weights] = [file for file in artifacts if isinstance(file, str)]
|
| 122 |
-
package_aoti(archive_file, files)
|
| 123 |
-
weights, = (artifact for artifact in artifacts if isinstance(artifact, Weights))
|
| 124 |
-
zerogpu_weights = ZeroGPUWeights({name: weights.get_weight(name)[0] for name in weights})
|
| 125 |
-
return ZeroGPUCompiledModel(archive_file, zerogpu_weights)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
@contextlib.contextmanager
|
| 129 |
-
def capture_component_call(
|
| 130 |
-
pipeline: Any,
|
| 131 |
-
component_name: str,
|
| 132 |
-
component_method='forward',
|
| 133 |
-
):
|
| 134 |
-
|
| 135 |
-
class CapturedCallException(Exception):
|
| 136 |
-
def __init__(self, *args, **kwargs):
|
| 137 |
-
super().__init__()
|
| 138 |
-
self.args = args
|
| 139 |
-
self.kwargs = kwargs
|
| 140 |
-
|
| 141 |
-
class CapturedCall:
|
| 142 |
-
def __init__(self):
|
| 143 |
-
self.args: tuple[Any, ...] = ()
|
| 144 |
-
self.kwargs: dict[str, Any] = {}
|
| 145 |
-
|
| 146 |
-
component = getattr(pipeline, component_name)
|
| 147 |
-
captured_call = CapturedCall()
|
| 148 |
-
|
| 149 |
-
def capture_call(*args, **kwargs):
|
| 150 |
-
raise CapturedCallException(*args, **kwargs)
|
| 151 |
-
|
| 152 |
-
with patch.object(component, component_method, new=capture_call):
|
| 153 |
-
try:
|
| 154 |
-
yield captured_call
|
| 155 |
-
except CapturedCallException as e:
|
| 156 |
-
captured_call.args = e.args
|
| 157 |
-
captured_call.kwargs = e.kwargs
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def drain_module_parameters(module: torch.nn.Module):
|
| 161 |
-
state_dict_meta = {name: {'device': tensor.device, 'dtype': tensor.dtype} for name, tensor in module.state_dict().items()}
|
| 162 |
-
state_dict = {name: torch.nn.Parameter(torch.empty_like(tensor, device='cpu')) for name, tensor in module.state_dict().items()}
|
| 163 |
-
module.load_state_dict(state_dict, assign=True)
|
| 164 |
-
for name, param in state_dict.items():
|
| 165 |
-
meta = state_dict_meta[name]
|
| 166 |
-
param.data = torch.Tensor([]).to(**meta)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
"""
|
| 3 |
+
import contextlib
|
| 4 |
+
from contextvars import ContextVar
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
from typing import Any
|
| 7 |
+
from typing import cast
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
|
| 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 |
+
|
| 17 |
+
INDUCTOR_CONFIGS_OVERRIDES = {
|
| 18 |
+
'aot_inductor.package_constants_in_so': False,
|
| 19 |
+
'aot_inductor.package_constants_on_disk': True,
|
| 20 |
+
'aot_inductor.package': True,
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ZeroGPUCompiledModel:
|
| 25 |
+
def __init__(self, archive_file: torch.types.FileLike, weights: Weights, cuda: bool = False):
|
| 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 |
+
weight_dict: dict[str, tuple[torch.Tensor, TensorProperties]] = {}
|
| 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(
|
| 52 |
+
exported_program: torch.export.ExportedProgram,
|
| 53 |
+
inductor_configs: dict[str, Any] | None = None,
|
| 54 |
+
):
|
| 55 |
+
inductor_configs = (inductor_configs or {}) | INDUCTOR_CONFIGS_OVERRIDES
|
| 56 |
+
gm = cast(torch.fx.GraphModule, exported_program.module())
|
| 57 |
+
assert exported_program.example_inputs is not None
|
| 58 |
+
args, kwargs = exported_program.example_inputs
|
| 59 |
+
artifacts = torch._inductor.aot_compile(gm, args, kwargs, options=inductor_configs)
|
| 60 |
+
archive_file = BytesIO()
|
| 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 |
+
return ZeroGPUCompiledModel(archive_file, weights)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@contextlib.contextmanager
|
| 68 |
+
def capture_component_call(
|
| 69 |
+
pipeline: Any,
|
| 70 |
+
component_name: str,
|
| 71 |
+
component_method='forward',
|
| 72 |
+
):
|
| 73 |
+
|
| 74 |
+
class CapturedCallException(Exception):
|
| 75 |
+
def __init__(self, *args, **kwargs):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.args = args
|
| 78 |
+
self.kwargs = kwargs
|
| 79 |
+
|
| 80 |
+
class CapturedCall:
|
| 81 |
+
def __init__(self):
|
| 82 |
+
self.args: tuple[Any, ...] = ()
|
| 83 |
+
self.kwargs: dict[str, Any] = {}
|
| 84 |
+
|
| 85 |
+
component = getattr(pipeline, component_name)
|
| 86 |
+
captured_call = CapturedCall()
|
| 87 |
+
|
| 88 |
+
def capture_call(*args, **kwargs):
|
| 89 |
+
raise CapturedCallException(*args, **kwargs)
|
| 90 |
+
|
| 91 |
+
with patch.object(component, component_method, new=capture_call):
|
| 92 |
+
try:
|
| 93 |
+
yield captured_call
|
| 94 |
+
except CapturedCallException as e:
|
| 95 |
+
captured_call.args = e.args
|
| 96 |
+
captured_call.kwargs = e.kwargs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,12 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
sentencepiece==0.2.1
|
| 7 |
-
peft==0.18.0
|
| 8 |
-
ftfy==6.3.1
|
| 9 |
-
imageio==2.37.2
|
| 10 |
-
imageio-ffmpeg==0.6.0
|
| 11 |
-
|
| 12 |
-
torchao==0.14.1
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
git+https://github.com/huggingface/diffusers.git
|
| 3 |
+
accelerate
|
| 4 |
+
safetensors
|
| 5 |
+
sentencepiece
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|