Spaces:
Restarting on Zero
Restarting on Zero
Upload 10 files
Browse files- README.md +7 -8
- app.py +465 -464
- bird.webp +3 -0
- cat_window.webp +0 -0
- diffusers.zip +3 -0
- optimization.py +43 -122
- person1.webp +0 -0
- requirements.txt +4 -4
- woman1.webp +0 -0
- woman2.webp +0 -0
README.md
CHANGED
|
@@ -1,13 +1,12 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
-
pinned:
|
| 10 |
-
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: FLUX.2 [Klein] 4B
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.29.1
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
|
@@ -1,464 +1,465 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
import
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
from diffusers import
|
| 15 |
-
|
| 16 |
-
import
|
| 17 |
-
import
|
| 18 |
-
import
|
| 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 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 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 |
-
image=
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
""
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
file_path = tmp_dir / filename
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
img.save(file_path, format=format_ or img.format)
|
| 246 |
-
|
| 247 |
-
return file_path
|
| 248 |
-
|
| 249 |
-
def infer_example(
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
)
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
prompt,
|
| 446 |
-
seed,
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import tempfile
|
| 4 |
+
import zipfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import io
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import numpy as np
|
| 11 |
+
import random
|
| 12 |
+
import spaces
|
| 13 |
+
import torch
|
| 14 |
+
from diffusers import Flux2KleinPipeline
|
| 15 |
+
import requests
|
| 16 |
+
from PIL import Image
|
| 17 |
+
import json
|
| 18 |
+
import base64
|
| 19 |
+
from huggingface_hub import InferenceClient
|
| 20 |
+
|
| 21 |
+
dtype = torch.bfloat16
|
| 22 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
|
| 24 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 25 |
+
MAX_IMAGE_SIZE = 1024
|
| 26 |
+
|
| 27 |
+
hf_client = InferenceClient(
|
| 28 |
+
api_key=os.environ.get("HF_TOKEN"),
|
| 29 |
+
)
|
| 30 |
+
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
|
| 31 |
+
|
| 32 |
+
SYSTEM_PROMPT_TEXT_ONLY = """You are an expert prompt engineer for FLUX.2 by Black Forest Labs. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent.
|
| 33 |
+
|
| 34 |
+
Guidelines:
|
| 35 |
+
1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
|
| 36 |
+
2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
|
| 37 |
+
3. Text in Images: Put ALL text in quotation marks, matching the prompt's language. Always provide explicit quoted text for objects that would contain text in reality (signs, labels, screens, etc.) - without it, the model generates gibberish.
|
| 38 |
+
|
| 39 |
+
Output only the revised prompt and nothing else."""
|
| 40 |
+
|
| 41 |
+
SYSTEM_PROMPT_WITH_IMAGES = """You are FLUX.2 by Black Forest Labs, an image-editing expert. You convert editing requests into one concise instruction (50-80 words, ~30 for brief requests).
|
| 42 |
+
|
| 43 |
+
Rules:
|
| 44 |
+
- Single instruction only, no commentary
|
| 45 |
+
- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
|
| 46 |
+
- Specify what changes AND what stays the same (face, lighting, composition)
|
| 47 |
+
- Reference actual image elements
|
| 48 |
+
- Turn negatives into positives ("don't change X" → "keep X")
|
| 49 |
+
- Make abstractions concrete ("futuristic" → "glowing cyan neon, metallic panels")
|
| 50 |
+
- Keep content PG-13
|
| 51 |
+
|
| 52 |
+
Output only the final instruction in plain text and nothing else."""
|
| 53 |
+
|
| 54 |
+
# Model repository IDs for 4B
|
| 55 |
+
REPO_ID_REGULAR = "black-forest-labs/FLUX.2-klein-base-4B"
|
| 56 |
+
REPO_ID_DISTILLED = "black-forest-labs/FLUX.2-klein-4B"
|
| 57 |
+
|
| 58 |
+
# Load both 4B models
|
| 59 |
+
print("Loading 4B Regular model...")
|
| 60 |
+
pipe_regular = Flux2KleinPipeline.from_pretrained(REPO_ID_REGULAR, torch_dtype=dtype)
|
| 61 |
+
pipe_regular.to("cuda")
|
| 62 |
+
|
| 63 |
+
print("Loading 4B Distilled model...")
|
| 64 |
+
pipe_distilled = Flux2KleinPipeline.from_pretrained(REPO_ID_DISTILLED, torch_dtype=dtype)
|
| 65 |
+
pipe_distilled.to("cuda")
|
| 66 |
+
|
| 67 |
+
# Dictionary for easy access
|
| 68 |
+
pipes = {
|
| 69 |
+
"Distilled (4 steps)": pipe_distilled,
|
| 70 |
+
"Base (50 steps)": pipe_regular,
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# Default steps for each mode
|
| 74 |
+
DEFAULT_STEPS = {
|
| 75 |
+
"Distilled (4 steps)": 4,
|
| 76 |
+
"Base (50 steps)": 50,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# Default CFG for each mode
|
| 80 |
+
DEFAULT_CFG = {
|
| 81 |
+
"Distilled (4 steps)": 1.0,
|
| 82 |
+
"Base (50 steps)": 4.0,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
prompt_debug_value = [None]
|
| 86 |
+
input_images_debug_value = [None]
|
| 87 |
+
number_debug_value = [None]
|
| 88 |
+
|
| 89 |
+
def image_to_data_uri(img):
|
| 90 |
+
buffered = io.BytesIO()
|
| 91 |
+
img.save(buffered, format="PNG")
|
| 92 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 93 |
+
return f"data:image/png;base64,{img_str}"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def upsample_prompt_logic(prompt, image_list):
|
| 97 |
+
try:
|
| 98 |
+
if image_list and len(image_list) > 0:
|
| 99 |
+
# Image + Text Editing Mode
|
| 100 |
+
system_content = SYSTEM_PROMPT_WITH_IMAGES
|
| 101 |
+
|
| 102 |
+
# Construct user message with text and images
|
| 103 |
+
user_content = [{"type": "text", "text": prompt}]
|
| 104 |
+
|
| 105 |
+
for img in image_list:
|
| 106 |
+
data_uri = image_to_data_uri(img)
|
| 107 |
+
user_content.append({
|
| 108 |
+
"type": "image_url",
|
| 109 |
+
"image_url": {"url": data_uri}
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
messages = [
|
| 113 |
+
{"role": "system", "content": system_content},
|
| 114 |
+
{"role": "user", "content": user_content}
|
| 115 |
+
]
|
| 116 |
+
else:
|
| 117 |
+
# Text Only Mode
|
| 118 |
+
system_content = SYSTEM_PROMPT_TEXT_ONLY
|
| 119 |
+
messages = [
|
| 120 |
+
{"role": "system", "content": system_content},
|
| 121 |
+
{"role": "user", "content": prompt}
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
completion = hf_client.chat.completions.create(
|
| 125 |
+
model=VLM_MODEL,
|
| 126 |
+
messages=messages,
|
| 127 |
+
max_tokens=1024
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
return completion.choices[0].message.content
|
| 131 |
+
except Exception as e:
|
| 132 |
+
print(f"Upsampling failed: {e}")
|
| 133 |
+
return prompt
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def update_dimensions_from_image(image_list):
|
| 137 |
+
"""Update width/height sliders based on uploaded image aspect ratio.
|
| 138 |
+
Keeps one side at 1024 and scales the other proportionally, with both sides as multiples of 8."""
|
| 139 |
+
if image_list is None or len(image_list) == 0:
|
| 140 |
+
return 1024, 1024 # Default dimensions
|
| 141 |
+
|
| 142 |
+
# Get the first image to determine dimensions
|
| 143 |
+
img = image_list[0][0] # Gallery returns list of tuples (image, caption)
|
| 144 |
+
img_width, img_height = img.size
|
| 145 |
+
|
| 146 |
+
aspect_ratio = img_width / img_height
|
| 147 |
+
|
| 148 |
+
if aspect_ratio >= 1: # Landscape or square
|
| 149 |
+
new_width = 1024
|
| 150 |
+
new_height = int(1024 / aspect_ratio)
|
| 151 |
+
else: # Portrait
|
| 152 |
+
new_height = 1024
|
| 153 |
+
new_width = int(1024 * aspect_ratio)
|
| 154 |
+
|
| 155 |
+
# Round to nearest multiple of 8
|
| 156 |
+
new_width = round(new_width / 8) * 8
|
| 157 |
+
new_height = round(new_height / 8) * 8
|
| 158 |
+
|
| 159 |
+
# Ensure within valid range (minimum 256, maximum 1024)
|
| 160 |
+
new_width = max(256, min(1024, new_width))
|
| 161 |
+
new_height = max(256, min(1024, new_height))
|
| 162 |
+
|
| 163 |
+
return new_width, new_height
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def update_steps_from_mode(mode_choice):
|
| 167 |
+
"""Update the number of inference steps based on the selected mode."""
|
| 168 |
+
return DEFAULT_STEPS[mode_choice], DEFAULT_CFG[mode_choice]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@spaces.GPU(duration=85)
|
| 172 |
+
def infer(prompt, input_images=None, mode_choice="Distilled (4 steps)", seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, guidance_scale=4.0, prompt_upsampling=False, progress=gr.Progress(track_tqdm=True)):
|
| 173 |
+
|
| 174 |
+
if randomize_seed:
|
| 175 |
+
seed = random.randint(0, MAX_SEED)
|
| 176 |
+
|
| 177 |
+
# Select the appropriate pipeline based on mode choice
|
| 178 |
+
pipe = pipes[mode_choice]
|
| 179 |
+
|
| 180 |
+
# Prepare image list (convert None or empty gallery to None)
|
| 181 |
+
image_list = None
|
| 182 |
+
if input_images is not None and len(input_images) > 0:
|
| 183 |
+
image_list = []
|
| 184 |
+
for item in input_images:
|
| 185 |
+
image_list.append(item[0])
|
| 186 |
+
|
| 187 |
+
# 1. Upsampling (Network bound)
|
| 188 |
+
final_prompt = prompt
|
| 189 |
+
if prompt_upsampling:
|
| 190 |
+
progress(0.1, desc="Upsampling prompt...")
|
| 191 |
+
final_prompt = upsample_prompt_logic(prompt, image_list)
|
| 192 |
+
print(f"Original Prompt: {prompt}")
|
| 193 |
+
print(f"Upsampled Prompt: {final_prompt}")
|
| 194 |
+
|
| 195 |
+
# 2. Image Generation
|
| 196 |
+
progress(0.2, desc=f"Generating image with 4B {mode_choice}...")
|
| 197 |
+
|
| 198 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 199 |
+
|
| 200 |
+
pipe_kwargs = {
|
| 201 |
+
"prompt": final_prompt,
|
| 202 |
+
"height": height,
|
| 203 |
+
"width": width,
|
| 204 |
+
"num_inference_steps": num_inference_steps,
|
| 205 |
+
"guidance_scale": guidance_scale,
|
| 206 |
+
"generator": generator,
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
# Add images if provided
|
| 210 |
+
if image_list is not None:
|
| 211 |
+
pipe_kwargs["image"] = image_list
|
| 212 |
+
|
| 213 |
+
image = pipe(**pipe_kwargs).images[0]
|
| 214 |
+
|
| 215 |
+
return image, seed
|
| 216 |
+
|
| 217 |
+
def export_images_to_zip(gallery) -> str:
|
| 218 |
+
"""
|
| 219 |
+
Bundle compiled_transformer_1 and compiled_transformer_2 into a zip file and return the file path.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
tmp_zip = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
|
| 223 |
+
tmp_zip.close()
|
| 224 |
+
|
| 225 |
+
with zipfile.ZipFile(tmp_zip.name, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
| 226 |
+
for i in range(len(gallery)):
|
| 227 |
+
image_path = gallery[i]
|
| 228 |
+
zf.write(image_path, arcname=os.path.basename(image_path))
|
| 229 |
+
|
| 230 |
+
print(str(len(gallery)) + " images zipped")
|
| 231 |
+
return tmp_zip.name
|
| 232 |
+
|
| 233 |
+
def save_on_path(img: Image, filename: str, format_: str = None) -> Path:
|
| 234 |
+
"""
|
| 235 |
+
Save `img` in a unique temporary folder under the given `filename`
|
| 236 |
+
and return its absolute path.
|
| 237 |
+
"""
|
| 238 |
+
# 1) unique temporary folder
|
| 239 |
+
tmp_dir = Path(tempfile.mkdtemp(prefix="pil_tmp_"))
|
| 240 |
+
|
| 241 |
+
# 2) full path of the future file
|
| 242 |
+
file_path = tmp_dir / filename
|
| 243 |
+
|
| 244 |
+
# 3) save
|
| 245 |
+
img.save(file_path, format=format_ or img.format)
|
| 246 |
+
|
| 247 |
+
return file_path
|
| 248 |
+
|
| 249 |
+
def infer_example(prompt, input_images=None, mode_choice="Distilled (4 steps)", seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, guidance_scale=4.0, prompt_upsampling=False):
|
| 250 |
+
number=1
|
| 251 |
+
if prompt_debug_value[0] is not None or input_images_debug_value[0] is not None or number_debug_value[0] is not None:
|
| 252 |
+
prompt=prompt_debug_value[0]
|
| 253 |
+
input_images=input_images_debug_value[0]
|
| 254 |
+
number=number_debug_value[0]
|
| 255 |
+
|
| 256 |
+
gallery = []
|
| 257 |
+
for i in range(number):
|
| 258 |
+
try:
|
| 259 |
+
print("Generating #" + str(i + 1) + " image...")
|
| 260 |
+
seed = random.randint(0, MAX_SEED)
|
| 261 |
+
[image, seed] = infer(prompt, input_images, mode_choice, seed, True, width, height, num_inference_steps, guidance_scale, prompt_upsampling)
|
| 262 |
+
image_filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f") + '.webp'
|
| 263 |
+
path = save_on_path(image, image_filename, format_="WEBP")
|
| 264 |
+
gallery.append(path)
|
| 265 |
+
except Exception as e:
|
| 266 |
+
print('Error: ' + e.message if e is not None else '')
|
| 267 |
+
#raise e
|
| 268 |
+
zip_path = export_images_to_zip(gallery)
|
| 269 |
+
return [seed, zip_path, "Done!"]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
examples = [
|
| 273 |
+
["Create a vase on a table in living room, the color of the vase is a gradient of color, starting with #02eb3c color and finishing with #edfa3c. The flowers inside the vase have the color #ff0088"],
|
| 274 |
+
["Photorealistic infographic showing the complete Berlin TV Tower (Fernsehturm) from ground base to antenna tip, full vertical view with entire structure visible including concrete shaft, metallic sphere, and antenna spire. Slight upward perspective angle looking up toward the iconic sphere, perfectly centered on clean white background. Left side labels with thin horizontal connector lines: the text '368m' in extra large bold dark grey numerals (#2D3748) positioned at exactly the antenna tip with 'TOTAL HEIGHT' in small caps below. The text '207m' in extra large bold with 'TELECAFÉ' in small caps below, with connector line touching the sphere precisely at the window level. Right side label with horizontal connector line touching the sphere's equator: the text '32m' in extra large bold dark grey numerals with 'SPHERE DIAMETER' in small caps below. Bottom section arranged in three balanced columns: Left - Large text '986' in extra bold dark grey with 'STEPS' in caps below. Center - 'BERLIN TV TOWER' in bold caps with 'FERNSEHTURM' in lighter weight below. Right - 'INAUGURATED' in bold caps with 'OCTOBER 3, 1969' below. All typography in modern sans-serif font (such as Inter or Helvetica), color #2D3748, clean minimal technical diagram style. Horizontal connector lines are thin, precise, and clearly visible, touching the tower structure at exact corresponding measurement points. Professional architectural elevation drawing aesthetic with dynamic low angle perspective creating sense of height and grandeur, poster-ready infographic design with perfect visual hierarchy."],
|
| 275 |
+
["Soaking wet capybara taking shelter under a banana leaf in the rainy jungle, close up photo"],
|
| 276 |
+
["A kawaii die-cut sticker of a chubby orange cat, featuring big sparkly eyes and a happy smile with paws raised in greeting and a heart-shaped pink nose. The design should have smooth rounded lines with black outlines and soft gradient shading with pink cheeks."],
|
| 277 |
+
]
|
| 278 |
+
|
| 279 |
+
examples_images = [
|
| 280 |
+
["The person from image 1 is petting the cat from image 2, the bird from image 3 is next to them", ["woman1.webp", "cat_window.webp", "bird.webp"]]
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
css = """
|
| 284 |
+
#col-container {
|
| 285 |
+
margin: 0 auto;
|
| 286 |
+
max-width: 1200px;
|
| 287 |
+
}
|
| 288 |
+
.gallery-container img{
|
| 289 |
+
object-fit: contain;
|
| 290 |
+
}
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
with gr.Blocks(css=css) as demo:
|
| 294 |
+
|
| 295 |
+
with gr.Column(elem_id="col-container"):
|
| 296 |
+
gr.Markdown(f"""# FLUX.2 [Klein] - 4B (Apache 2.0)
|
| 297 |
+
FLUX.2 [klein] is a fast, unified image generation and editing model designed for fast inference [[model](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B)], [[blog](https://bfl.ai/blog/flux-2)]
|
| 298 |
+
""")
|
| 299 |
+
with gr.Row():
|
| 300 |
+
with gr.Column():
|
| 301 |
+
with gr.Row():
|
| 302 |
+
prompt = gr.Text(
|
| 303 |
+
label="Prompt",
|
| 304 |
+
show_label=False,
|
| 305 |
+
max_lines=2,
|
| 306 |
+
placeholder="Enter your prompt",
|
| 307 |
+
container=False,
|
| 308 |
+
scale=3
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
run_button = gr.Button("Run", scale=1)
|
| 312 |
+
|
| 313 |
+
with gr.Accordion("Input image(s) (optional)", open=False):
|
| 314 |
+
input_images = gr.Gallery(
|
| 315 |
+
label="Input Image(s)",
|
| 316 |
+
type="pil",
|
| 317 |
+
columns=3,
|
| 318 |
+
rows=1,
|
| 319 |
+
)
|
| 320 |
+
input_image = gr.Image(label="Upload the image for editing", type="pil")
|
| 321 |
+
|
| 322 |
+
mode_choice = gr.Radio(
|
| 323 |
+
label="Mode",
|
| 324 |
+
choices=["Distilled (4 steps)", "Base (50 steps)"],
|
| 325 |
+
value="Distilled (4 steps)",
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 329 |
+
|
| 330 |
+
prompt_upsampling = gr.Checkbox(
|
| 331 |
+
label="Prompt Upsampling",
|
| 332 |
+
value=False,
|
| 333 |
+
info="Automatically enhance the prompt using a VLM"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
seed = gr.Slider(
|
| 337 |
+
label="Seed",
|
| 338 |
+
minimum=0,
|
| 339 |
+
maximum=MAX_SEED,
|
| 340 |
+
step=1,
|
| 341 |
+
value=0,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 345 |
+
|
| 346 |
+
with gr.Row():
|
| 347 |
+
|
| 348 |
+
width = gr.Slider(
|
| 349 |
+
label="Width",
|
| 350 |
+
minimum=256,
|
| 351 |
+
maximum=MAX_IMAGE_SIZE,
|
| 352 |
+
step=8,
|
| 353 |
+
value=1024,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
height = gr.Slider(
|
| 357 |
+
label="Height",
|
| 358 |
+
minimum=256,
|
| 359 |
+
maximum=MAX_IMAGE_SIZE,
|
| 360 |
+
step=8,
|
| 361 |
+
value=1024,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
with gr.Row():
|
| 365 |
+
|
| 366 |
+
num_inference_steps = gr.Slider(
|
| 367 |
+
label="Number of inference steps",
|
| 368 |
+
minimum=1,
|
| 369 |
+
maximum=100,
|
| 370 |
+
step=1,
|
| 371 |
+
value=4,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
guidance_scale = gr.Slider(
|
| 375 |
+
label="Guidance scale",
|
| 376 |
+
minimum=0.0,
|
| 377 |
+
maximum=10.0,
|
| 378 |
+
step=0.1,
|
| 379 |
+
value=1.0,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
with gr.Column():
|
| 384 |
+
result = gr.Image(label="Result", show_label=False)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
gr.Examples(
|
| 388 |
+
examples=examples,
|
| 389 |
+
fn=infer,
|
| 390 |
+
inputs=[prompt],
|
| 391 |
+
outputs=[result, seed],
|
| 392 |
+
cache_examples=True,
|
| 393 |
+
cache_mode="lazy"
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
gr.Examples(
|
| 397 |
+
examples=examples_images,
|
| 398 |
+
fn=infer,
|
| 399 |
+
inputs=[prompt, input_images],
|
| 400 |
+
outputs=[result, seed],
|
| 401 |
+
cache_examples=True,
|
| 402 |
+
cache_mode="lazy"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Auto-update dimensions when images are uploaded
|
| 406 |
+
input_images.upload(
|
| 407 |
+
fn=update_dimensions_from_image,
|
| 408 |
+
inputs=[input_images],
|
| 409 |
+
outputs=[width, height]
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# Auto-update steps when mode changes
|
| 413 |
+
mode_choice.change(
|
| 414 |
+
fn=update_steps_from_mode,
|
| 415 |
+
inputs=[mode_choice],
|
| 416 |
+
outputs=[num_inference_steps, guidance_scale]
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
gr.on(
|
| 420 |
+
triggers=[run_button.click, prompt.submit],
|
| 421 |
+
fn=infer,
|
| 422 |
+
inputs=[prompt, input_images, mode_choice, seed, randomize_seed, width, height, num_inference_steps, guidance_scale, prompt_upsampling],
|
| 423 |
+
outputs=[result, seed]
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
with gr.Row(visible=False):
|
| 427 |
+
download_button = gr.DownloadButton(elem_id="download_btn", interactive = True)
|
| 428 |
+
info_debug = gr.HTML(value = "")
|
| 429 |
+
prompt_debug = gr.Text(
|
| 430 |
+
max_lines=2,
|
| 431 |
+
container=False,
|
| 432 |
+
scale=3
|
| 433 |
+
)
|
| 434 |
+
input_images_debug = gr.Gallery(
|
| 435 |
+
label="Input Image(s)",
|
| 436 |
+
type="pil",
|
| 437 |
+
columns=3,
|
| 438 |
+
rows=1,
|
| 439 |
+
)
|
| 440 |
+
gr.Examples(
|
| 441 |
+
examples=[
|
| 442 |
+
["A dog", "woman1.webp"]
|
| 443 |
+
],
|
| 444 |
+
fn=infer_example,
|
| 445 |
+
inputs=[prompt, input_image],
|
| 446 |
+
outputs=[seed, download_button, info_debug],
|
| 447 |
+
run_on_click=True,
|
| 448 |
+
cache_examples=True,
|
| 449 |
+
cache_mode='lazy'
|
| 450 |
+
)
|
| 451 |
+
number_debug=gr.Slider(minimum=1, maximum=50, step=1, value=50)
|
| 452 |
+
|
| 453 |
+
def handle_field_debug_change(prompt_debug_data, input_images_debug_data, number_debug_data):
|
| 454 |
+
prompt_debug_value[0] = prompt_debug_data
|
| 455 |
+
input_images_debug_value[0] = input_images_debug_data
|
| 456 |
+
number_debug_value[0] = number_debug_data
|
| 457 |
+
return []
|
| 458 |
+
|
| 459 |
+
inputs_debug=[prompt_debug, input_images_debug, number_debug]
|
| 460 |
+
|
| 461 |
+
prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 462 |
+
input_images_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 463 |
+
number_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 464 |
+
|
| 465 |
+
demo.launch()
|
bird.webp
ADDED
|
Git LFS Details
|
cat_window.webp
ADDED
|
diffusers.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f21e689d4807674000c1da8d3a084f7d521e961ee26ebd77e7a55a8efc3b95d
|
| 3 |
+
size 5269929
|
optimization.py
CHANGED
|
@@ -4,37 +4,34 @@
|
|
| 4 |
from typing import Any
|
| 5 |
from typing import Callable
|
| 6 |
from typing import ParamSpec
|
| 7 |
-
|
| 8 |
-
import os
|
| 9 |
import spaces
|
| 10 |
import torch
|
| 11 |
-
from
|
| 12 |
-
from
|
| 13 |
-
from
|
| 14 |
-
from torchao.quantization import Int8WeightOnlyConfig
|
| 15 |
-
from huggingface_hub import hf_hub_download
|
| 16 |
-
|
| 17 |
-
from optimization_utils import capture_component_call
|
| 18 |
-
from optimization_utils import aoti_compile
|
| 19 |
-
from optimization_utils import drain_module_parameters
|
| 20 |
-
from optimization_utils import ZeroGPUCompiledModelFromDict # NEW
|
| 21 |
-
|
| 22 |
|
| 23 |
P = ParamSpec('P')
|
| 24 |
|
| 25 |
-
|
| 26 |
-
COMPILED_TRANSFORMER_1 = None
|
| 27 |
-
COMPILED_TRANSFORMER_2 = None
|
| 28 |
-
|
| 29 |
-
LATENT_FRAMES_DIM = torch.export.Dim('num_latent_frames', min=8, max=81)
|
| 30 |
-
LATENT_PATCHED_HEIGHT_DIM = torch.export.Dim('latent_patched_height', min=30, max=52)
|
| 31 |
-
LATENT_PATCHED_WIDTH_DIM = torch.export.Dim('latent_patched_width', min=30, max=52)
|
| 32 |
|
| 33 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
| 34 |
-
'
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
},
|
| 39 |
}
|
| 40 |
|
|
@@ -47,110 +44,34 @@ INDUCTOR_CONFIGS = {
|
|
| 47 |
'triton.cudagraphs': True,
|
| 48 |
}
|
| 49 |
|
| 50 |
-
|
| 51 |
-
def load_compiled_transformers_from_hub(
|
| 52 |
-
repo_id: str,
|
| 53 |
-
filename_1: str = "compiled_transformer_1.pt",
|
| 54 |
-
filename_2: str = "compiled_transformer_2.pt",
|
| 55 |
-
device: str = "cuda",
|
| 56 |
-
):
|
| 57 |
-
"""
|
| 58 |
-
Loads the payload dicts (created via ZeroGPUCompiledModel.to_serializable_dict() and torch.save)
|
| 59 |
-
and rebuilds callable models that will move constants to CUDA on first call.
|
| 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 |
-
|
| 85 |
-
|
| 86 |
-
pipeline.
|
| 87 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
pipeline(*args, **kwargs)
|
| 105 |
|
| 106 |
-
dynamic_shapes =
|
| 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 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 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 |
-
|
| 153 |
-
drain_module_parameters(pipeline.transformer)
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from typing import Any
|
| 5 |
from typing import Callable
|
| 6 |
from typing import ParamSpec
|
|
|
|
|
|
|
| 7 |
import spaces
|
| 8 |
import torch
|
| 9 |
+
from spaces.zero.torch.aoti import ZeroGPUCompiledModel
|
| 10 |
+
from spaces.zero.torch.aoti import ZeroGPUWeights
|
| 11 |
+
from torch.utils._pytree import tree_map
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
P = ParamSpec('P')
|
| 14 |
|
| 15 |
+
TRANSFORMER_IMAGE_DIM = torch.export.Dim('image_seq_length', min=4096, max=16384) # min: 0 images, max: 3 (1024x1024) images
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
| 18 |
+
'double': {
|
| 19 |
+
'hidden_states': {
|
| 20 |
+
1: TRANSFORMER_IMAGE_DIM,
|
| 21 |
+
},
|
| 22 |
+
'image_rotary_emb': (
|
| 23 |
+
{0: TRANSFORMER_IMAGE_DIM + 512},
|
| 24 |
+
{0: TRANSFORMER_IMAGE_DIM + 512},
|
| 25 |
+
),
|
| 26 |
+
},
|
| 27 |
+
'single': {
|
| 28 |
+
'hidden_states': {
|
| 29 |
+
1: TRANSFORMER_IMAGE_DIM + 512,
|
| 30 |
+
},
|
| 31 |
+
'image_rotary_emb': (
|
| 32 |
+
{0: TRANSFORMER_IMAGE_DIM + 512},
|
| 33 |
+
{0: TRANSFORMER_IMAGE_DIM + 512},
|
| 34 |
+
),
|
| 35 |
},
|
| 36 |
}
|
| 37 |
|
|
|
|
| 44 |
'triton.cudagraphs': True,
|
| 45 |
}
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
|
|
|
| 48 |
|
| 49 |
+
blocks = {
|
| 50 |
+
'double': pipeline.transformer.transformer_blocks,
|
| 51 |
+
'single': pipeline.transformer.single_transformer_blocks,
|
| 52 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
@spaces.GPU(duration=1200)
|
| 55 |
+
def compile_block(blocks_kind: str):
|
| 56 |
+
block = blocks[blocks_kind][0]
|
| 57 |
+
with spaces.aoti_capture(block) as call:
|
| 58 |
pipeline(*args, **kwargs)
|
| 59 |
|
| 60 |
+
dynamic_shapes = tree_map(lambda t: None, call.kwargs)
|
| 61 |
+
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES[blocks_kind]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
exported = torch.export.export(
|
| 65 |
+
mod=block,
|
| 66 |
+
args=call.args,
|
| 67 |
+
kwargs=call.kwargs,
|
| 68 |
+
dynamic_shapes=dynamic_shapes,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
return spaces.aoti_compile(exported, INDUCTOR_CONFIGS).archive_file
|
|
|
|
| 72 |
|
| 73 |
+
for blocks_kind in ('double', 'single'):
|
| 74 |
+
archive_file = compile_block(blocks_kind)
|
| 75 |
+
for block in blocks[blocks_kind]:
|
| 76 |
+
weights = ZeroGPUWeights(block.state_dict())
|
| 77 |
+
block.forward = ZeroGPUCompiledModel(archive_file, weights)
|
person1.webp
ADDED
|
requirements.txt
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
git+https://github.com/huggingface/diffusers.git
|
| 2 |
transformers
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
-
|
| 6 |
-
|
| 7 |
kernels
|
| 8 |
-
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/diffusers.git
|
| 2 |
transformers
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
+
bitsandbytes
|
| 6 |
+
torchao
|
| 7 |
kernels
|
| 8 |
+
spaces==0.43.0
|
woman1.webp
ADDED
|
woman2.webp
ADDED
|