Spaces:
Runtime error
Runtime error
Upload 10 files
Browse files- .gitattributes +1 -0
- README.md +4 -6
- app.py +302 -238
- bird.webp +3 -0
- cat_window.webp +0 -0
- diffusers.zip +3 -0
- optimization.py +45 -28
- person1.webp +0 -0
- requirements.txt +5 -2
- woman1.webp +0 -0
- woman2.webp +0 -0
.gitattributes
CHANGED
|
@@ -70,3 +70,4 @@ poli_tower.png filter=lfs diff=lfs merge=lfs -text
|
|
| 70 |
squatting_sonic.png filter=lfs diff=lfs merge=lfs -text
|
| 71 |
tower_takes_off.png filter=lfs diff=lfs merge=lfs -text
|
| 72 |
ugly_sonic.jpeg filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 70 |
squatting_sonic.png filter=lfs diff=lfs merge=lfs -text
|
| 71 |
tower_takes_off.png filter=lfs diff=lfs merge=lfs -text
|
| 72 |
ugly_sonic.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
bird.webp filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,14 +1,12 @@
|
|
| 1 |
---
|
| 2 |
-
title: FLUX.
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 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
|
|
|
|
| 1 |
---
|
| 2 |
+
title: FLUX.2 [Klein] 4B
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.3.0
|
| 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,198 +1,275 @@
|
|
| 1 |
-
# PyTorch 2.8 (temporary hack)
|
| 2 |
import os
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
try:
|
| 7 |
-
import spaces
|
| 8 |
-
except:
|
| 9 |
-
class spaces():
|
| 10 |
-
def GPU(*args, **kwargs):
|
| 11 |
-
def decorator(function):
|
| 12 |
-
return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs)
|
| 13 |
-
return decorator
|
| 14 |
-
|
| 15 |
import gradio as gr
|
| 16 |
import numpy as np
|
| 17 |
-
import torch
|
| 18 |
import random
|
| 19 |
-
import
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
from PIL import Image
|
| 23 |
-
import
|
| 24 |
-
import
|
| 25 |
-
import
|
| 26 |
-
from pathlib import Path
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
from optimization import optimize_pipeline_
|
| 32 |
|
| 33 |
MAX_SEED = np.iinfo(np.int32).max
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
img.save(file_path, format=format_ or img.format)
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
seed = 42,
|
| 62 |
-
randomize_seed = False,
|
| 63 |
-
guidance_scale = 2.5,
|
| 64 |
-
steps = 28,
|
| 65 |
-
width = -1,
|
| 66 |
-
height = -1,
|
| 67 |
-
progress=gr.Progress(track_tqdm=True)
|
| 68 |
-
):
|
| 69 |
-
"""
|
| 70 |
-
Perform image editing using the FLUX.1 Kontext pipeline.
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
prompt (str): Text description of the desired edit to apply to the image.
|
| 80 |
-
Examples: "Remove glasses", "Add a hat", "Change background to beach".
|
| 81 |
-
seed (int, optional): Random seed for reproducible generation. Defaults to 42.
|
| 82 |
-
Must be between 0 and MAX_SEED (2^31 - 1).
|
| 83 |
-
randomize_seed (bool, optional): If True, generates a random seed instead of
|
| 84 |
-
using the provided seed value. Defaults to False.
|
| 85 |
-
guidance_scale (float, optional): Controls how closely the model follows the
|
| 86 |
-
prompt. Higher values mean stronger adherence to the prompt but may reduce
|
| 87 |
-
image quality. Range: 1.0-10.0. Defaults to 2.5.
|
| 88 |
-
steps (int, optional): Controls how many steps to run the diffusion model for.
|
| 89 |
-
Range: 1-30. Defaults to 28.
|
| 90 |
-
progress (gr.Progress, optional): Gradio progress tracker for monitoring
|
| 91 |
-
generation progress. Defaults to gr.Progress(track_tqdm=True).
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
Example:
|
| 100 |
-
>>> edited_image, used_seed, button_update = infer(
|
| 101 |
-
... input_image=my_image,
|
| 102 |
-
... prompt="Add sunglasses",
|
| 103 |
-
... seed=123,
|
| 104 |
-
... randomize_seed=False,
|
| 105 |
-
... guidance_scale=2.5
|
| 106 |
-
... )
|
| 107 |
-
"""
|
| 108 |
if randomize_seed:
|
| 109 |
seed = random.randint(0, MAX_SEED)
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
image = pipe(
|
| 114 |
-
image=input_image,
|
| 115 |
-
prompt=prompt,
|
| 116 |
-
guidance_scale=guidance_scale,
|
| 117 |
-
width = input_image.size[0] if width == -1 else width,
|
| 118 |
-
height = input_image.size[1] if height == -1 else height,
|
| 119 |
-
num_inference_steps=steps,
|
| 120 |
-
generator=torch.Generator().manual_seed(seed),
|
| 121 |
-
).images[0]
|
| 122 |
-
else:
|
| 123 |
-
image = pipe(
|
| 124 |
-
prompt=prompt,
|
| 125 |
-
guidance_scale=guidance_scale,
|
| 126 |
-
num_inference_steps=steps,
|
| 127 |
-
generator=torch.Generator().manual_seed(seed),
|
| 128 |
-
).images[0]
|
| 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 |
#col-container {
|
| 171 |
margin: 0 auto;
|
| 172 |
-
max-width:
|
|
|
|
|
|
|
|
|
|
| 173 |
}
|
| 174 |
"""
|
| 175 |
|
| 176 |
with gr.Blocks(css=css) as demo:
|
| 177 |
|
| 178 |
with gr.Column(elem_id="col-container"):
|
| 179 |
-
gr.Markdown(f"""# FLUX.
|
| 180 |
-
|
| 181 |
""")
|
| 182 |
with gr.Row():
|
| 183 |
with gr.Column():
|
| 184 |
-
input_image = gr.Image(label="Upload the image for editing", type="pil")
|
| 185 |
with gr.Row():
|
| 186 |
prompt = gr.Text(
|
| 187 |
label="Prompt",
|
| 188 |
show_label=False,
|
| 189 |
-
max_lines=
|
| 190 |
-
placeholder="Enter your prompt
|
| 191 |
container=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
)
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
with gr.Accordion("Advanced Settings", open=False):
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
seed = gr.Slider(
|
| 197 |
label="Seed",
|
| 198 |
minimum=0,
|
|
@@ -203,97 +280,84 @@ Image editing and manipulation model guidance-distilled from FLUX.1 Kontext [pro
|
|
| 203 |
|
| 204 |
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
label="Output width",
|
| 224 |
-
info="-1 = original width",
|
| 225 |
-
minimum=-1,
|
| 226 |
-
maximum=1024,
|
| 227 |
-
value=-1,
|
| 228 |
-
step=1
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
height = gr.Slider(
|
| 232 |
-
label="Output height",
|
| 233 |
-
info="-1 = original height",
|
| 234 |
-
minimum=-1,
|
| 235 |
-
maximum=1024,
|
| 236 |
-
value=-1,
|
| 237 |
-
step=1
|
| 238 |
-
)
|
| 239 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
with gr.Column():
|
| 241 |
-
result = gr.Image(label="Result", show_label=False
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
with gr.Row(visible=False):
|
| 246 |
-
download_button = gr.DownloadButton(elem_id="download_btn", interactive = True)
|
| 247 |
-
result_gallery = gr.Gallery(label = 'Downloadable results', show_label = True, interactive = False, elem_id = "gallery1")
|
| 248 |
gr.Examples(
|
| 249 |
-
examples=
|
| 250 |
-
|
| 251 |
-
],
|
| 252 |
-
|
| 253 |
-
outputs=[result_gallery, seed, download_button],
|
| 254 |
-
fn=infer_example,
|
| 255 |
-
run_on_click=True,
|
| 256 |
cache_examples=True,
|
| 257 |
-
cache_mode=
|
| 258 |
)
|
| 259 |
-
prompt_debug=gr.Textbox(label="Prompt Debug")
|
| 260 |
-
input_image_debug=gr.Image(type="pil", label="Image Debug")
|
| 261 |
-
number_debug=gr.Slider(label="Number Debug", minimum=1, maximum=50, step=1, value=50)
|
| 262 |
-
|
| 263 |
-
gr.Examples(
|
| 264 |
-
label = "Examples from demo",
|
| 265 |
-
examples=[
|
| 266 |
-
["flowers.png", "turn the flowers into sunflowers"],
|
| 267 |
-
["monster.png", "make this monster ride a skateboard on the beach"],
|
| 268 |
-
["cat.png", "make this cat happy"]
|
| 269 |
-
],
|
| 270 |
-
inputs=[input_image, prompt],
|
| 271 |
-
outputs=[result, download_button, seed],
|
| 272 |
-
fn=infer
|
| 273 |
-
)
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
-
input_image_debug.upload(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 284 |
-
prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 285 |
-
number_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
|
| 286 |
-
|
| 287 |
gr.on(
|
| 288 |
triggers=[run_button.click, prompt.submit],
|
| 289 |
-
fn
|
| 290 |
-
inputs
|
| 291 |
-
outputs
|
| 292 |
-
)
|
| 293 |
-
reuse_button.click(
|
| 294 |
-
fn = lambda image: image,
|
| 295 |
-
inputs = [result],
|
| 296 |
-
outputs = [input_image]
|
| 297 |
)
|
| 298 |
|
| 299 |
-
demo.launch(
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
|
|
|
| 7 |
import random
|
| 8 |
+
import spaces
|
| 9 |
+
import torch
|
| 10 |
+
from diffusers import Flux2KleinPipeline
|
| 11 |
+
import requests
|
| 12 |
from PIL import Image
|
| 13 |
+
import json
|
| 14 |
+
import base64
|
| 15 |
+
from huggingface_hub import InferenceClient
|
|
|
|
| 16 |
|
| 17 |
+
dtype = torch.bfloat16
|
| 18 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
|
|
|
| 19 |
|
| 20 |
MAX_SEED = np.iinfo(np.int32).max
|
| 21 |
+
MAX_IMAGE_SIZE = 1024
|
| 22 |
+
|
| 23 |
+
hf_client = InferenceClient(
|
| 24 |
+
api_key=os.environ.get("HF_TOKEN"),
|
| 25 |
+
)
|
| 26 |
+
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
|
| 27 |
+
|
| 28 |
+
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.
|
| 29 |
+
|
| 30 |
+
Guidelines:
|
| 31 |
+
1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
|
| 32 |
+
2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
|
| 33 |
+
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.
|
| 34 |
+
|
| 35 |
+
Output only the revised prompt and nothing else."""
|
| 36 |
+
|
| 37 |
+
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).
|
| 38 |
+
|
| 39 |
+
Rules:
|
| 40 |
+
- Single instruction only, no commentary
|
| 41 |
+
- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
|
| 42 |
+
- Specify what changes AND what stays the same (face, lighting, composition)
|
| 43 |
+
- Reference actual image elements
|
| 44 |
+
- Turn negatives into positives ("don't change X" → "keep X")
|
| 45 |
+
- Make abstractions concrete ("futuristic" → "glowing cyan neon, metallic panels")
|
| 46 |
+
- Keep content PG-13
|
| 47 |
+
|
| 48 |
+
Output only the final instruction in plain text and nothing else."""
|
| 49 |
+
|
| 50 |
+
# Model repository IDs for 4B
|
| 51 |
+
REPO_ID_REGULAR = "black-forest-labs/FLUX.2-klein-base-4B"
|
| 52 |
+
REPO_ID_DISTILLED = "black-forest-labs/FLUX.2-klein-4B"
|
| 53 |
+
|
| 54 |
+
# Load both 4B models
|
| 55 |
+
print("Loading 4B Regular model...")
|
| 56 |
+
pipe_regular = Flux2KleinPipeline.from_pretrained(REPO_ID_REGULAR, torch_dtype=dtype)
|
| 57 |
+
pipe_regular.to("cuda")
|
| 58 |
+
|
| 59 |
+
print("Loading 4B Distilled model...")
|
| 60 |
+
pipe_distilled = Flux2KleinPipeline.from_pretrained(REPO_ID_DISTILLED, torch_dtype=dtype)
|
| 61 |
+
pipe_distilled.to("cuda")
|
| 62 |
+
|
| 63 |
+
# Dictionary for easy access
|
| 64 |
+
pipes = {
|
| 65 |
+
"Distilled (4 steps)": pipe_distilled,
|
| 66 |
+
"Base (50 steps)": pipe_regular,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# Default steps for each mode
|
| 70 |
+
DEFAULT_STEPS = {
|
| 71 |
+
"Distilled (4 steps)": 4,
|
| 72 |
+
"Base (50 steps)": 50,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
# Default CFG for each mode
|
| 76 |
+
DEFAULT_CFG = {
|
| 77 |
+
"Distilled (4 steps)": 1.0,
|
| 78 |
+
"Base (50 steps)": 4.0,
|
| 79 |
+
}
|
| 80 |
|
| 81 |
+
def image_to_data_uri(img):
|
| 82 |
+
buffered = io.BytesIO()
|
| 83 |
+
img.save(buffered, format="PNG")
|
| 84 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 85 |
+
return f"data:image/png;base64,{img_str}"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def upsample_prompt_logic(prompt, image_list):
|
| 89 |
+
try:
|
| 90 |
+
if image_list and len(image_list) > 0:
|
| 91 |
+
# Image + Text Editing Mode
|
| 92 |
+
system_content = SYSTEM_PROMPT_WITH_IMAGES
|
| 93 |
+
|
| 94 |
+
# Construct user message with text and images
|
| 95 |
+
user_content = [{"type": "text", "text": prompt}]
|
| 96 |
+
|
| 97 |
+
for img in image_list:
|
| 98 |
+
data_uri = image_to_data_uri(img)
|
| 99 |
+
user_content.append({
|
| 100 |
+
"type": "image_url",
|
| 101 |
+
"image_url": {"url": data_uri}
|
| 102 |
+
})
|
| 103 |
+
|
| 104 |
+
messages = [
|
| 105 |
+
{"role": "system", "content": system_content},
|
| 106 |
+
{"role": "user", "content": user_content}
|
| 107 |
+
]
|
| 108 |
+
else:
|
| 109 |
+
# Text Only Mode
|
| 110 |
+
system_content = SYSTEM_PROMPT_TEXT_ONLY
|
| 111 |
+
messages = [
|
| 112 |
+
{"role": "system", "content": system_content},
|
| 113 |
+
{"role": "user", "content": prompt}
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
completion = hf_client.chat.completions.create(
|
| 117 |
+
model=VLM_MODEL,
|
| 118 |
+
messages=messages,
|
| 119 |
+
max_tokens=1024
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
return completion.choices[0].message.content
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print(f"Upsampling failed: {e}")
|
| 125 |
+
return prompt
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def update_dimensions_from_image(image_list):
|
| 129 |
+
"""Update width/height sliders based on uploaded image aspect ratio.
|
| 130 |
+
Keeps one side at 1024 and scales the other proportionally, with both sides as multiples of 8."""
|
| 131 |
+
if image_list is None or len(image_list) == 0:
|
| 132 |
+
return 1024, 1024 # Default dimensions
|
| 133 |
|
| 134 |
+
# Get the first image to determine dimensions
|
| 135 |
+
img = image_list[0][0] # Gallery returns list of tuples (image, caption)
|
| 136 |
+
img_width, img_height = img.size
|
| 137 |
|
| 138 |
+
aspect_ratio = img_width / img_height
|
|
|
|
| 139 |
|
| 140 |
+
if aspect_ratio >= 1: # Landscape or square
|
| 141 |
+
new_width = 1024
|
| 142 |
+
new_height = int(1024 / aspect_ratio)
|
| 143 |
+
else: # Portrait
|
| 144 |
+
new_height = 1024
|
| 145 |
+
new_width = int(1024 * aspect_ratio)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# Round to nearest multiple of 8
|
| 148 |
+
new_width = round(new_width / 8) * 8
|
| 149 |
+
new_height = round(new_height / 8) * 8
|
| 150 |
|
| 151 |
+
# Ensure within valid range (minimum 256, maximum 1024)
|
| 152 |
+
new_width = max(256, min(1024, new_width))
|
| 153 |
+
new_height = max(256, min(1024, new_height))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
return new_width, new_height
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def update_steps_from_mode(mode_choice):
|
| 159 |
+
"""Update the number of inference steps based on the selected mode."""
|
| 160 |
+
return DEFAULT_STEPS[mode_choice], DEFAULT_CFG[mode_choice]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@spaces.GPU(duration=85)
|
| 164 |
+
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)):
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
if randomize_seed:
|
| 167 |
seed = random.randint(0, MAX_SEED)
|
| 168 |
|
| 169 |
+
# Select the appropriate pipeline based on mode choice
|
| 170 |
+
pipe = pipes[mode_choice]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# Prepare image list (convert None or empty gallery to None)
|
| 173 |
+
image_list = None
|
| 174 |
+
if input_images is not None and len(input_images) > 0:
|
| 175 |
+
image_list = []
|
| 176 |
+
for item in input_images:
|
| 177 |
+
image_list.append(item[0])
|
| 178 |
+
|
| 179 |
+
# 1. Upsampling (Network bound)
|
| 180 |
+
final_prompt = prompt
|
| 181 |
+
if prompt_upsampling:
|
| 182 |
+
progress(0.1, desc="Upsampling prompt...")
|
| 183 |
+
final_prompt = upsample_prompt_logic(prompt, image_list)
|
| 184 |
+
print(f"Original Prompt: {prompt}")
|
| 185 |
+
print(f"Upsampled Prompt: {final_prompt}")
|
| 186 |
+
|
| 187 |
+
# 2. Image Generation
|
| 188 |
+
progress(0.2, desc=f"Generating image with 4B {mode_choice}...")
|
| 189 |
+
|
| 190 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 191 |
+
|
| 192 |
+
pipe_kwargs = {
|
| 193 |
+
"prompt": final_prompt,
|
| 194 |
+
"height": height,
|
| 195 |
+
"width": width,
|
| 196 |
+
"num_inference_steps": num_inference_steps,
|
| 197 |
+
"guidance_scale": guidance_scale,
|
| 198 |
+
"generator": generator,
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
# Add images if provided
|
| 202 |
+
if image_list is not None:
|
| 203 |
+
pipe_kwargs["image"] = image_list
|
| 204 |
+
|
| 205 |
+
image = pipe(**pipe_kwargs).images[0]
|
| 206 |
+
|
| 207 |
+
return image, seed
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
examples = [
|
| 211 |
+
["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"],
|
| 212 |
+
["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."],
|
| 213 |
+
["Soaking wet capybara taking shelter under a banana leaf in the rainy jungle, close up photo"],
|
| 214 |
+
["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."],
|
| 215 |
+
]
|
| 216 |
+
|
| 217 |
+
examples_images = [
|
| 218 |
+
["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"]]
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
css = """
|
| 222 |
#col-container {
|
| 223 |
margin: 0 auto;
|
| 224 |
+
max-width: 1200px;
|
| 225 |
+
}
|
| 226 |
+
.gallery-container img{
|
| 227 |
+
object-fit: contain;
|
| 228 |
}
|
| 229 |
"""
|
| 230 |
|
| 231 |
with gr.Blocks(css=css) as demo:
|
| 232 |
|
| 233 |
with gr.Column(elem_id="col-container"):
|
| 234 |
+
gr.Markdown(f"""# FLUX.2 [Klein] - 4B (Apache 2.0)
|
| 235 |
+
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)]
|
| 236 |
""")
|
| 237 |
with gr.Row():
|
| 238 |
with gr.Column():
|
|
|
|
| 239 |
with gr.Row():
|
| 240 |
prompt = gr.Text(
|
| 241 |
label="Prompt",
|
| 242 |
show_label=False,
|
| 243 |
+
max_lines=2,
|
| 244 |
+
placeholder="Enter your prompt",
|
| 245 |
container=False,
|
| 246 |
+
scale=3
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
run_button = gr.Button("Run", scale=1)
|
| 250 |
+
|
| 251 |
+
with gr.Accordion("Input image(s) (optional)", open=False):
|
| 252 |
+
input_images = gr.Gallery(
|
| 253 |
+
label="Input Image(s)",
|
| 254 |
+
type="pil",
|
| 255 |
+
columns=3,
|
| 256 |
+
rows=1,
|
| 257 |
)
|
| 258 |
+
|
| 259 |
+
mode_choice = gr.Radio(
|
| 260 |
+
label="Mode",
|
| 261 |
+
choices=["Distilled (4 steps)", "Base (50 steps)"],
|
| 262 |
+
value="Distilled (4 steps)",
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
with gr.Accordion("Advanced Settings", open=False):
|
| 266 |
|
| 267 |
+
prompt_upsampling = gr.Checkbox(
|
| 268 |
+
label="Prompt Upsampling",
|
| 269 |
+
value=False,
|
| 270 |
+
info="Automatically enhance the prompt using a VLM"
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
seed = gr.Slider(
|
| 274 |
label="Seed",
|
| 275 |
minimum=0,
|
|
|
|
| 280 |
|
| 281 |
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 282 |
|
| 283 |
+
with gr.Row():
|
| 284 |
+
|
| 285 |
+
width = gr.Slider(
|
| 286 |
+
label="Width",
|
| 287 |
+
minimum=256,
|
| 288 |
+
maximum=MAX_IMAGE_SIZE,
|
| 289 |
+
step=8,
|
| 290 |
+
value=1024,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
height = gr.Slider(
|
| 294 |
+
label="Height",
|
| 295 |
+
minimum=256,
|
| 296 |
+
maximum=MAX_IMAGE_SIZE,
|
| 297 |
+
step=8,
|
| 298 |
+
value=1024,
|
| 299 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
+
with gr.Row():
|
| 302 |
+
|
| 303 |
+
num_inference_steps = gr.Slider(
|
| 304 |
+
label="Number of inference steps",
|
| 305 |
+
minimum=1,
|
| 306 |
+
maximum=100,
|
| 307 |
+
step=1,
|
| 308 |
+
value=4,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
guidance_scale = gr.Slider(
|
| 312 |
+
label="Guidance scale",
|
| 313 |
+
minimum=0.0,
|
| 314 |
+
maximum=10.0,
|
| 315 |
+
step=0.1,
|
| 316 |
+
value=1.0,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
with gr.Column():
|
| 321 |
+
result = gr.Image(label="Result", show_label=False)
|
| 322 |
+
|
| 323 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
gr.Examples(
|
| 325 |
+
examples=examples,
|
| 326 |
+
fn=infer,
|
| 327 |
+
inputs=[prompt],
|
| 328 |
+
outputs=[result, seed],
|
|
|
|
|
|
|
|
|
|
| 329 |
cache_examples=True,
|
| 330 |
+
cache_mode="lazy"
|
| 331 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
+
gr.Examples(
|
| 334 |
+
examples=examples_images,
|
| 335 |
+
fn=infer,
|
| 336 |
+
inputs=[prompt, input_images],
|
| 337 |
+
outputs=[result, seed],
|
| 338 |
+
cache_examples=True,
|
| 339 |
+
cache_mode="lazy"
|
| 340 |
+
)
|
| 341 |
|
| 342 |
+
# Auto-update dimensions when images are uploaded
|
| 343 |
+
input_images.upload(
|
| 344 |
+
fn=update_dimensions_from_image,
|
| 345 |
+
inputs=[input_images],
|
| 346 |
+
outputs=[width, height]
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Auto-update steps when mode changes
|
| 350 |
+
mode_choice.change(
|
| 351 |
+
fn=update_steps_from_mode,
|
| 352 |
+
inputs=[mode_choice],
|
| 353 |
+
outputs=[num_inference_steps, guidance_scale]
|
| 354 |
+
)
|
| 355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
gr.on(
|
| 357 |
triggers=[run_button.click, prompt.submit],
|
| 358 |
+
fn=infer,
|
| 359 |
+
inputs=[prompt, input_images, mode_choice, seed, randomize_seed, width, height, num_inference_steps, guidance_scale, prompt_upsampling],
|
| 360 |
+
outputs=[result, seed]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
)
|
| 362 |
|
| 363 |
+
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,23 +4,35 @@
|
|
| 4 |
from typing import Any
|
| 5 |
from typing import Callable
|
| 6 |
from typing import ParamSpec
|
| 7 |
-
|
| 8 |
import spaces
|
| 9 |
import torch
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
from
|
| 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 |
-
'
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
}
|
| 25 |
|
| 26 |
INDUCTOR_CONFIGS = {
|
|
@@ -32,29 +44,34 @@ INDUCTOR_CONFIGS = {
|
|
| 32 |
'triton.cudagraphs': True,
|
| 33 |
}
|
| 34 |
|
| 35 |
-
|
| 36 |
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
pipeline(*args, **kwargs)
|
| 43 |
|
| 44 |
-
dynamic_shapes =
|
| 45 |
-
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
| 46 |
-
|
| 47 |
-
pipeline.transformer.fuse_qkv_projections()
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
-
return aoti_compile(exported, INDUCTOR_CONFIGS)
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
| 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 |
|
| 38 |
INDUCTOR_CONFIGS = {
|
|
|
|
| 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,5 +1,8 @@
|
|
|
|
|
| 1 |
transformers
|
| 2 |
-
git+https://github.com/huggingface/diffusers.git
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/diffusers.git@flux2-klein
|
| 2 |
transformers
|
|
|
|
| 3 |
accelerate
|
| 4 |
safetensors
|
| 5 |
+
bitsandbytes
|
| 6 |
+
torchao
|
| 7 |
+
kernels
|
| 8 |
+
spaces==0.43.0
|
woman1.webp
ADDED
|
woman2.webp
ADDED
|