mpatel57 commited on
Commit
fb618bb
·
verified ·
1 Parent(s): ab50172

Upload 42 files

Browse files
Files changed (42) hide show
  1. app.py +359 -0
  2. assets/dog.webp +0 -0
  3. assets/vulcano.jpg +0 -0
  4. assets/vulcano_mask.webp +0 -0
  5. pipeline_rf_inversionfree_edit.py +699 -0
  6. requirements.txt +11 -0
  7. saved_results/20241129_041830/input.png +0 -0
  8. saved_results/20241129_041830/mask.png +0 -0
  9. saved_results/20241129_041830/output.png +0 -0
  10. saved_results/20241129_041830/parameters.json +14 -0
  11. saved_results/20241129_154837/input.png +0 -0
  12. saved_results/20241129_154837/mask.png +0 -0
  13. saved_results/20241129_154837/output.png +0 -0
  14. saved_results/20241129_154837/parameters.json +13 -0
  15. saved_results/20241129_160150/input.png +0 -0
  16. saved_results/20241129_160150/mask.png +0 -0
  17. saved_results/20241129_160150/output.png +0 -0
  18. saved_results/20241129_160150/parameters.json +13 -0
  19. saved_results/20241129_160359/input.png +0 -0
  20. saved_results/20241129_160359/mask.png +0 -0
  21. saved_results/20241129_160359/output.png +0 -0
  22. saved_results/20241129_160359/parameters.json +13 -0
  23. saved_results/20241129_160439/input.png +0 -0
  24. saved_results/20241129_160439/mask.png +0 -0
  25. saved_results/20241129_160439/output.png +0 -0
  26. saved_results/20241129_160439/parameters.json +13 -0
  27. saved_results/20241129_161118/input.png +0 -0
  28. saved_results/20241129_161118/mask.png +0 -0
  29. saved_results/20241129_161118/output.png +0 -0
  30. saved_results/20241129_161118/parameters.json +13 -0
  31. saved_results/20241129_161547/input.png +0 -0
  32. saved_results/20241129_161547/mask.png +0 -0
  33. saved_results/20241129_161547/output.png +0 -0
  34. saved_results/20241129_161547/parameters.json +13 -0
  35. saved_results/20241129_161602/input.png +0 -0
  36. saved_results/20241129_161602/mask.png +0 -0
  37. saved_results/20241129_161602/output.png +0 -0
  38. saved_results/20241129_161602/parameters.json +13 -0
  39. saved_results/20241129_195331/input.png +0 -0
  40. saved_results/20241129_195331/mask.png +0 -0
  41. saved_results/20241129_195331/output.png +0 -0
  42. saved_results/20241129_195331/parameters.json +12 -0
app.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import torch
4
+ from diffusers import StableDiffusionInpaintPipeline, StableDiffusionImg2ImgPipeline
5
+ from PIL import Image
6
+ import random
7
+ import numpy as np
8
+ import torch
9
+ import os
10
+ import json
11
+ from datetime import datetime
12
+
13
+ from pipeline_rf_inversionfree_edit import RectifiedFlowPipeline as RectifiedFlowEditPipeline
14
+
15
+
16
+ pipe_edit = RectifiedFlowEditPipeline.from_pretrained("XCLIU/2_rectified_flow_from_sd_1_5", torch_dtype=torch.float32)
17
+ pipe_edit.to("cuda")
18
+
19
+ # Function to process the image
20
+ @spaces.GPU(duration=10)
21
+ def process_image(
22
+ image_layers, prompt, edit_prompt, seed, randomize_seed, num_inference_steps,
23
+ max_steps, learning_rate, max_source_steps, optimization_steps, true_cfg, mask_input
24
+ ):
25
+ image_with_mask = {
26
+ "image": image_layers["background"],
27
+ "mask": image_layers["layers"][0] if mask_input is None else mask_input
28
+ }
29
+
30
+ # Set seed
31
+ if randomize_seed or seed is None:
32
+ seed = random.randint(0, 2**32 - 1)
33
+ generator = torch.Generator("cuda").manual_seed(int(seed))
34
+
35
+ # Unpack image and mask
36
+ if image_with_mask is None:
37
+ return None, f"❌ Please upload an image and create a mask."
38
+ image = image_with_mask["image"]
39
+ mask = image_with_mask["mask"]
40
+
41
+ if image is None or mask is None:
42
+ return None, f"❌ Please ensure both image and mask are provided."
43
+
44
+ # Convert images to RGB
45
+ image = image.convert("RGB")
46
+ mask = mask.split()[-1] # Convert mask to grayscale
47
+
48
+ if not edit_prompt:
49
+ return None, f"❌ Please provide a prompt for editing."
50
+ if not prompt:
51
+ prompt = ""
52
+ # Resize the mask to match the image
53
+ # mask = mask.resize(image.size)
54
+ with torch.autocast("cuda"):
55
+ # Placeholder for using advanced parameters in the future
56
+ # Adjust parameters according to advanced settings if applicable
57
+ result = pipe_edit(
58
+ prompt=prompt,
59
+ edit_prompt=edit_prompt,
60
+ input_image=image.resize((512, 512)),
61
+ mask_image=mask.resize((512, 512)),
62
+ negative_prompt="",
63
+ num_inference_steps=num_inference_steps,
64
+ guidance_scale=true_cfg,
65
+ generator=generator,
66
+ # save_masked_image=False,
67
+ # output_path="",
68
+ learning_rate=learning_rate,
69
+ max_steps=max_steps,
70
+ optimization_steps=optimization_steps,
71
+ full_source_steps=max_source_steps,
72
+ ).images[0]
73
+ return result, f"✅ Editing completed with seed {seed}."
74
+
75
+ # Design the Gradio interface
76
+ with gr.Blocks() as demo:
77
+ gr.Markdown(
78
+ """
79
+ <style>
80
+ body {background-color: #f5f5f5; color: #333333;}
81
+ h1 {text-align: center; font-family: 'Helvetica', sans-serif; margin-bottom: 10px;}
82
+ h2 {text-align: center; color: #666666; font-weight: normal; margin-bottom: 30px;}
83
+ .gradio-container {max-width: 800px; margin: auto;}
84
+ .footer {text-align: center; margin-top: 20px; color: #999999; font-size: 12px;}
85
+ </style>
86
+ """
87
+ )
88
+ gr.Markdown("<h1>🍲 FlowChef 🍲</h1>")
89
+ gr.Markdown("<h2>Inversion/Gradient/Training-free Steering of <u>InstaFlow (SDv1.5) for Image Editing</u></h2>")
90
+ gr.Markdown("<h3><p><a href='https://flowchef.github.io/'>Project Page</a> | <a href='#'>Paper</a></p> (Steering Rectified Flow Models in the Vector Field for Controlled Image Generation)</h3>")
91
+ gr.Markdown("<h3>💡 We recommend going through our <a href='#'>tutorial introduction</a> before getting started!</h3>")
92
+ gr.Markdown("<h3>⚡ For better performance, check out our demo on <a href='https://huggingface.co/spaces/FlowChef/FlowChef-Flux1-dev'>Flux</a>!</h3>")
93
+
94
+ # Store current state
95
+ current_input_image = None
96
+ current_mask = None
97
+ current_output_image = None
98
+ current_params = {}
99
+
100
+ # Images at the top
101
+ with gr.Row():
102
+ with gr.Column():
103
+ image_input = gr.ImageMask(
104
+ # source="upload",
105
+ # tool="sketch",
106
+ type="pil",
107
+ label="Input Image and Mask",
108
+ image_mode="RGBA",
109
+ height=512,
110
+ width=512,
111
+ )
112
+ with gr.Column():
113
+ output_image = gr.Image(label="Output Image")
114
+
115
+ # All options below
116
+ with gr.Column():
117
+ prompt = gr.Textbox(
118
+ label="Prompt",
119
+ placeholder="Describe what should appear in the masked area..."
120
+ )
121
+ edit_prompt = gr.Textbox(
122
+ label="Editing Prompt",
123
+ placeholder="Describe how you want to edit the image..."
124
+ )
125
+ with gr.Row():
126
+ seed = gr.Number(label="Seed (Optional)", value=None)
127
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
128
+ num_inference_steps = gr.Slider(
129
+ label="Inference Steps", minimum=10, maximum=100, value=50
130
+ )
131
+ # Advanced settings in an accordion
132
+ with gr.Accordion("Advanced Settings", open=False):
133
+ max_steps = gr.Slider(label="Max Steps", minimum=10, maximum=100, value=50)
134
+ learning_rate = gr.Slider(label="Learning Rate", minimum=0.1, maximum=1.0, value=0.5)
135
+ true_cfg = gr.Slider(label="Guidance Scale", minimum=1, maximum=20, value=2)
136
+ max_source_steps = gr.Slider(label="Max Source Steps", minimum=1, maximum=200, value=40)
137
+ optimization_steps = gr.Slider(label="Optimization Steps", minimum=1, maximum=10, value=1)
138
+ mask_input = gr.Image(
139
+ type="pil",
140
+ label="Optional Mask",
141
+ image_mode="RGBA",
142
+ )
143
+ with gr.Row():
144
+ run_button = gr.Button("Run", variant="primary")
145
+ # save_button = gr.Button("Save Data", variant="secondary")
146
+
147
+ # def update_visibility(selected_mode):
148
+ # if selected_mode == "Inpainting":
149
+ # return gr.update(visible=True), gr.update(visible=False)
150
+ # else:
151
+ # return gr.update(visible=True), gr.update(visible=True)
152
+
153
+ # mode.change(
154
+ # update_visibility,
155
+ # inputs=mode,
156
+ # outputs=[prompt, edit_prompt],
157
+ # )
158
+
159
+ def run_and_update_status(
160
+ image_with_mask, prompt, edit_prompt, seed, randomize_seed, num_inference_steps,
161
+ max_steps, learning_rate, max_source_steps, optimization_steps, true_cfg, mask_input
162
+ ):
163
+ result_image, result_status = process_image(
164
+ image_with_mask, prompt, edit_prompt, seed, randomize_seed, num_inference_steps,
165
+ max_steps, learning_rate, max_source_steps, optimization_steps, true_cfg, mask_input
166
+ )
167
+
168
+ # Store current state
169
+ global current_input_image, current_mask, current_output_image, current_params
170
+
171
+ current_input_image = image_with_mask["background"] if image_with_mask else None
172
+ current_mask = mask_input if mask_input is not None else (image_with_mask["layers"][0] if image_with_mask else None)
173
+ current_output_image = result_image
174
+ current_params = {
175
+ "prompt": prompt,
176
+ "edit_prompt": edit_prompt,
177
+ "seed": seed,
178
+ "randomize_seed": randomize_seed,
179
+ "num_inference_steps": num_inference_steps,
180
+ "max_steps": max_steps,
181
+ "learning_rate": learning_rate,
182
+ "max_source_steps": max_source_steps,
183
+ "optimization_steps": optimization_steps,
184
+ "true_cfg": true_cfg,
185
+ }
186
+
187
+ return result_image
188
+
189
+ def save_data():
190
+ if not os.path.exists("saved_results"):
191
+ os.makedirs("saved_results")
192
+
193
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
194
+ save_dir = os.path.join("saved_results", timestamp)
195
+ os.makedirs(save_dir)
196
+
197
+ # Save images
198
+ if current_input_image:
199
+ current_input_image.save(os.path.join(save_dir, "input.png"))
200
+ if current_mask:
201
+ current_mask.save(os.path.join(save_dir, "mask.png"))
202
+ if current_output_image:
203
+ current_output_image.save(os.path.join(save_dir, "output.png"))
204
+
205
+ # Save parameters
206
+ with open(os.path.join(save_dir, "parameters.json"), "w") as f:
207
+ json.dump(current_params, f, indent=4)
208
+
209
+ return f"✅ Data saved in {save_dir}"
210
+
211
+ run_button.click(
212
+ fn=run_and_update_status,
213
+ inputs=[
214
+ image_input,
215
+ prompt,
216
+ edit_prompt,
217
+ seed,
218
+ randomize_seed,
219
+ num_inference_steps,
220
+ max_steps,
221
+ learning_rate,
222
+ max_source_steps,
223
+ optimization_steps,
224
+ true_cfg,
225
+ mask_input
226
+ ],
227
+ outputs=output_image,
228
+ )
229
+
230
+ # save_button.click(fn=save_data)
231
+
232
+ gr.Markdown(
233
+ "<div class='footer'>Developed with ❤️ using InstaFlow (Stable Diffusion v1.5) and Gradio by <a href='https://maitreyapatel.com'>Maitreya Patel</a></div>"
234
+ )
235
+
236
+ def load_example_image_with_mask(image_path):
237
+ # Load the image
238
+ image = Image.open(image_path)
239
+ # Create an empty mask of the same size
240
+ mask = Image.new('L', image.size, 0)
241
+ return {"background": image, "layers": [mask], "composite": image}
242
+
243
+ examples_dir = "assets"
244
+ volcano_dict = load_example_image_with_mask(os.path.join(examples_dir, "vulcano.jpg"))
245
+ dog_dict = load_example_image_with_mask(os.path.join(examples_dir, "dog.webp"))
246
+
247
+ gr.Examples(
248
+ examples=[
249
+ [
250
+ "./saved_results/20241129_154837/input.png", # image with mask
251
+ "./saved_results/20241129_154837/mask.png",
252
+ "./saved_results/20241129_154837/output.png",
253
+ "a cat", # prompt
254
+ "a tiger", # edit_prompt
255
+ 0, # seed
256
+ True, # randomize_seed
257
+ 50, # num_inference_steps
258
+ 50, # max_steps
259
+ 0.5, # learning_rate
260
+ 20, # max_source_steps
261
+ 5, # optimization_steps
262
+ 2, # true_cfg
263
+ ],
264
+ [
265
+ "./saved_results/20241129_195331/input.png", # image with mask
266
+ "./saved_results/20241129_195331/mask.png",
267
+ "./saved_results/20241129_195331/output.png",
268
+ "a cat", # prompt
269
+ "a silver sculpture of cat", # edit_prompt
270
+ 0, # seed
271
+ True, # randomize_seed
272
+ 50, # num_inference_steps
273
+ 50, # max_steps
274
+ 0.5, # learning_rate
275
+ 20, # max_source_steps
276
+ 5, # optimization_steps
277
+ 2, # true_cfg
278
+ ],
279
+ [
280
+ "./saved_results/20241129_160439/input.png", # image with mask
281
+ "./saved_results/20241129_160439/mask.png",
282
+ "./saved_results/20241129_160439/output.png",
283
+ "a dog", # prompt
284
+ "a lion", # edit_prompt
285
+ 0, # seed
286
+ True, # randomize_seed
287
+ 50, # num_inference_steps
288
+ 20, # max_steps
289
+ 0.5, # learning_rate
290
+ 20, # max_source_steps
291
+ 5, # optimization_steps
292
+ 4, # true_cfg
293
+ ],
294
+ [
295
+ "./saved_results/20241129_161118/input.png", # image with mask
296
+ "./saved_results/20241129_161118/mask.png",
297
+ "./saved_results/20241129_161118/output.png",
298
+ "two birds sitting on a branch", # prompt
299
+ "two origami birds sitting on a branch", # edit_prompt
300
+ 0, # seed
301
+ True, # randomize_seed
302
+ 50, # num_inference_steps
303
+ 50, # max_steps
304
+ 0.5, # learning_rate
305
+ 30, # max_source_steps
306
+ 2, # optimization_steps
307
+ 2, # true_cfg
308
+ ],
309
+ [
310
+ "./saved_results/20241129_161602/input.png", # image with mask
311
+ "./saved_results/20241129_161602/mask.png",
312
+ "./saved_results/20241129_161602/output.png",
313
+ "a woman with long hair sitting in the sand at sunset", # prompt
314
+ "a woman with short hair sitting in the sand at sunset", # edit_prompt
315
+ 0, # seed
316
+ True, # randomize_seed
317
+ 50, # num_inference_steps
318
+ 30, # max_steps
319
+ 0.5, # learning_rate
320
+ 20, # max_source_steps
321
+ 2, # optimization_steps
322
+ 2, # true_cfg
323
+ ],
324
+ [
325
+ "./saved_results/20241129_160150/input.png", # image with mask
326
+ "./saved_results/20241129_160150/mask.png",
327
+ "./saved_results/20241129_160150/output.png",
328
+ "A cute rabbit with big eyes", # prompt
329
+ "A cute pig with big eyes", # edit_prompt
330
+ 0, # seed
331
+ True, # randomize_seed
332
+ 50, # num_inference_steps
333
+ 40, # max_steps
334
+ 0.5, # learning_rate
335
+ 20, # max_source_steps
336
+ 5, # optimization_steps
337
+ 4, # true_cfg
338
+ ],
339
+ ],
340
+ inputs=[
341
+ image_input,
342
+ mask_input,
343
+ output_image,
344
+ prompt,
345
+ edit_prompt,
346
+ seed,
347
+ randomize_seed,
348
+ num_inference_steps,
349
+ max_steps,
350
+ learning_rate,
351
+ max_source_steps,
352
+ optimization_steps,
353
+ true_cfg,
354
+ ],
355
+ # outputs=[output_image],
356
+ # fn=run_and_update_status,
357
+ # cache_examples=True,
358
+ )
359
+ demo.launch()
assets/dog.webp ADDED
assets/vulcano.jpg ADDED
assets/vulcano_mask.webp ADDED
pipeline_rf_inversionfree_edit.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers.configuration_utils import FrozenDict
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
25
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
26
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
27
+ from diffusers.schedulers import KarrasDiffusionSchedulers
28
+ from diffusers.utils import (
29
+ deprecate,
30
+ logging,
31
+ replace_example_docstring,
32
+ )
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
35
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
36
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
37
+ import kornia.augmentation as K
38
+
39
+ import os
40
+ import torch
41
+ import cv2
42
+
43
+ import numpy as np
44
+ from torchvision import transforms as TF
45
+ from tqdm import tqdm
46
+
47
+ import sys
48
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
49
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
50
+
51
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
52
+
53
+ def retrieve_latents(
54
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
55
+ ):
56
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
57
+ return encoder_output.latent_dist.sample(generator)
58
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
59
+ return encoder_output.latent_dist.mode()
60
+ elif hasattr(encoder_output, "latents"):
61
+ return encoder_output.latents
62
+ else:
63
+ raise AttributeError("Could not access latents of provided encoder_output")
64
+
65
+
66
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
67
+ """
68
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
69
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
70
+ """
71
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
72
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
73
+ # rescale the results from guidance (fixes overexposure)
74
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
75
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
76
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
77
+ return noise_cfg
78
+
79
+
80
+ class RectifiedFlowPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin):
81
+ r"""
82
+ Pipeline for text-to-image generation using Rectified Flow and Euler discretization.
83
+ This customized pipeline is based on StableDiffusionPipeline from the official Diffusers library (0.21.4)
84
+
85
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
86
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
87
+
88
+ The pipeline also inherits the following loading methods:
89
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
90
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
91
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
92
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
93
+
94
+ Args:
95
+ vae ([`AutoencoderKL`]):
96
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
97
+ text_encoder ([`~transformers.CLIPTextModel`]):
98
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
99
+ tokenizer ([`~transformers.CLIPTokenizer`]):
100
+ A `CLIPTokenizer` to tokenize text.
101
+ unet ([`UNet2DConditionModel`]):
102
+ A `UNet2DConditionModel` to denoise the encoded image latents.
103
+ scheduler ([`SchedulerMixin`]):
104
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
105
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
106
+ safety_checker ([`StableDiffusionSafetyChecker`]):
107
+ Classification module that estimates whether generated images could be considered offensive or harmful.
108
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
109
+ about a model's potential harms.
110
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
111
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
112
+ """
113
+ model_cpu_offload_seq = "text_encoder->unet->vae"
114
+ _optional_components = ["safety_checker", "feature_extractor"]
115
+ _exclude_from_cpu_offload = ["safety_checker"]
116
+
117
+ def __init__(
118
+ self,
119
+ vae: AutoencoderKL,
120
+ text_encoder: CLIPTextModel,
121
+ tokenizer: CLIPTokenizer,
122
+ unet: UNet2DConditionModel,
123
+ scheduler: KarrasDiffusionSchedulers,
124
+ safety_checker: StableDiffusionSafetyChecker,
125
+ feature_extractor: CLIPImageProcessor,
126
+ requires_safety_checker: bool = True,
127
+ ):
128
+ super().__init__()
129
+
130
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
131
+ deprecation_message = (
132
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
133
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
134
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
135
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
136
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
137
+ " file"
138
+ )
139
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
140
+ new_config = dict(scheduler.config)
141
+ new_config["steps_offset"] = 1
142
+ scheduler._internal_dict = FrozenDict(new_config)
143
+
144
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
145
+ deprecation_message = (
146
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
147
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
148
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
149
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
150
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
151
+ )
152
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
153
+ new_config = dict(scheduler.config)
154
+ new_config["clip_sample"] = False
155
+ scheduler._internal_dict = FrozenDict(new_config)
156
+
157
+ if safety_checker is None and requires_safety_checker:
158
+ logger.warning(
159
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
160
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
161
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
162
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
163
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
164
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
165
+ )
166
+
167
+ if safety_checker is not None and feature_extractor is None:
168
+ raise ValueError(
169
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
170
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
171
+ )
172
+
173
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
174
+ version.parse(unet.config._diffusers_version).base_version
175
+ ) < version.parse("0.9.0.dev0")
176
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
177
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
178
+ deprecation_message = (
179
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
180
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
181
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
182
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
183
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
184
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
185
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
186
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
187
+ " the `unet/config.json` file"
188
+ )
189
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
190
+ new_config = dict(unet.config)
191
+ new_config["sample_size"] = 64
192
+ unet._internal_dict = FrozenDict(new_config)
193
+
194
+ self.register_modules(
195
+ vae=vae,
196
+ text_encoder=text_encoder,
197
+ tokenizer=tokenizer,
198
+ unet=unet,
199
+ scheduler=scheduler,
200
+ safety_checker=safety_checker,
201
+ feature_extractor=feature_extractor,
202
+ )
203
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
204
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
205
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
206
+
207
+ def enable_vae_slicing(self):
208
+ r"""
209
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
210
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
211
+ """
212
+ self.vae.enable_slicing()
213
+
214
+ def disable_vae_slicing(self):
215
+ r"""
216
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
217
+ computing decoding in one step.
218
+ """
219
+ self.vae.disable_slicing()
220
+
221
+ def enable_vae_tiling(self):
222
+ r"""
223
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
224
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
225
+ processing larger images.
226
+ """
227
+ self.vae.enable_tiling()
228
+
229
+ def disable_vae_tiling(self):
230
+ r"""
231
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
232
+ computing decoding in one step.
233
+ """
234
+ self.vae.disable_tiling()
235
+
236
+ def _encode_prompt(
237
+ self,
238
+ prompt,
239
+ device,
240
+ num_images_per_prompt,
241
+ do_classifier_free_guidance,
242
+ negative_prompt=None,
243
+ prompt_embeds: Optional[torch.FloatTensor] = None,
244
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
245
+ lora_scale: Optional[float] = None,
246
+ ):
247
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
248
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
249
+
250
+ prompt_embeds_tuple = self.encode_prompt(
251
+ prompt=prompt,
252
+ device=device,
253
+ num_images_per_prompt=num_images_per_prompt,
254
+ do_classifier_free_guidance=do_classifier_free_guidance,
255
+ negative_prompt=negative_prompt,
256
+ prompt_embeds=prompt_embeds,
257
+ negative_prompt_embeds=negative_prompt_embeds,
258
+ lora_scale=lora_scale,
259
+ )
260
+
261
+ # concatenate for backwards comp
262
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
263
+
264
+ return prompt_embeds
265
+
266
+ def encode_prompt(
267
+ self,
268
+ prompt,
269
+ device,
270
+ num_images_per_prompt,
271
+ do_classifier_free_guidance,
272
+ negative_prompt=None,
273
+ prompt_embeds: Optional[torch.FloatTensor] = None,
274
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
275
+ lora_scale: Optional[float] = None,
276
+ ):
277
+ r"""
278
+ Encodes the prompt into text encoder hidden states.
279
+
280
+ Args:
281
+ prompt (`str` or `List[str]`, *optional*):
282
+ prompt to be encoded
283
+ device: (`torch.device`):
284
+ torch device
285
+ num_images_per_prompt (`int`):
286
+ number of images that should be generated per prompt
287
+ do_classifier_free_guidance (`bool`):
288
+ whether to use classifier free guidance or not
289
+ negative_prompt (`str` or `List[str]`, *optional*):
290
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
291
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
292
+ less than `1`).
293
+ prompt_embeds (`torch.FloatTensor`, *optional*):
294
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
295
+ provided, text embeddings will be generated from `prompt` input argument.
296
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
297
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
298
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
299
+ argument.
300
+ lora_scale (`float`, *optional*):
301
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
302
+ """
303
+ # set lora scale so that monkey patched LoRA
304
+ # function of text encoder can correctly access it
305
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
306
+ self._lora_scale = lora_scale
307
+
308
+ # dynamically adjust the LoRA scale
309
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
310
+
311
+ if prompt is not None and isinstance(prompt, str):
312
+ batch_size = 1
313
+ elif prompt is not None and isinstance(prompt, list):
314
+ batch_size = len(prompt)
315
+ else:
316
+ batch_size = prompt_embeds.shape[0]
317
+
318
+ if prompt_embeds is None:
319
+ # textual inversion: procecss multi-vector tokens if necessary
320
+ if isinstance(self, TextualInversionLoaderMixin):
321
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
322
+
323
+ text_inputs = self.tokenizer(
324
+ prompt,
325
+ padding="max_length",
326
+ max_length=self.tokenizer.model_max_length,
327
+ truncation=True,
328
+ return_tensors="pt",
329
+ )
330
+ text_input_ids = text_inputs.input_ids
331
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
332
+
333
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
334
+ text_input_ids, untruncated_ids
335
+ ):
336
+ removed_text = self.tokenizer.batch_decode(
337
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
338
+ )
339
+ logger.warning(
340
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
341
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
342
+ )
343
+
344
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
345
+ attention_mask = text_inputs.attention_mask.to(device)
346
+ else:
347
+ attention_mask = None
348
+
349
+ prompt_embeds = self.text_encoder(
350
+ text_input_ids.to(device),
351
+ attention_mask=attention_mask,
352
+ )
353
+ prompt_embeds = prompt_embeds[0]
354
+
355
+ if self.text_encoder is not None:
356
+ prompt_embeds_dtype = self.text_encoder.dtype
357
+ elif self.unet is not None:
358
+ prompt_embeds_dtype = self.unet.dtype
359
+ else:
360
+ prompt_embeds_dtype = prompt_embeds.dtype
361
+
362
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
363
+
364
+ bs_embed, seq_len, _ = prompt_embeds.shape
365
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
366
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
367
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
368
+
369
+ # get unconditional embeddings for classifier free guidance
370
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
371
+ uncond_tokens: List[str]
372
+ if negative_prompt is None:
373
+ uncond_tokens = [""] * batch_size
374
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
375
+ raise TypeError(
376
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
377
+ f" {type(prompt)}."
378
+ )
379
+ elif isinstance(negative_prompt, str):
380
+ uncond_tokens = [negative_prompt]
381
+ elif batch_size != len(negative_prompt):
382
+ raise ValueError(
383
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
384
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
385
+ " the batch size of `prompt`."
386
+ )
387
+ else:
388
+ uncond_tokens = negative_prompt
389
+
390
+ # textual inversion: procecss multi-vector tokens if necessary
391
+ if isinstance(self, TextualInversionLoaderMixin):
392
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
393
+
394
+ max_length = prompt_embeds.shape[1]
395
+ uncond_input = self.tokenizer(
396
+ uncond_tokens,
397
+ padding="max_length",
398
+ max_length=max_length,
399
+ truncation=True,
400
+ return_tensors="pt",
401
+ )
402
+
403
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
404
+ attention_mask = uncond_input.attention_mask.to(device)
405
+ else:
406
+ attention_mask = None
407
+
408
+ negative_prompt_embeds = self.text_encoder(
409
+ uncond_input.input_ids.to(device),
410
+ attention_mask=attention_mask,
411
+ )
412
+ negative_prompt_embeds = negative_prompt_embeds[0]
413
+
414
+ if do_classifier_free_guidance:
415
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
416
+ seq_len = negative_prompt_embeds.shape[1]
417
+
418
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
419
+
420
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
421
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
422
+
423
+ return prompt_embeds, negative_prompt_embeds
424
+
425
+ def run_safety_checker(self, image, device, dtype):
426
+ if self.safety_checker is None:
427
+ has_nsfw_concept = None
428
+ else:
429
+ if torch.is_tensor(image):
430
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
431
+ else:
432
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
433
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
434
+ image, has_nsfw_concept = self.safety_checker(
435
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
436
+ )
437
+ return image, has_nsfw_concept
438
+
439
+ def decode_latents(self, latents):
440
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
441
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
442
+
443
+ latents = 1 / self.vae.config.scaling_factor * latents
444
+ image = self.vae.decode(latents, return_dict=False)[0]
445
+ image = (image / 2 + 0.5).clamp(0, 1)
446
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
447
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
448
+ return image
449
+
450
+ def prepare_extra_step_kwargs(self, generator, eta):
451
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
452
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
453
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
454
+ # and should be between [0, 1]
455
+
456
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
457
+ extra_step_kwargs = {}
458
+ if accepts_eta:
459
+ extra_step_kwargs["eta"] = eta
460
+
461
+ # check if the scheduler accepts generator
462
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
463
+ if accepts_generator:
464
+ extra_step_kwargs["generator"] = generator
465
+ return extra_step_kwargs
466
+
467
+ def check_inputs(
468
+ self,
469
+ prompt,
470
+ height,
471
+ width,
472
+ callback_steps,
473
+ negative_prompt=None,
474
+ prompt_embeds=None,
475
+ negative_prompt_embeds=None,
476
+ ):
477
+ if height % 8 != 0 or width % 8 != 0:
478
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
479
+
480
+ if (callback_steps is None) or (
481
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
482
+ ):
483
+ raise ValueError(
484
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
485
+ f" {type(callback_steps)}."
486
+ )
487
+
488
+ if prompt is not None and prompt_embeds is not None:
489
+ raise ValueError(
490
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
491
+ " only forward one of the two."
492
+ )
493
+ elif prompt is None and prompt_embeds is None:
494
+ raise ValueError(
495
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
496
+ )
497
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
498
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
499
+
500
+ if negative_prompt is not None and negative_prompt_embeds is not None:
501
+ raise ValueError(
502
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
503
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
504
+ )
505
+
506
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
507
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
508
+ raise ValueError(
509
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
510
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
511
+ f" {negative_prompt_embeds.shape}."
512
+ )
513
+
514
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
515
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
516
+ if isinstance(generator, list) and len(generator) != batch_size:
517
+ raise ValueError(
518
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
519
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
520
+ )
521
+
522
+ if latents is None:
523
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
524
+ else:
525
+ latents = latents.to(device)
526
+
527
+ # scale the initial noise by the standard deviation required by the scheduler
528
+ latents = latents * self.scheduler.init_noise_sigma
529
+ return latents
530
+
531
+ @torch.no_grad()
532
+ def __call__(
533
+ self,
534
+ prompt: Union[str, List[str]] = None,
535
+ edit_prompt: Union[str, List[str]] = None,
536
+ height: Optional[int] = None,
537
+ width: Optional[int] = None,
538
+ num_inference_steps: int = 50,
539
+ guidance_scale: float = 7.5,
540
+ negative_prompt: Optional[Union[str, List[str]]] = None,
541
+ num_images_per_prompt: Optional[int] = 1,
542
+ eta: float = 0.0,
543
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
544
+ latents: Optional[torch.FloatTensor] = None,
545
+ prompt_embeds: Optional[torch.FloatTensor] = None,
546
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
547
+ output_type: Optional[str] = "pil",
548
+ return_dict: bool = True,
549
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
550
+ callback_steps: int = 1,
551
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
552
+ guidance_rescale: float = 0.0,
553
+ optimization_steps: int = 1,
554
+ learning_rate: float = 0.05,
555
+ max_steps: int = 50,
556
+ input_image = None,
557
+ mask_image = None,
558
+ full_source_steps: int = 10,
559
+ ):
560
+ # 0. Default height and width to unet
561
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
562
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
563
+
564
+ # 1. Check inputs
565
+ self.check_inputs(prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
566
+
567
+ # 2. Define call parameters
568
+ batch_size = 1 if prompt is None else (1 if isinstance(prompt, str) else len(prompt))
569
+ device = self._execution_device
570
+ do_classifier_free_guidance = guidance_scale > 1.0
571
+
572
+ # 3. Encode input prompt
573
+ target_prompt_embeds, negative_prompt_embeds = self.encode_prompt(
574
+ edit_prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt=prompt,
575
+ prompt_embeds=None,
576
+ lora_scale=cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None,
577
+ )
578
+ if do_classifier_free_guidance:
579
+ target_prompt_embeds = torch.cat([negative_prompt_embeds, target_prompt_embeds])
580
+
581
+ # 4. Prepare timesteps
582
+ timesteps = [(1. - i/num_inference_steps) * 1000. for i in range(num_inference_steps)]
583
+
584
+ # 5. Prepare latent variables
585
+ num_channels_latents = self.unet.config.in_channels
586
+
587
+ # 6. Prepare extra step kwargs
588
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
589
+
590
+
591
+ image = self.image_processor.preprocess(input_image)
592
+ image = image.to(device=device, dtype=self.unet.dtype)
593
+
594
+
595
+ gt_latents = retrieve_latents(self.vae.encode(image), generator=generator) * self.vae.config.scaling_factor
596
+
597
+
598
+ random_latents = self.prepare_latents(
599
+ batch_size * num_images_per_prompt, num_channels_latents, height, width,
600
+ target_prompt_embeds.dtype, device, generator
601
+ )
602
+ latents = random_latents.clone().detach()
603
+
604
+ mask = TF.ToTensor()(mask_image).to(device)
605
+ if mask.shape[0] == 3:
606
+ mask = mask[0]
607
+ mask = mask.float()
608
+ mask = mask.unsqueeze(0)#.unsqueeze(0)
609
+
610
+ mask = torch.nn.functional.interpolate(mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor), mode='bilinear', align_corners=False)
611
+ mask = ~mask.expand_as(latents).bool()
612
+
613
+
614
+ self.unet.eval()
615
+ self.vae.eval()
616
+ self.vae.eval()
617
+
618
+ latents = random_latents.clone().detach()
619
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
620
+ for i, t in enumerate(timesteps):
621
+ latents, _ = self.perform_denoising_step(
622
+ latents, t, target_prompt_embeds, do_classifier_free_guidance, guidance_scale,
623
+ device, i, optimization_steps, learning_rate,
624
+ max_steps, timesteps, gt_latents, full_source_steps, mask=mask
625
+ )
626
+
627
+ if callback is not None and i % callback_steps == 0:
628
+ callback(i // getattr(self.scheduler, "order", 1), t, latents)
629
+
630
+ progress_bar.update()
631
+
632
+ # 10. Post-processing
633
+ image = self.post_process_image(latents, output_type)
634
+
635
+ # 11. Offload all models
636
+ self.maybe_free_model_hooks()
637
+
638
+ if not return_dict:
639
+ return (image, None)
640
+
641
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
642
+
643
+ def load_and_preprocess_image(self, image_path, custom_image_processor, device):
644
+ from diffusers.utils import load_image
645
+ img = load_image(image_path)
646
+ img = img.resize((512, 512))
647
+ return custom_image_processor(img).unsqueeze(0).to(device)
648
+
649
+ def perform_denoising_step(self, latents, t, prompt_embeds, do_classifier_free_guidance, guidance_scale,
650
+ device, step, optimization_steps, learning_rate,
651
+ max_steps, timesteps, gt_latents, full_source_steps, mask=None):
652
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
653
+ vec_t = torch.ones((latent_model_input.shape[0],), device=latents.device) * t
654
+ v_pred = self.unet(latent_model_input, vec_t, encoder_hidden_states=prompt_embeds).sample
655
+
656
+ if do_classifier_free_guidance:
657
+ v_pred_neg, v_pred_text = v_pred.chunk(2)
658
+ v_pred = v_pred_text + ~mask*(v_pred_text - v_pred_neg) * guidance_scale
659
+ else:
660
+ mask = torch.ones_like(v_pred, dtype=torch.float32)
661
+
662
+ if step < full_source_steps:
663
+ mask = torch.ones_like(v_pred, dtype=torch.float32)
664
+
665
+ if step <= max_steps:
666
+ latents = self.optimize_latents(latents, v_pred_neg, t,
667
+ device, optimization_steps, learning_rate, gt_latents, mask)
668
+
669
+ return latents + (1.0 / len(timesteps)) * v_pred, mask
670
+
671
+ def optimize_latents(self, latents, v_pred, t, device, optimization_steps, learning_rate,
672
+ gt_latents, mask):
673
+ with torch.enable_grad():
674
+ latent_copy = latents.clone().detach()
675
+ latents = torch.autograd.Variable(latents, requires_grad=True)
676
+ optimizer = torch.optim.Adam([latents], lr=learning_rate)
677
+
678
+ # latents_new = latents + new_parameter
679
+ for _ in range(optimization_steps):
680
+ latents_p = latents + t/1000 * v_pred
681
+
682
+ loss = (0.00001*torch.nn.functional.mse_loss(latents_p, gt_latents, reduction='none')*mask).mean()
683
+ loss.backward()
684
+ optimizer.step()
685
+ optimizer.zero_grad()
686
+
687
+ return latents
688
+
689
+ def decode_latents(self, latents):
690
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
691
+ return self.image_processor.postprocess(image, output_type="pt")[0]
692
+
693
+ def post_process_image(self, latents, output_type):
694
+ if output_type == "latent":
695
+ return latents
696
+
697
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
698
+ do_denormalize = [True] * image.shape[0]
699
+ return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spaces
2
+ diffusers
3
+ gradio==5.6.0
4
+ numpy
5
+ Pillow
6
+ torch
7
+ torchvision
8
+ transformers
9
+ accelerate
10
+ xformers
11
+ sentencepiece
saved_results/20241129_041830/input.png ADDED
saved_results/20241129_041830/mask.png ADDED
saved_results/20241129_041830/output.png ADDED
saved_results/20241129_041830/parameters.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mode": "Editing",
3
+ "prompt": "a dog",
4
+ "edit_prompt": "a tiger",
5
+ "seed": 0,
6
+ "randomize_seed": true,
7
+ "num_inference_steps": 50,
8
+ "max_steps": 50,
9
+ "learning_rate": 1,
10
+ "max_source_steps": 20,
11
+ "optimization_steps": 5,
12
+ "true_cfg": 2,
13
+ "inverseproblem": false
14
+ }
saved_results/20241129_154837/input.png ADDED
saved_results/20241129_154837/mask.png ADDED
saved_results/20241129_154837/output.png ADDED
saved_results/20241129_154837/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "a cat",
3
+ "edit_prompt": "a tiger",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 50,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 5,
11
+ "true_cfg": 2,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_160150/input.png ADDED
saved_results/20241129_160150/mask.png ADDED
saved_results/20241129_160150/output.png ADDED
saved_results/20241129_160150/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "A cute rabbit with big eyes",
3
+ "edit_prompt": "A cute pig with big eyes",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 40,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 5,
11
+ "true_cfg": 4,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_160359/input.png ADDED
saved_results/20241129_160359/mask.png ADDED
saved_results/20241129_160359/output.png ADDED
saved_results/20241129_160359/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "a dog",
3
+ "edit_prompt": "a lion",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 40,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 5,
11
+ "true_cfg": 4,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_160439/input.png ADDED
saved_results/20241129_160439/mask.png ADDED
saved_results/20241129_160439/output.png ADDED
saved_results/20241129_160439/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "a dog",
3
+ "edit_prompt": "a lion",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 20,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 5,
11
+ "true_cfg": 4,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_161118/input.png ADDED
saved_results/20241129_161118/mask.png ADDED
saved_results/20241129_161118/output.png ADDED
saved_results/20241129_161118/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "two birds sitting on a branch",
3
+ "edit_prompt": "two origami birds sitting on a branch",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 50,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 30,
10
+ "optimization_steps": 2,
11
+ "true_cfg": 2,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_161547/input.png ADDED
saved_results/20241129_161547/mask.png ADDED
saved_results/20241129_161547/output.png ADDED
saved_results/20241129_161547/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": " a woman with long hair sitting in the sand at sunset",
3
+ "edit_prompt": "a woman with short hair sitting in the sand at sunset",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 50,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 2,
11
+ "true_cfg": 2,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_161602/input.png ADDED
saved_results/20241129_161602/mask.png ADDED
saved_results/20241129_161602/output.png ADDED
saved_results/20241129_161602/parameters.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": " a woman with long hair sitting in the sand at sunset",
3
+ "edit_prompt": "a woman with short hair sitting in the sand at sunset",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 30,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 2,
11
+ "true_cfg": 2,
12
+ "inverseproblem": false
13
+ }
saved_results/20241129_195331/input.png ADDED
saved_results/20241129_195331/mask.png ADDED
saved_results/20241129_195331/output.png ADDED
saved_results/20241129_195331/parameters.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "prompt": "a cat",
3
+ "edit_prompt": "a silver sculpture of cat",
4
+ "seed": 0,
5
+ "randomize_seed": true,
6
+ "num_inference_steps": 50,
7
+ "max_steps": 50,
8
+ "learning_rate": 0.5,
9
+ "max_source_steps": 20,
10
+ "optimization_steps": 5,
11
+ "true_cfg": 2,
12
+ }