File size: 12,773 Bytes
64fd258
 
 
 
 
 
 
 
 
fd85691
3d490be
30a5000
64fd258
 
 
 
 
deebc0f
 
 
64fd258
 
091c199
deebc0f
091c199
110970f
 
8f2f81c
f6365e6
110970f
64fd258
b733ae9
542b971
62d5a4d
 
 
 
 
 
542b971
 
73b3534
 
 
 
 
 
64fd258
73b3534
 
64fd258
 
 
 
 
 
 
 
deebc0f
482f37f
deebc0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5f6a4a
1600510
 
8f2f81c
f6365e6
deebc0f
1600510
f6365e6
deebc0f
1600510
030cf22
 
 
77592d5
deebc0f
482f37f
030cf22
 
 
64fd258
9c74d86
64fd258
 
110970f
7d1539c
80aaa3d
 
deebc0f
80aaa3d
73b3534
80aaa3d
64fd258
 
 
110970f
73b3534
 
 
 
 
 
 
 
 
110970f
73b3534
 
 
 
 
 
 
110970f
73b3534
 
 
55fc94b
73b3534
 
 
 
 
 
7d1539c
73b3534
 
030cf22
 
 
 
 
 
 
deebc0f
1840c1c
deebc0f
 
73b3534
deebc0f
55fc94b
deebc0f
73b3534
deebc0f
030cf22
 
73b3534
55fc94b
 
73b3534
 
110970f
 
 
 
64fd258
 
 
 
 
 
 
 
 
 
 
 
 
73b3534
 
64fd258
 
3aa678b
3d490be
deebc0f
a67e235
deebc0f
64fd258
 
 
 
 
 
 
 
deebc0f
 
 
 
 
 
64fd258
 
 
 
030cf22
 
62699b1
030cf22
 
62699b1
030cf22
 
62699b1
030cf22
 
62699b1
030cf22
1600510
d4a75aa
deebc0f
 
1507f22
64fd258
 
 
 
73b3534
 
 
64fd258
 
bff13e4
 
 
 
 
 
 
 
 
 
a3ae4e4
 
 
 
 
 
110970f
a3ae4e4
7d1539c
 
 
 
 
 
 
deebc0f
1507f22
 
deebc0f
1507f22
 
 
 
 
55fc94b
1507f22
110970f
 
 
 
 
 
 
64fd258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1507f22
 
64fd258
 
 
 
 
deebc0f
 
030cf22
 
64fd258
9c74d86
80aaa3d
 
110970f
7d1539c
64fd258
 
 
73b3534
 
80aaa3d
64fd258
73b3534
64fd258
 
deebc0f
 
 
 
b733ae9
deebc0f
bff13e4
73b3534
 
 
 
 
 
 
 
64fd258
73b3534
64fd258
 
 
9c74d86
 
73b3534
9c74d86
 
 
f4356d9
07a3fc5
73b3534
07a3fc5
 
 
1600510
 
 
 
deebc0f
1600510
2b325d9
 
 
 
64fd258
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
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
243
244
245
246
247
248
249
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
import gradio as gr
import numpy as np
import random
import torch
import spaces
from PIL import Image
import os
from huggingface_hub import hf_hub_download
import torch
from diffusers import DiffusionPipeline
from huggingface_hub import hf_hub_download
#from gradio_imageslider import ImageSlider

# Constants
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
import numpy as np
MULTIMODAL_VITAL_LAYERS = [0, 1, 17, 18]
SINGLE_MODAL_VITAL_LAYERS = list(np.array([28, 53, 54, 56, 25]) - 19) 


pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev",
                        
                                          torch_dtype=torch.bfloat16)
pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
pipe.fuse_lora(lora_scale=0.125)

#pipe.enable_lora()
pipe.to(DEVICE, dtype=torch.float16)

def get_examples():
    case = [
           [Image.open("metal.png"),"dragon.png", "a dragon, in 3d melting gold metal",0.9, 0.5, 0, 5, 28, 28,  0, False,False, 2,  False, "text/image guided stylzation" ],        
           [Image.open("doll.png"),"anime.png", "anime illustration",0.9, 0.5, 0, 6, 28, 28,  0, False, False, 2,  False,"text/image guided stylzation" ],
           [Image.open("doll.png"), "raccoon.png", "raccoon, made of yarn",0.9, 0.5, 0, 4, 28, 28,  0, False, False, 2,  False, "local subject edits" ],
           [Image.open("cat.jpg"),"parrot.png", "a parrot", 0.9 ,0.5,2, 8,28, 28,0, False ,  False, 1,  False, "local subject edits"],
           [Image.open("cat.jpg"),"tiger.png", "a tiger", 0.9 ,0.5,0, 4,8, 8,789385745, False ,  False, 1,  True, "local subject edits"],
           [Image.open("metal.png"), "dragon.png","a dragon, in 3d melting gold metal",0.9, 0.5, 0, 4, 8, 8,  789385745, False,True, 2,  True , "text/image guided stylzation"],
        ]
    return case

def reset_image_input():
    return True

def reset_do_inversion(image_input):
    if image_input:
        return True
    else:
        return False
    
def resize_img(image, max_size=1024):
    width, height = image.size
    scaling_factor = min(max_size / width, max_size / height)
    new_width = int(width * scaling_factor)
    new_height = int(height * scaling_factor)
    return image.resize((new_width, new_height), Image.LANCZOS)

@torch.no_grad()
@spaces.GPU(duration=85)
def image2latent(image, latent_nudging_scalar = 1.15):
    image = pipe.image_processor.preprocess(image, height=1024, width=1024,).type(pipe.vae.dtype).to("cuda")
    latents = pipe.vae.encode(image)["latent_dist"].mean
    latents = (latents - pipe.vae.config.shift_factor) * pipe.vae.config.scaling_factor
    latents = latents * latent_nudging_scalar
    
    height = pipe.default_sample_size * pipe.vae_scale_factor
    width = pipe.default_sample_size * pipe.vae_scale_factor
    
    num_channels_latents = pipe.transformer.config.in_channels // 4
    height = 2 * (height // (pipe.vae_scale_factor * 2))
    width = 2 * (width // (pipe.vae_scale_factor * 2))

    latents = pipe._pack_latents(
        latents=latents,
        batch_size=1,
        num_channels_latents=num_channels_latents,
        height=height,
        width=width
    )

    return latents

def check_hyper_flux_lora(enable_hyper_flux):
    if enable_hyper_flux:
        pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"), lora_scale=0.125)
        pipe.fuse_lora(lora_scale=0.125)
        return 8, 8
    else:
        pipe.unfuse_lora()
        return 28, 28

def convert_string_to_list(s):
    return [int(x) for x in s.split(',') if x]

@spaces.GPU(duration=150)
def invert_and_edit(image,
                    source_prompt,
                    edit_prompt,
                    multimodal_layers,
                    single_layers,
                    num_inversion_steps,
                    num_inference_steps,
                    seed,
                    randomize_seed,
                    latent_nudging_scalar,
                    guidance_scale,
                    width = 1024,
                    height = 1024,
                    inverted_latent_list = None,
                    do_inversion = True,
                    image_input = False,
                    
                   ):
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    if image_input and (image is not None):
        if do_inversion:
            inverted_latent_list = pipe(
                source_prompt,
                height=1024,
                width=1024,
                guidance_scale=1,
                output_type="pil",
                num_inference_steps=num_inversion_steps,
                max_sequence_length=512,
                latents=image2latent(image, latent_nudging_scalar),
                invert_image=True
            )
            do_inversion = False
            
        else:
            # move to gpu because of zero and gr.states
            inverted_latent_list = [tensor.to(DEVICE) for tensor in inverted_latent_list]
        num_inference_steps = num_inversion_steps 
        latents = inverted_latent_list[-1].tile(2, 1, 1)
        guidance_scale = [1,3]
        image_input = True
    else:
        latents = torch.randn(
            (4096, 64), 
            generator=torch.Generator(0).manual_seed(0), 
            dtype=torch.float16,
    device=DEVICE,
        ).tile(2, 1, 1)
        guidance_scale = guidance_scale
        image_input = False
        

    try:
        multimodal_layers = convert_string_to_list(multimodal_layers)
        single_layers = convert_string_to_list(single_layers)
    except:
        multimodal_layers = MULTIMODAL_VITAL_LAYERS
        single_layers = SINGLE_MODAL_VITAL_LAYERS
    output = pipe(
            [source_prompt, edit_prompt],
            height=1024,
            width=1024,
            guidance_scale=guidance_scale,
            output_type="pil",
            num_inference_steps=num_inference_steps,
            max_sequence_length=512,
            latents=latents,
            inverted_latent_list=inverted_latent_list,
            mm_copy_blocks=multimodal_layers,
            single_copy_blocks=single_layers,
        ).images

    # move back to cpu because of zero and gr.states
    if inverted_latent_list is not None:
        inverted_latent_list = [tensor.cpu() for tensor in inverted_latent_list]
    if image is None:
        image = output[0]
    
    return image, output[1], inverted_latent_list, do_inversion, image_input, seed

# UI CSS
css = """
#col-container {
    margin: 0 auto;
    max-width: 960px;
}
"""

# Create the Gradio interface
with gr.Blocks(css=css) as demo:

    inverted_latents = gr.State()
    do_inversion = gr.State(False)
    image_input = gr.State(False)
    
    with gr.Column(elem_id="col-container"):
        gr.Markdown(f"""# Stable Flow 🌊🖌️
### Edit real images with FLUX.1 [dev]
following the algorithm proposed in [*Stable Flow: Vital Layers for Training-Free Image Editing* by Avrahami et al.](https://arxiv.org/pdf/2411.14430)

[[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[project page](https://omriavrahami.com/stable-flow/) [[arxiv](https://arxiv.org/pdf/2411.14430)]
        """)
        
        with gr.Row():
            with gr.Column():
                input_image = gr.Image(
                    label="Input Image",
                    type="pil"
                )
                source_prompt = gr.Text(
                    label="Source Prompt",
                    max_lines=1,
                    placeholder="describe the edited output",
                )
                edit_prompt = gr.Text(
                    label="Edit Prompt",
                    max_lines=1,
                    placeholder="describe the edited output",
                )
                with gr.Row():
                    multimodal_layers = gr.Text(
                        info = "MMDiT attention layers used for editing",
                        label="vital multimodal layers",
                        max_lines=1,
                        value="0, 1, 17, 18",
                    )
                    single_layers = gr.Text(
                        info = "DiT attention layers used editing",
                        label="vital single layers",
                        max_lines=1,
                        value="9, 34, 35, 37, 6",
                    )
                with gr.Row():
                    enable_hyper_flux = gr.Checkbox(label="8-step LoRA", value=False, info="may reduce edit quality", visible=False)
                    
                    
                
                run_button = gr.Button("Edit", variant="primary")
            
            with gr.Column():
                result = gr.Image(label="Result")
            # with gr.Column():
            #     with gr.Group():
            #         result = ImageSlider(position=0.5)
        
        with gr.Accordion("Advanced Settings", open=False):
            
            seed = gr.Slider(
                label="Seed",
                minimum=0,
                maximum=MAX_SEED,
                step=1,
                value=42,
            )
            
            randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
            with gr.Row():
                num_inference_steps = gr.Slider(
                            label="num inference steps",
                            minimum=1,
                            maximum=50,
                            step=1,
                            value=8,
                        )
                guidance_scale = gr.Slider(
                            label="guidance scale",
                            minimum=1,
                            maximum=25,
                            step=1,
                            value=3.5,
                        )
                

            with gr.Row():
                
                num_inversion_steps = gr.Slider(
                        label="num inversion steps",
                        minimum=1,
                        maximum=50,
                        step=1,
                        value=25,
                    )
                latent_nudging_scalar= gr.Slider(
                        label="latent nudging scalar",
                        minimum=1,
                        maximum=5,
                        step=0.01,
                        value=1.15,
                    )
            
            with gr.Row():
                width = gr.Slider(
                    label="Width",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=1024,
                )
                
                height = gr.Slider(
                    label="Height",
                    minimum=256,
                    maximum=MAX_IMAGE_SIZE,
                    step=32,
                    value=1024,
                )
            
                
    
    run_button.click(
        fn=invert_and_edit,
        inputs=[
            input_image,
            source_prompt,
            edit_prompt,
            multimodal_layers,
            single_layers,
            num_inversion_steps,
            num_inference_steps,
            seed,
            randomize_seed,
            latent_nudging_scalar,
            guidance_scale,
            width,
            height,
            inverted_latents,
            do_inversion,
            image_input
            
        ],
        outputs=[input_image, result, inverted_latents, do_inversion, image_input, seed],
    )

    # gr.Examples(
    #             examples=get_examples(),
    #             inputs=[input_image,result, prompt, num_inversion_steps, num_inference_steps, seed, randomize_seed, enable_hyper_flux ],
    #             outputs=[result],
               
    #         )

    input_image.input(fn=reset_image_input,
                     outputs=[image_input]).then(
        fn=reset_do_inversion,
        inputs = [image_input],
        outputs=[do_inversion]
    )
    
    source_prompt.change(
        fn=reset_do_inversion,
        inputs = [image_input],
        outputs=[do_inversion]
    )

    num_inversion_steps.change(
        fn=reset_do_inversion,
        inputs = [image_input],
        outputs=[do_inversion]
    )

    seed.change(
        fn=reset_do_inversion,
        inputs = [image_input],
        outputs=[do_inversion]
    )


    enable_hyper_flux.change(
        fn=check_hyper_flux_lora,
        inputs=[enable_hyper_flux],
        outputs=[num_inversion_steps, num_inference_steps]
    )
    

    

if __name__ == "__main__":
    demo.launch()