Fabrice-TIERCELIN commited on
Commit
e6633e4
·
verified ·
1 Parent(s): c719d4e

Upload 8 files

Browse files
Files changed (4) hide show
  1. README.md +13 -11
  2. app.py +299 -464
  3. optimization.py +28 -45
  4. requirements.txt +5 -8
README.md CHANGED
@@ -1,12 +1,14 @@
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
 
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,464 +1,299 @@
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
- try:
258
- for i in range(number):
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:
266
- print("Error")
267
- zip_path = export_images_to_zip(gallery)
268
- return [seed, zip_path, "Done!"]
269
-
270
-
271
- examples = [
272
- ["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"],
273
- ["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."],
274
- ["Soaking wet capybara taking shelter under a banana leaf in the rainy jungle, close up photo"],
275
- ["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."],
276
- ]
277
-
278
- examples_images = [
279
- ["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"]]
280
- ]
281
-
282
- css = """
283
- #col-container {
284
- margin: 0 auto;
285
- max-width: 1200px;
286
- }
287
- .gallery-container img{
288
- object-fit: contain;
289
- }
290
- """
291
-
292
- with gr.Blocks(css=css) as demo:
293
-
294
- with gr.Column(elem_id="col-container"):
295
- gr.Markdown(f"""# FLUX.2 [Klein] - 4B (Apache 2.0)
296
- 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)]
297
- """)
298
- with gr.Row():
299
- with gr.Column():
300
- with gr.Row():
301
- prompt = gr.Text(
302
- label="Prompt",
303
- show_label=False,
304
- max_lines=2,
305
- placeholder="Enter your prompt",
306
- container=False,
307
- scale=3
308
- )
309
-
310
- run_button = gr.Button("Run", scale=1)
311
-
312
- with gr.Accordion("Input image(s) (optional)", open=False):
313
- input_images = gr.Gallery(
314
- label="Input Image(s)",
315
- type="pil",
316
- columns=3,
317
- rows=1,
318
- )
319
- input_image = gr.Image(label="Upload the image for editing", type="pil")
320
-
321
- mode_choice = gr.Radio(
322
- label="Mode",
323
- choices=["Distilled (4 steps)", "Base (50 steps)"],
324
- value="Distilled (4 steps)",
325
- )
326
-
327
- with gr.Accordion("Advanced Settings", open=False):
328
-
329
- prompt_upsampling = gr.Checkbox(
330
- label="Prompt Upsampling",
331
- value=False,
332
- info="Automatically enhance the prompt using a VLM"
333
- )
334
-
335
- seed = gr.Slider(
336
- label="Seed",
337
- minimum=0,
338
- maximum=MAX_SEED,
339
- step=1,
340
- value=0,
341
- )
342
-
343
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
344
-
345
- with gr.Row():
346
-
347
- width = gr.Slider(
348
- label="Width",
349
- minimum=256,
350
- maximum=MAX_IMAGE_SIZE,
351
- step=8,
352
- value=1024,
353
- )
354
-
355
- height = gr.Slider(
356
- label="Height",
357
- minimum=256,
358
- maximum=MAX_IMAGE_SIZE,
359
- step=8,
360
- value=1024,
361
- )
362
-
363
- with gr.Row():
364
-
365
- num_inference_steps = gr.Slider(
366
- label="Number of inference steps",
367
- minimum=1,
368
- maximum=100,
369
- step=1,
370
- value=4,
371
- )
372
-
373
- guidance_scale = gr.Slider(
374
- label="Guidance scale",
375
- minimum=0.0,
376
- maximum=10.0,
377
- step=0.1,
378
- value=1.0,
379
- )
380
-
381
-
382
- with gr.Column():
383
- result = gr.Image(label="Result", show_label=False)
384
-
385
-
386
- gr.Examples(
387
- examples=examples,
388
- fn=infer,
389
- inputs=[prompt],
390
- outputs=[result, seed],
391
- cache_examples=True,
392
- cache_mode="lazy"
393
- )
394
-
395
- gr.Examples(
396
- examples=examples_images,
397
- fn=infer,
398
- inputs=[prompt, input_images],
399
- outputs=[result, seed],
400
- cache_examples=True,
401
- cache_mode="lazy"
402
- )
403
-
404
- # Auto-update dimensions when images are uploaded
405
- input_images.upload(
406
- fn=update_dimensions_from_image,
407
- inputs=[input_images],
408
- outputs=[width, height]
409
- )
410
-
411
- # Auto-update steps when mode changes
412
- mode_choice.change(
413
- fn=update_steps_from_mode,
414
- inputs=[mode_choice],
415
- outputs=[num_inference_steps, guidance_scale]
416
- )
417
-
418
- gr.on(
419
- triggers=[run_button.click, prompt.submit],
420
- fn=infer,
421
- inputs=[prompt, input_images, mode_choice, seed, randomize_seed, width, height, num_inference_steps, guidance_scale, prompt_upsampling],
422
- outputs=[result, seed]
423
- )
424
-
425
- with gr.Row(visible=False):
426
- download_button = gr.DownloadButton(elem_id="download_btn", interactive = True)
427
- info_debug = gr.HTML(value = "")
428
- prompt_debug = gr.Text(
429
- max_lines=2,
430
- container=False,
431
- scale=3
432
- )
433
- input_images_debug = gr.Gallery(
434
- label="Input Image(s)",
435
- type="pil",
436
- columns=3,
437
- rows=1,
438
- )
439
- gr.Examples(
440
- examples=[
441
- ["A dog", "woman1.webp"]
442
- ],
443
- fn=infer_example,
444
- inputs=[prompt, input_image],
445
- outputs=[seed, download_button, info_debug],
446
- run_on_click=True,
447
- cache_examples=True,
448
- cache_mode='lazy'
449
- )
450
- number_debug=gr.Slider(minimum=1, maximum=50, step=1, value=50)
451
-
452
- def handle_field_debug_change(prompt_debug_data, input_images_debug_data, number_debug_data):
453
- prompt_debug_value[0] = prompt_debug_data
454
- input_images_debug_value[0] = input_images_debug_data
455
- number_debug_value[0] = number_debug_data
456
- return []
457
-
458
- inputs_debug=[prompt_debug, input_images_debug, number_debug]
459
-
460
- prompt_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
461
- input_images_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
462
- number_debug.change(fn=handle_field_debug_change, inputs=inputs_debug, outputs=[])
463
-
464
- demo.launch()
 
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:
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 os
20
+ from datetime import datetime
21
+
22
+ from PIL import Image
23
+ import tempfile
24
+ import zipfile
25
+ import shutil
26
+ from pathlib import Path
27
+
28
+ from diffusers import FluxKontextPipeline
29
+ from diffusers.utils import load_image
30
+
31
+ from optimization import optimize_pipeline_
32
+
33
+ MAX_SEED = np.iinfo(np.int32).max
34
+
35
+ pipe = FluxKontextPipeline.from_pretrained("yuvraj108c/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16).to("cuda")
36
+ optimize_pipeline_(pipe, image=Image.new("RGB", (512, 512)), prompt='prompt')
37
+
38
+ input_image_debug_value = [None]
39
+ prompt_debug_value = [None]
40
+ number_debug_value = [None]
41
+ def save_on_path(img: Image, filename: str, format_: str = None) -> Path:
42
+ """
43
+ Save `img` in a unique temporary folder under the given `filename`
44
+ and return its absolute path.
45
+ """
46
+ # 1) unique temporary folder
47
+ tmp_dir = Path(tempfile.mkdtemp(prefix="pil_tmp_"))
48
+
49
+ # 2) full path of the future file
50
+ file_path = tmp_dir / filename
51
+
52
+ # 3) save
53
+ img.save(file_path, format=format_ or img.format)
54
+
55
+ return file_path
56
+
57
+ @spaces.GPU(duration=40)
58
+ def infer(
59
+ input_image,
60
+ prompt,
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
+ This function takes an input image and a text prompt to generate a modified version
73
+ of the image based on the provided instructions. It uses the FLUX.1 Kontext model
74
+ for contextual image editing tasks.
75
+
76
+ Args:
77
+ input_image (PIL.Image.Image): The input image to be edited. Will be converted
78
+ to RGB format if not already in that format.
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
+ Returns:
94
+ tuple: A 3-tuple containing:
95
+ - PIL.Image.Image: The generated/edited image
96
+ - int: The seed value used for generation (useful when randomize_seed=True)
97
+ - gr.update: Gradio update object to make the reuse button visible
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
+ if input_image:
112
+ input_image = input_image.convert("RGB")
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
+ image_filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f") + '.webp'
131
+ path = save_on_path(image, image_filename, format_="WEBP")
132
+ return path, gr.update(value=path, visible=True), seed, gr.update(visible=True)
133
+
134
+ def infer_example(input_image, prompt):
135
+ number=1
136
+ 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:
137
+ input_image=input_image_debug_value[0]
138
+ prompt=prompt_debug_value[0]
139
+ number=number_debug_value[0]
140
+ #input_image_debug_value[0]=prompt_debug_value[0]=prompt_debug_value[0]=None
141
+ gallery = []
142
+ try:
143
+ for i in range(number):
144
+ print("Generating #" + str(i + 1) + " image...")
145
+ seed = random.randint(0, MAX_SEED)
146
+ image, download_button, seed, _ = infer(input_image, prompt, seed, True)
147
+ gallery.append(image)
148
+ except:
149
+ print("Error")
150
+ zip_path = export_images_to_zip(gallery)
151
+ return gallery, seed, zip_path
152
+
153
+ def export_images_to_zip(gallery) -> str:
154
+ """
155
+ Bundle compiled_transformer_1 and compiled_transformer_2 into a zip file and return the file path.
156
+ """
157
+
158
+ tmp_zip = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
159
+ tmp_zip.close()
160
+
161
+ with zipfile.ZipFile(tmp_zip.name, "w", compression=zipfile.ZIP_DEFLATED) as zf:
162
+ for i in range(len(gallery)):
163
+ image_path = gallery[i]
164
+ zf.write(image_path, arcname=os.path.basename(image_path))
165
+
166
+ print(str(len(gallery)) + " images zipped")
167
+ return tmp_zip.name
168
+
169
+ css="""
170
+ #col-container {
171
+ margin: 0 auto;
172
+ max-width: 960px;
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.1 Kontext [dev]
180
+ 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)
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=1,
190
+ placeholder="Enter your prompt for editing (e.g., 'Remove glasses', 'Add a hat')",
191
+ container=False,
192
+ )
193
+ run_button = gr.Button(value="🚀 Edit", variant = "primary", scale=0)
194
+ with gr.Accordion("Advanced Settings", open=False):
195
+
196
+ seed = gr.Slider(
197
+ label="Seed",
198
+ minimum=0,
199
+ maximum=MAX_SEED,
200
+ step=1,
201
+ value=0,
202
+ )
203
+
204
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
205
+
206
+ guidance_scale = gr.Slider(
207
+ label="Guidance Scale",
208
+ minimum=1,
209
+ maximum=10,
210
+ step=0.1,
211
+ value=2.5,
212
+ )
213
+
214
+ steps = gr.Slider(
215
+ label="Steps",
216
+ minimum=1,
217
+ maximum=30,
218
+ value=30,
219
+ step=1
220
+ )
221
+
222
+ width = gr.Slider(
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, interactive=False)
242
+ download_button = gr.DownloadButton(elem_id="download_btn", visible=False)
243
+ reuse_button = gr.Button("Reuse this image", visible=False)
244
+
245
+ with gr.Row(visible=False):
246
+ download_button = gr.DownloadButton(elem_id="download_btn", interactive = True)
247
+ result_gallery = gr.Gallery(interactive = False, elem_id = "gallery1")
248
+ gr.Examples(
249
+ examples=[
250
+ ["monster.png", "Make this monster ride a skateboard on the beach"]
251
+ ],
252
+ inputs=[input_image, prompt],
253
+ outputs=[result_gallery, seed, download_button],
254
+ fn=infer_example,
255
+ run_on_click=True,
256
+ cache_examples=True,
257
+ cache_mode='lazy'
258
+ )
259
+ prompt_debug=gr.Textbox()
260
+ input_image_debug=gr.Image(type="pil")
261
+ number_debug=gr.Slider(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
+ def handle_field_debug_change(input_image_debug_data, prompt_debug_data, number_debug_data):
276
+ prompt_debug_value[0] = prompt_debug_data
277
+ input_image_debug_value[0] = input_image_debug_data
278
+ number_debug_value[0] = number_debug_data
279
+ return []
280
+
281
+ inputs_debug=[input_image_debug, prompt_debug, number_debug]
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 = infer,
290
+ inputs = [input_image, prompt, seed, randomize_seed, guidance_scale, steps, width, height],
291
+ outputs = [result, download_button, seed, reuse_button]
292
+ )
293
+ reuse_button.click(
294
+ fn = lambda image: image,
295
+ inputs = [result],
296
+ outputs = [input_image]
297
+ )
298
+
299
+ demo.launch(mcp_server=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
optimization.py CHANGED
@@ -4,35 +4,23 @@
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,34 +32,29 @@ 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)
 
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 = {
 
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]
 
 
requirements.txt CHANGED
@@ -1,8 +1,5 @@
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
 
1
+ transformers
2
+ git+https://github.com/huggingface/diffusers.git
3
+ accelerate
4
+ safetensors
5
+ sentencepiece