Linoy Tsaban commited on
Commit
249a7a1
1 Parent(s): a0966be

Upload 9 files

Browse files
app.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import numpy as np
4
+ import requests
5
+ import random
6
+ from io import BytesIO
7
+ from utils import *
8
+ from constants import *
9
+ # from inversion_utils import *
10
+ # from inversion_utils_dpmplusplus import *
11
+ #from modified_pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
12
+ from pipeline_semantic_stable_diffusion_img2img_solver import SemanticStableDiffusionImg2ImgPipeline_DPMSolver
13
+ from torch import autocast, inference_mode
14
+ from diffusers import StableDiffusionPipeline
15
+ from diffusers.schedulers import DDIMScheduler
16
+ from scheduling_dpmsolver_multistep_inject import DPMSolverMultistepSchedulerInject
17
+ from transformers import AutoProcessor, BlipForConditionalGeneration
18
+ from share_btn import community_icon_html, loading_icon_html, share_js
19
+
20
+ # load pipelines
21
+ sd_model_id = "runwayml/stable-diffusion-v1-5"
22
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+
24
+ pipe = SemanticStableDiffusionImg2ImgPipeline_DPMSolver.from_pretrained(sd_model_id,torch_dtype=torch.float16).to(device)
25
+ # pipe.scheduler = DDIMScheduler.from_config(sd_model_id, subfolder = "scheduler")
26
+ pipe.scheduler = DPMSolverMultistepSchedulerInject(algorithm_type="sde-dpmsolver++", solver_order=2)
27
+
28
+ blip_processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
29
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base",torch_dtype=torch.float16).to(device)
30
+
31
+
32
+
33
+ ## IMAGE CPATIONING ##
34
+ def caption_image(input_image):
35
+ inputs = blip_processor(images=input_image, return_tensors="pt").to(device, torch.float16)
36
+ pixel_values = inputs.pixel_values
37
+
38
+ generated_ids = blip_model.generate(pixel_values=pixel_values, max_length=50)
39
+ generated_caption = blip_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
40
+ return generated_caption, generated_caption
41
+
42
+
43
+
44
+ ## DDPM INVERSION AND SAMPLING ##
45
+ # def invert(x0, prompt_src="", num_diffusion_steps=100, cfg_scale_src = 3.5, eta = 1):
46
+
47
+ # # inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
48
+ # # based on the code in https://github.com/inbarhub/DDPM_inversion
49
+
50
+ # # returns wt, zs, wts:
51
+ # # wt - inverted latent
52
+ # # wts - intermediate inverted latents
53
+ # # zs - noise maps
54
+
55
+ # sd_pipe.scheduler.set_timesteps(num_diffusion_steps)
56
+
57
+ # # vae encode image
58
+ # with inference_mode():
59
+ # w0 = (sd_pipe.vae.encode(x0).latent_dist.mode() * 0.18215)
60
+
61
+ # # find Zs and wts - forward process
62
+ # wt, zs, wts = inversion_forward_process(sd_pipe, w0, etas=eta, prompt=prompt_src, cfg_scale=cfg_scale_src, prog_bar=True, num_inference_steps=num_diffusion_steps)
63
+ # return zs, wts
64
+
65
+
66
+ # def sample(zs, wts, prompt_tar="", cfg_scale_tar=15, skip=36, eta = 1):
67
+
68
+ # # reverse process (via Zs and wT)
69
+ # w0, _ = inversion_reverse_process(sd_pipe, xT=wts[skip], etas=eta, prompts=[prompt_tar], cfg_scales=[cfg_scale_tar], prog_bar=True, zs=zs[skip:])
70
+
71
+ # # vae decode image
72
+ # with inference_mode():
73
+ # x0_dec = sd_pipe.vae.decode(1 / 0.18215 * w0).sample
74
+ # if x0_dec.dim()<4:
75
+ # x0_dec = x0_dec[None,:,:,:]
76
+ # img = image_grid(x0_dec)
77
+ # return img
78
+
79
+ # def reconstruct(tar_prompt,
80
+ # image_caption,
81
+ # tar_cfg_scale,
82
+ # skip,
83
+ # wts, zs,
84
+ # do_reconstruction,
85
+ # reconstruction,
86
+ # reconstruct_button
87
+ # ):
88
+
89
+ # if reconstruct_button == "Hide Reconstruction":
90
+ # return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=False), do_reconstruction, "Show Reconstruction"
91
+
92
+ # else:
93
+ # if do_reconstruction:
94
+ # if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run actual reconstruction
95
+ # tar_prompt = ""
96
+ # reconstruction_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
97
+ # reconstruction = gr.State(value=reconstruction_img)
98
+ # do_reconstruction = False
99
+ # return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=True), do_reconstruction, "Hide Reconstruction"
100
+
101
+ def sample(zs, wts, prompt_tar="", cfg_scale_tar=15, skip=36, eta = 1):
102
+
103
+ latnets = wts.value[-1].expand(1, -1, -1, -1)
104
+ img = pipe(prompt=tar_prompt,
105
+ init_latents=latnets,
106
+ guidance_scale = tar_cfg_scale,
107
+ # num_images_per_prompt=1,
108
+ # num_inference_steps=steps,
109
+ # use_ddpm=True,
110
+ # wts=wts.value,
111
+ zs=zs.value).images[0]
112
+ return img
113
+
114
+
115
+
116
+ def reconstruct(tar_prompt,
117
+ image_caption,
118
+ tar_cfg_scale,
119
+ skip,
120
+ wts, zs,
121
+ do_reconstruction,
122
+ reconstruction,
123
+ reconstruct_button
124
+ ):
125
+
126
+ if reconstruct_button == "Hide Reconstruction":
127
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=False), do_reconstruction, "Show Reconstruction"
128
+
129
+ else:
130
+ if do_reconstruction:
131
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run actual reconstruction
132
+ tar_prompt = ""
133
+ latnets = wts.value[-1].expand(1, -1, -1, -1)
134
+ reconstruction_img = pipe(prompt=tar_prompt,
135
+ init_latents=latnets,
136
+ guidance_scale = tar_cfg_scale,
137
+ # num_images_per_prompt=1,
138
+ # num_inference_steps=steps,
139
+ # use_ddpm=True,
140
+ # wts=wts.value,
141
+ zs=zs.value).images[0]
142
+ reconstruction = gr.State(value=reconstruction_img)
143
+ do_reconstruction = False
144
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=True), do_reconstruction, "Hide Reconstruction"
145
+
146
+
147
+
148
+
149
+ def load_and_invert(
150
+ input_image,
151
+ do_inversion,
152
+ seed, randomize_seed,
153
+ wts, zs,
154
+ src_prompt ="",
155
+ # tar_prompt="",
156
+ steps=30,
157
+ src_cfg_scale = 3.5,
158
+ skip=15,
159
+ tar_cfg_scale=15,
160
+ progress=gr.Progress(track_tqdm=True)
161
+
162
+ ):
163
+
164
+
165
+ # x0 = load_512(input_image, device=device).to(torch.float16)
166
+
167
+ if do_inversion or randomize_seed:
168
+ # invert and retrieve noise maps and latent
169
+ zs_tensor, wts_tensor = pipe.invert(
170
+ image_path = input_image,
171
+ source_prompt =src_prompt,
172
+ source_guidance_scale= src_cfg_scale,
173
+ num_inversion_steps = steps,
174
+ skip = skip,
175
+ eta = 1.0,
176
+ )
177
+ wts = gr.State(value=wts_tensor)
178
+ zs = gr.State(value=zs_tensor)
179
+ do_inversion = False
180
+
181
+ return wts, zs, do_inversion, inversion_progress.update(visible=False)
182
+
183
+ ## SEGA ##
184
+
185
+ def edit(input_image,
186
+ wts, zs,
187
+ tar_prompt,
188
+ image_caption,
189
+ steps,
190
+ skip,
191
+ tar_cfg_scale,
192
+ edit_concept_1,edit_concept_2,edit_concept_3,
193
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
194
+ warmup_1, warmup_2, warmup_3,
195
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
196
+ threshold_1, threshold_2, threshold_3,
197
+ do_reconstruction,
198
+ reconstruction,
199
+ # for inversion in case it needs to be re computed (and avoid delay):
200
+ do_inversion,
201
+ seed,
202
+ randomize_seed,
203
+ src_prompt,
204
+ src_cfg_scale,
205
+ mask_type):
206
+ show_share_button = gr.update(visible=True)
207
+ if(mask_type == "No mask"):
208
+ use_cross_attn_mask = False
209
+ use_intersect_mask = False
210
+ elif(mask_type=="Cross Attention Mask"):
211
+ use_cross_attn_mask = True
212
+ use_intersect_mask = False
213
+ elif(mask_type=="Intersect Mask"):
214
+ use_cross_attn_mask = False
215
+ use_intersect_mask = True
216
+ if do_inversion or randomize_seed:
217
+ zs_tensor, wts_tensor = pipe.invert(
218
+ image_path = input_image,
219
+ source_prompt =src_prompt,
220
+ source_guidance_scale= src_cfg_scale,
221
+ num_inversion_steps = steps,
222
+ skip = skip,
223
+ eta = 1.0,
224
+ )
225
+ wts = gr.State(value=wts_tensor)
226
+ zs = gr.State(value=zs_tensor)
227
+ do_inversion = False
228
+
229
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run pure sega
230
+ tar_prompt = ""
231
+
232
+ if edit_concept_1 != "" or edit_concept_2 != "" or edit_concept_3 != "":
233
+ editing_args = dict(
234
+ editing_prompt = [edit_concept_1,edit_concept_2,edit_concept_3],
235
+ reverse_editing_direction = [ neg_guidance_1, neg_guidance_2, neg_guidance_3,],
236
+ edit_warmup_steps=[warmup_1, warmup_2, warmup_3,],
237
+ edit_guidance_scale=[guidnace_scale_1,guidnace_scale_2,guidnace_scale_3],
238
+ edit_threshold=[threshold_1, threshold_2, threshold_3],
239
+ edit_momentum_scale=0.3,
240
+ edit_mom_beta=0.6,
241
+ eta=1,
242
+ use_cross_attn_mask=use_cross_attn_mask,
243
+ use_intersect_mask=use_intersect_mask
244
+ )
245
+
246
+ latnets = wts.value[-1].expand(1, -1, -1, -1)
247
+ sega_out = pipe(prompt=tar_prompt,
248
+ init_latents=latnets,
249
+ guidance_scale = tar_cfg_scale,
250
+ # num_images_per_prompt=1,
251
+ # num_inference_steps=steps,
252
+ # use_ddpm=True,
253
+ # wts=wts.value,
254
+ zs=zs.value, **editing_args)
255
+
256
+ return sega_out.images[0], reconstruct_button.update(visible=True), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
257
+
258
+ else: # if sega concepts were not added, performs regular ddpm sampling
259
+
260
+ if do_reconstruction: # if ddpm sampling wasn't computed
261
+ pure_ddpm_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
262
+ reconstruction = gr.State(value=pure_ddpm_img)
263
+ do_reconstruction = False
264
+ return pure_ddpm_img, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
265
+
266
+ return reconstruction.value, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
267
+
268
+
269
+ def randomize_seed_fn(seed, randomize_seed):
270
+ if randomize_seed:
271
+ seed = random.randint(0, np.iinfo(np.int32).max)
272
+ torch.manual_seed(seed)
273
+ return seed
274
+
275
+ def crop_image(image):
276
+ h, w, c = image.shape
277
+ if h < w:
278
+ offset = (w - h) // 2
279
+ image = image[:, offset:offset + h]
280
+ elif w < h:
281
+ offset = (h - w) // 2
282
+ image = image[offset:offset + w]
283
+ image = np.array(Image.fromarray(image).resize((512, 512)))
284
+ return image
285
+
286
+
287
+ def get_example():
288
+ case = [
289
+ [
290
+ 'examples/lemons_input.jpg',
291
+ # '',
292
+ 'apples', 'lemons',
293
+ 'a ceramic bowl',
294
+ 'examples/lemons_output.jpg',
295
+
296
+
297
+ 7,7,
298
+ 1,1,
299
+ False, True,
300
+ 100,
301
+ 36,
302
+ 15,
303
+
304
+ ],
305
+ [
306
+ 'examples/girl_with_pearl_earring_input.png',
307
+ # '',
308
+ 'glasses', '',
309
+ '',
310
+ 'examples/girl_with_pearl_earring_output.png',
311
+
312
+
313
+ 3,7,
314
+ 3,2,
315
+ False,False,
316
+ 100,
317
+ 36,
318
+ 15,
319
+
320
+ ],
321
+ [
322
+ 'examples/rockey_shore_input.jpg',
323
+ # '',
324
+ 'sea turtle', '',
325
+ 'watercolor painting',
326
+ 'examples/rockey_shore_output.jpg',
327
+
328
+
329
+ 7,7,
330
+ 1,2,
331
+ False,False,
332
+ 100,
333
+ 36,
334
+ 15,
335
+ ],
336
+ [
337
+ 'examples/flower_field_input.jpg',
338
+ # '',
339
+ 'wheat', 'red flowers',
340
+ 'oil painting',
341
+ 'examples/flower_field_output_2.jpg',
342
+
343
+
344
+ 20,7,
345
+ 1,1,
346
+ False,True,
347
+ 100,
348
+ 36,
349
+ 15,
350
+
351
+ ],
352
+ [
353
+ 'examples/butterfly_input.jpg',
354
+ # '',
355
+ 'bee', 'butterfly',
356
+ 'oil painting',
357
+ 'examples/butterfly_output.jpg',
358
+ 7, 7,
359
+ 1,1,
360
+ False, True,
361
+ 100,
362
+ 36,
363
+ 15,
364
+ ]
365
+ ]
366
+ return case
367
+
368
+
369
+ def swap_visibilities(input_image,
370
+ edit_concept_1,
371
+ edit_concept_2,
372
+ tar_prompt,
373
+ sega_edited_image,
374
+ guidnace_scale_1,
375
+ guidnace_scale_2,
376
+ warmup_1,
377
+ warmup_2,
378
+ neg_guidance_1,
379
+ neg_guidance_2,
380
+ steps,
381
+ skip,
382
+ tar_cfg_scale,
383
+ sega_concepts_counter
384
+
385
+ ):
386
+ sega_concepts_counter=0
387
+ concept1_update = update_display_concept("Remove" if neg_guidance_1 else "Add", edit_concept_1, neg_guidance_1, sega_concepts_counter)
388
+ if(edit_concept_2 != ""):
389
+ concept2_update = update_display_concept("Remove" if neg_guidance_2 else "Add", edit_concept_2, neg_guidance_2, sega_concepts_counter+1)
390
+ else:
391
+ concept2_update = gr.update(visible=False), gr.update(visible=False),gr.update(visible=False), gr.update(value=neg_guidance_2),gr.update(visible=True),gr.update(visible=False),sega_concepts_counter+1
392
+
393
+ return (gr.update(visible=True), *concept1_update[:-1], *concept2_update)
394
+
395
+
396
+
397
+ ########
398
+ # demo #
399
+ ########
400
+
401
+
402
+ intro = """
403
+ <h1 style="font-weight: 1400; text-align: center; margin-bottom: 7px;">
404
+ LEDITS - Pipeline for editing images
405
+ </h1>
406
+ <h3 style="font-weight: 600; text-align: center;">
407
+ Real Image Latent Editing with Edit Friendly DDPM and Semantic Guidance
408
+ </h3>
409
+ <h4 style="text-align: center; margin-bottom: 7px;">
410
+ <a href="https://editing-images-project.hf.space/" style="text-decoration: underline;" target="_blank">Project Page</a> | <a href="https://arxiv.org/abs/2307.00522" style="text-decoration: underline;" target="_blank">ArXiv</a>
411
+ </h4>
412
+
413
+ <p style="font-size: 0.9rem; margin: 0rem; line-height: 1.2em; margin-top:1em">
414
+ <a href="https://huggingface.co/spaces/editing-images/edit_friendly_ddpm_x_sega?duplicate=true">
415
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
416
+ <p/>"""
417
+
418
+ help_text = """
419
+ - **Getting Started - edit images with DDPM X SEGA:**
420
+
421
+ The are 3 general setting options you can play with -
422
+
423
+ 1. **Pure DDPM Edit -** Describe the desired edited output image in detail
424
+ 2. **Pure SEGA Edit -** Keep the target prompt empty ***or*** with a description of the original image and add editing concepts for Semantic Gudiance editing
425
+ 3. **Combined -** Describe the desired edited output image in detail and add additional SEGA editing concepts on top
426
+ - **Getting Started - Tips**
427
+
428
+ While the best approach depends on your editing objective and source image, we can layout a few guiding tips to use as a starting point -
429
+
430
+ 1. **DDPM** is usually more suited for scene/style changes and major subject changes (for example ) while **SEGA** allows for more fine grained control, changes are more delicate, more suited for adding details (for example facial expressions and attributes, subtle style modifications, object adding/removing)
431
+ 2. The more you describe the scene in the target prompt (both the parts and details you wish to keep the same and those you wish to change), the better the result
432
+ 3. **Combining DDPM Edit with SEGA -**
433
+ Try dividing your editing objective to more significant scene/style/subject changes and detail adding/removing and more moderate changes. Then describe the major changes in a detailed target prompt and add the more fine grained details as SEGA concepts.
434
+ 4. **Reconstruction:** Using an empty source prompt + target prompt will lead to a perfect reconstruction
435
+ - **Fidelity vs creativity**:
436
+
437
+ Bigger values → more fidelity, smaller values → more creativity
438
+
439
+ 1. `Skip Steps`
440
+ 2. `Warmup` (SEGA)
441
+ 3. `Threshold` (SEGA)
442
+
443
+ Bigger values → more creativity, smaller values → more fidelity
444
+
445
+ 1. `Guidance Scale`
446
+ 2. `Concept Guidance Scale` (SEGA)
447
+ """
448
+
449
+ with gr.Blocks(css="style.css") as demo:
450
+ def update_counter(sega_concepts_counter, concept1, concept2, concept3):
451
+ if sega_concepts_counter == "":
452
+ sega_concepts_counter = sum(1 for concept in (concept1, concept2, concept3) if concept != '')
453
+ return sega_concepts_counter
454
+ def remove_concept(sega_concepts_counter, row_triggered):
455
+ sega_concepts_counter -= 1
456
+ rows_visibility = [gr.update(visible=False) for _ in range(4)]
457
+
458
+ if(row_triggered-1 > sega_concepts_counter):
459
+ rows_visibility[sega_concepts_counter] = gr.update(visible=True)
460
+ else:
461
+ rows_visibility[row_triggered-1] = gr.update(visible=True)
462
+
463
+ row1_visibility, row2_visibility, row3_visibility, row4_visibility = rows_visibility
464
+
465
+ guidance_scale_label = "Concept Guidance Scale"
466
+ # enable_interactive = gr.update(interactive=True)
467
+ return (gr.update(visible=False),
468
+ gr.update(visible=False, value="",),
469
+ gr.update(interactive=True, value=""),
470
+ gr.update(visible=False,label = guidance_scale_label),
471
+ gr.update(interactive=True, value =False),
472
+ gr.update(value=DEFAULT_WARMUP_STEPS),
473
+ gr.update(value=DEFAULT_THRESHOLD),
474
+ gr.update(visible=True),
475
+ gr.update(interactive=True, value="custom"),
476
+ row1_visibility,
477
+ row2_visibility,
478
+ row3_visibility,
479
+ row4_visibility,
480
+ sega_concepts_counter
481
+ )
482
+
483
+
484
+
485
+ def update_display_concept(button_label, edit_concept, neg_guidance, sega_concepts_counter):
486
+ sega_concepts_counter += 1
487
+ guidance_scale_label = "Concept Guidance Scale"
488
+ if(button_label=='Remove'):
489
+ neg_guidance = True
490
+ guidance_scale_label = "Negative Guidance Scale"
491
+
492
+ return (gr.update(visible=True), #boxn
493
+ gr.update(visible=True, value=edit_concept), #concept_n
494
+ gr.update(visible=True,label = guidance_scale_label), #guidance_scale_n
495
+ gr.update(value=neg_guidance),#neg_guidance_n
496
+ gr.update(visible=False), #row_n
497
+ gr.update(visible=True), #row_n+1
498
+ sega_concepts_counter
499
+ )
500
+
501
+
502
+ def display_editing_options(run_button, clear_button, sega_tab):
503
+ return run_button.update(visible=True), clear_button.update(visible=True), sega_tab.update(visible=True)
504
+
505
+ def update_interactive_mode(add_button_label):
506
+ if add_button_label == "Clear":
507
+ return gr.update(interactive=False), gr.update(interactive=False)
508
+ else:
509
+ return gr.update(interactive=True), gr.update(interactive=True)
510
+
511
+ def update_dropdown_parms(dropdown):
512
+ if dropdown == 'custom':
513
+ return DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD
514
+ elif dropdown =='style':
515
+ return STYLE_SEGA_CONCEPT_GUIDANCE_SCALE,STYLE_WARMUP_STEPS, STYLE_THRESHOLD
516
+ elif dropdown =='object':
517
+ return OBJECT_SEGA_CONCEPT_GUIDANCE_SCALE,OBJECT_WARMUP_STEPS, OBJECT_THRESHOLD
518
+ elif dropdown =='faces':
519
+ return FACE_SEGA_CONCEPT_GUIDANCE_SCALE,FACE_WARMUP_STEPS, FACE_THRESHOLD
520
+
521
+
522
+ def reset_do_inversion():
523
+ return True
524
+
525
+ def reset_do_reconstruction():
526
+ do_reconstruction = True
527
+ return do_reconstruction
528
+
529
+ def reset_image_caption():
530
+ return ""
531
+
532
+ def update_inversion_progress_visibility(input_image, do_inversion):
533
+ if do_inversion and not input_image is None:
534
+ return inversion_progress.update(visible=True)
535
+ else:
536
+ return inversion_progress.update(visible=False)
537
+
538
+ def update_edit_progress_visibility(input_image, do_inversion):
539
+ # if do_inversion and not input_image is None:
540
+ # return inversion_progress.update(visible=True)
541
+ # else:
542
+ return inversion_progress.update(visible=True)
543
+
544
+
545
+ gr.HTML(intro)
546
+ wts = gr.State()
547
+ zs = gr.State()
548
+ reconstruction = gr.State()
549
+ do_inversion = gr.State(value=True)
550
+ do_reconstruction = gr.State(value=True)
551
+ sega_concepts_counter = gr.State(0)
552
+ image_caption = gr.State(value="")
553
+
554
+ with gr.Row():
555
+ input_image = gr.Image(label="Input Image", interactive=True, elem_id="input_image")
556
+ ddpm_edited_image = gr.Image(label=f"Pure DDPM Inversion Image", interactive=False, visible=False)
557
+ sega_edited_image = gr.Image(label=f"LEDITS Edited Image", interactive=False, elem_id="output_image")
558
+ input_image.style(height=365, width=365)
559
+ ddpm_edited_image.style(height=365, width=365)
560
+ sega_edited_image.style(height=365, width=365)
561
+
562
+ with gr.Group(visible=False) as share_btn_container:
563
+ with gr.Group(elem_id="share-btn-container"):
564
+ community_icon = gr.HTML(community_icon_html, visible=True)
565
+ loading_icon = gr.HTML(loading_icon_html, visible=False)
566
+ share_button = gr.Button("Share to community", elem_id="share-btn", visible=True)
567
+
568
+ with gr.Row():
569
+ with gr.Box(visible=False, elem_id="box1") as box1:
570
+ with gr.Row():
571
+ concept_1 = gr.Button(scale=3, value="")
572
+ remove_concept1 = gr.Button("x", scale=1, min_width=10)
573
+ with gr.Row():
574
+ guidnace_scale_1 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
575
+ info="How strongly the concept should modify the image",
576
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
577
+ step=0.5, interactive=True)
578
+ with gr.Box(visible=False, elem_id="box2") as box2:
579
+ with gr.Row():
580
+ concept_2 = gr.Button(scale=3, value="")
581
+ remove_concept2 = gr.Button("x", scale=1, min_width=10)
582
+ with gr.Row():
583
+ guidnace_scale_2 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
584
+ info="How strongly the concept should modify the image",
585
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
586
+ step=0.5, interactive=True)
587
+ with gr.Box(visible=False, elem_id="box3") as box3:
588
+ with gr.Row():
589
+ concept_3 = gr.Button(scale=3, value="")
590
+ remove_concept3 = gr.Button("x", scale=1, min_width=10)
591
+ with gr.Row():
592
+ guidnace_scale_3 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
593
+ info="How strongly the concept should modify the image",
594
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
595
+ step=0.5, interactive=True)
596
+
597
+
598
+ with gr.Row():
599
+ inversion_progress = gr.Textbox(visible=False, label="Inversion progress")
600
+
601
+ with gr.Box():
602
+ intro_segs = gr.Markdown("Add/Remove Concepts from your Image <span style=\"font-size: 12px; color: rgb(156, 163, 175)\">with Semantic Guidance</span>")
603
+ # 1st SEGA concept
604
+ with gr.Row().style(mobile_collapse=False) as row1:
605
+ with gr.Column(scale=3, min_width=100):
606
+ with gr.Row().style(mobile_collapse=True):
607
+ # with gr.Column(scale=3, min_width=100):
608
+ edit_concept_1 = gr.Textbox(
609
+ label="Concept",
610
+ show_label=True,
611
+ max_lines=1, value="",
612
+ placeholder="E.g.: Sunglasses",
613
+ )
614
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
615
+ dropdown1 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
616
+
617
+
618
+ with gr.Column(scale=1, min_width=100, visible=False):
619
+ neg_guidance_1 = gr.Checkbox(
620
+ label='Remove Concept?')
621
+
622
+ with gr.Column(scale=1, min_width=100):
623
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
624
+ with gr.Column():
625
+ add_1 = gr.Button('Add')
626
+ remove_1 = gr.Button('Remove')
627
+
628
+
629
+ # 2nd SEGA concept
630
+ with gr.Row(visible=False).style(equal_height=True) as row2:
631
+ with gr.Column(scale=3, min_width=100):
632
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
633
+ # with gr.Column(scale=3, min_width=100):
634
+ edit_concept_2 = gr.Textbox(
635
+ label="Concept",
636
+ show_label=True,
637
+ max_lines=1,
638
+ placeholder="E.g.: Realistic",
639
+ )
640
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
641
+ dropdown2 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
642
+
643
+ with gr.Column(scale=1, min_width=100, visible=False):
644
+ neg_guidance_2 = gr.Checkbox(
645
+ label='Remove Concept?')
646
+
647
+ with gr.Column(scale=1, min_width=100):
648
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
649
+ with gr.Column():
650
+ add_2 = gr.Button('Add')
651
+ remove_2 = gr.Button('Remove')
652
+
653
+ # 3rd SEGA concept
654
+ with gr.Row(visible=False).style(equal_height=True) as row3:
655
+ with gr.Column(scale=3, min_width=100):
656
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
657
+ # with gr.Column(scale=3, min_width=100):
658
+ edit_concept_3 = gr.Textbox(
659
+ label="Concept",
660
+ show_label=True,
661
+ max_lines=1,
662
+ placeholder="E.g.: orange",
663
+ )
664
+ # with gr.Column(scale=2, min_width=100):
665
+ dropdown3 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
666
+
667
+ with gr.Column(scale=1, min_width=100, visible=False):
668
+ neg_guidance_3 = gr.Checkbox(
669
+ label='Remove Concept?',visible=True)
670
+
671
+ with gr.Column(scale=1, min_width=100):
672
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
673
+ with gr.Column():
674
+ add_3 = gr.Button('Add')
675
+ remove_3 = gr.Button('Remove')
676
+
677
+ with gr.Row(visible=False).style(equal_height=True) as row4:
678
+ gr.Markdown("### Max of 3 concepts reached. Remove a concept to add more")
679
+
680
+ #with gr.Row(visible=False).style(mobile_collapse=False, equal_height=True):
681
+ # add_concept_button = gr.Button("+1 concept")
682
+
683
+
684
+
685
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
686
+ tar_prompt = gr.Textbox(
687
+ label="Describe your edited image (optional)",
688
+ elem_id="target_prompt",
689
+ # show_label=False,
690
+ max_lines=1, value="", scale=3,
691
+ placeholder="Target prompt, DDPM Inversion", info = "DDPM Inversion Prompt. Can help with global changes, modify to what you would like to see"
692
+ )
693
+ # caption_button = gr.Button("Caption Image", scale=1)
694
+
695
+
696
+ with gr.Row():
697
+ run_button = gr.Button("Edit your image!", visible=True)
698
+
699
+
700
+ with gr.Accordion("Advanced Options", open=False):
701
+ with gr.Tabs() as tabs:
702
+
703
+ with gr.TabItem('General options', id=2):
704
+ with gr.Row():
705
+ with gr.Column(min_width=100):
706
+ clear_button = gr.Button("Clear", visible=True)
707
+ src_prompt = gr.Textbox(lines=1, label="Source Prompt", interactive=True, placeholder="")
708
+ steps = gr.Number(value=100, precision=0, label="Num Diffusion Steps", interactive=True)
709
+ src_cfg_scale = gr.Number(value=3.5, label=f"Source Guidance Scale", interactive=True)
710
+ mask_type = gr.Radio(choices=["No mask", "Cross Attention Mask", "Intersect Mask"], value="Intersect Mask", label="Mask type")
711
+
712
+ with gr.Column(min_width=100):
713
+ reconstruct_button = gr.Button("Show Reconstruction", visible=False)
714
+ skip = gr.Slider(minimum=0, maximum=60, value=36, step=1, label="Skip Steps", interactive=True, info = "At which step to start denoising. Bigger values increase fidelity to input image")
715
+ tar_cfg_scale = gr.Slider(minimum=1, maximum=30,value=15, label=f"Guidance Scale", interactive=True)
716
+ seed = gr.Number(value=0, precision=0, label="Seed", interactive=True)
717
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=False)
718
+
719
+ with gr.TabItem('SEGA options', id=3) as sega_advanced_tab:
720
+ # 1st SEGA concept
721
+ gr.Markdown("1st concept")
722
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
723
+ warmup_1 = gr.Slider(label='Warmup', minimum=0, maximum=50,
724
+ value=DEFAULT_WARMUP_STEPS,
725
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
726
+ threshold_1 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
727
+ value=DEFAULT_THRESHOLD, step=0.01, interactive=True,
728
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
729
+
730
+ # 2nd SEGA concept
731
+ gr.Markdown("2nd concept")
732
+ with gr.Row() as row2_advanced:
733
+ warmup_2 = gr.Slider(label='Warmup', minimum=0, maximum=50,
734
+ value=DEFAULT_WARMUP_STEPS,
735
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
736
+ threshold_2 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
737
+ value=DEFAULT_THRESHOLD,
738
+ step=0.01, interactive=True,
739
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
740
+ # 3rd SEGA concept
741
+ gr.Markdown("3rd concept")
742
+ with gr.Row() as row3_advanced:
743
+ warmup_3 = gr.Slider(label='Warmup', minimum=0, maximum=50,
744
+ value=DEFAULT_WARMUP_STEPS, step=1,
745
+ interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
746
+ threshold_3 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
747
+ value=DEFAULT_THRESHOLD, step=0.01,
748
+ interactive=True,
749
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
750
+
751
+ # caption_button.click(
752
+ # fn = caption_image,
753
+ # inputs = [input_image],
754
+ # outputs = [tar_prompt]
755
+ # )
756
+ #neg_guidance_1.change(fn = update_label, inputs=[neg_guidance_1], outputs=[add_1])
757
+ #neg_guidance_2.change(fn = update_label, inputs=[neg_guidance_2], outputs=[add_2])
758
+ #neg_guidance_3.change(fn = update_label, inputs=[neg_guidance_3], outputs=[add_3])
759
+ add_1.click(fn=update_counter,
760
+ inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3],
761
+ outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_1, edit_concept_1, neg_guidance_1, sega_concepts_counter], outputs=[box1, concept_1, guidnace_scale_1,neg_guidance_1,row1, row2, sega_concepts_counter],queue=False)
762
+ add_2.click(fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_2, edit_concept_2, neg_guidance_2, sega_concepts_counter], outputs=[box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3, sega_concepts_counter],queue=False)
763
+ add_3.click(fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_3, edit_concept_3, neg_guidance_3, sega_concepts_counter], outputs=[box3, concept_3, guidnace_scale_3,neg_guidance_3,row3, row4, sega_concepts_counter],queue=False)
764
+
765
+ remove_1.click(fn = update_display_concept, inputs=[remove_1, edit_concept_1, neg_guidance_1, sega_concepts_counter], outputs=[box1, concept_1, guidnace_scale_1,neg_guidance_1,row1, row2, sega_concepts_counter],queue=False)
766
+ remove_2.click(fn = update_display_concept, inputs=[remove_2, edit_concept_2, neg_guidance_2 ,sega_concepts_counter], outputs=[box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3,sega_concepts_counter],queue=False)
767
+ remove_3.click(fn = update_display_concept, inputs=[remove_3, edit_concept_3, neg_guidance_3, sega_concepts_counter], outputs=[box3, concept_3, guidnace_scale_3,neg_guidance_3, row3, row4, sega_concepts_counter],queue=False)
768
+
769
+ remove_concept1.click(
770
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
771
+ fn = remove_concept, inputs=[sega_concepts_counter,gr.State(1)], outputs= [box1, concept_1, edit_concept_1, guidnace_scale_1,neg_guidance_1,warmup_1, threshold_1, add_1, dropdown1, row1, row2, row3, row4, sega_concepts_counter],queue=False)
772
+ remove_concept2.click(
773
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
774
+ fn = remove_concept, inputs=[sega_concepts_counter,gr.State(2)], outputs=[box2, concept_2, edit_concept_2, guidnace_scale_2,neg_guidance_2, warmup_2, threshold_2, add_2 , dropdown2, row1, row2, row3, row4, sega_concepts_counter],queue=False)
775
+ remove_concept3.click(
776
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
777
+ fn = remove_concept,inputs=[sega_concepts_counter,gr.State(3)], outputs=[box3, concept_3, edit_concept_3, guidnace_scale_3,neg_guidance_3,warmup_3, threshold_3, add_3, dropdown3, row1, row2, row3, row4, sega_concepts_counter],queue=False)
778
+
779
+ #add_concept_button.click(fn = update_display_concept, inputs=sega_concepts_counter,
780
+ # outputs= [row2, row2_advanced, row3, row3_advanced, add_concept_button, sega_concepts_counter], queue = False)
781
+
782
+ run_button.click(
783
+ fn=edit,
784
+ inputs=[input_image,
785
+ wts, zs,
786
+ tar_prompt,
787
+ image_caption,
788
+ steps,
789
+ skip,
790
+ tar_cfg_scale,
791
+ edit_concept_1,edit_concept_2,edit_concept_3,
792
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
793
+ warmup_1, warmup_2, warmup_3,
794
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
795
+ threshold_1, threshold_2, threshold_3, do_reconstruction, reconstruction,
796
+ do_inversion,
797
+ seed,
798
+ randomize_seed,
799
+ src_prompt,
800
+ src_cfg_scale,
801
+ mask_type
802
+
803
+
804
+ ],
805
+ outputs=[sega_edited_image, reconstruct_button, do_reconstruction, reconstruction, wts, zs, do_inversion, share_btn_container])
806
+ # .success(fn=update_gallery_display, inputs= [prev_output_image, sega_edited_image], outputs = [gallery, gallery, prev_output_image])
807
+
808
+
809
+ input_image.change(
810
+ fn = reset_do_inversion,
811
+ outputs = [do_inversion],
812
+ queue = False).then(
813
+ fn = randomize_seed_fn,
814
+ inputs = [seed, randomize_seed],
815
+ outputs = [seed], queue = False)
816
+ # Automatically start inverting upon input_image change
817
+ input_image.upload(fn = crop_image, inputs = [input_image], outputs = [input_image],queue=False).then(
818
+ fn = reset_do_inversion,
819
+ outputs = [do_inversion],
820
+ queue = False).then(
821
+ fn = randomize_seed_fn,
822
+ inputs = [seed, randomize_seed],
823
+ outputs = [seed], queue = False).then(fn = caption_image,
824
+ inputs = [input_image],
825
+ outputs = [tar_prompt, image_caption]).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
826
+ outputs=[inversion_progress],queue=False).then(
827
+ fn=load_and_invert,
828
+ inputs=[input_image,
829
+ do_inversion,
830
+ seed, randomize_seed,
831
+ wts, zs,
832
+ src_prompt,
833
+ # tar_prompt,
834
+ steps,
835
+ src_cfg_scale,
836
+ skip,
837
+ tar_cfg_scale,
838
+ ],
839
+ # outputs=[ddpm_edited_image, wts, zs, do_inversion],
840
+ outputs=[wts, zs, do_inversion, inversion_progress],
841
+ ).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
842
+ outputs=[inversion_progress],queue=False).then(
843
+ lambda: reconstruct_button.update(visible=False),
844
+ outputs=[reconstruct_button]).then(
845
+ fn = reset_do_reconstruction,
846
+ outputs = [do_reconstruction],
847
+ queue = False)
848
+
849
+
850
+ # Repeat inversion (and reconstruction) when these params are changed:
851
+ src_prompt.change(
852
+ fn = reset_do_inversion,
853
+ outputs = [do_inversion], queue = False).then(
854
+ fn = reset_do_reconstruction,
855
+ outputs = [do_reconstruction], queue = False)
856
+
857
+ steps.change(
858
+ fn = reset_do_inversion,
859
+ outputs = [do_inversion], queue = False).then(
860
+ fn = reset_do_reconstruction,
861
+ outputs = [do_reconstruction], queue = False)
862
+
863
+
864
+ src_cfg_scale.change(
865
+ fn = reset_do_inversion,
866
+ outputs = [do_inversion], queue = False).then(
867
+ fn = reset_do_reconstruction,
868
+ outputs = [do_reconstruction], queue = False)
869
+
870
+ # Repeat only reconstruction these params are changed:
871
+
872
+ tar_prompt.change(
873
+ fn = reset_do_reconstruction,
874
+ outputs = [do_reconstruction], queue = False)
875
+
876
+ tar_cfg_scale.change(
877
+ fn = reset_do_reconstruction,
878
+ outputs = [do_reconstruction], queue = False)
879
+
880
+ skip.change(
881
+ fn = reset_do_reconstruction,
882
+ outputs = [do_reconstruction], queue = False)
883
+
884
+ dropdown1.change(fn=update_dropdown_parms, inputs = [dropdown1], outputs = [guidnace_scale_1,warmup_1, threshold_1], queue=False)
885
+ dropdown2.change(fn=update_dropdown_parms, inputs = [dropdown2], outputs = [guidnace_scale_2,warmup_2, threshold_2], queue=False)
886
+ dropdown3.change(fn=update_dropdown_parms, inputs = [dropdown3], outputs = [guidnace_scale_3,warmup_3, threshold_3], queue=False)
887
+
888
+ clear_components = [input_image,ddpm_edited_image,ddpm_edited_image,sega_edited_image, do_inversion,
889
+ src_prompt, steps, src_cfg_scale, seed,
890
+ tar_prompt, skip, tar_cfg_scale, reconstruct_button,reconstruct_button,
891
+ edit_concept_1, guidnace_scale_1,guidnace_scale_1,warmup_1, threshold_1, neg_guidance_1,dropdown1, concept_1, concept_1, row1,
892
+ edit_concept_2, guidnace_scale_2,guidnace_scale_2,warmup_2, threshold_2, neg_guidance_2,dropdown2, concept_2, concept_2, row2,
893
+ edit_concept_3, guidnace_scale_3,guidnace_scale_3,warmup_3, threshold_3, neg_guidance_3,dropdown3, concept_3,concept_3, row3,
894
+ row4,sega_concepts_counter, box1, box2, box3 ]
895
+
896
+ clear_components_output_vals = [None, None,ddpm_edited_image.update(visible=False), None, True,
897
+ "", DEFAULT_DIFFUSION_STEPS, DEFAULT_SOURCE_GUIDANCE_SCALE, DEFAULT_SEED,
898
+ "", DEFAULT_SKIP_STEPS, DEFAULT_TARGET_GUIDANCE_SCALE, reconstruct_button.update(value="Show Reconstruction"),reconstruct_button.update(visible=False),
899
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_1.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","", concept_1.update(visible=False), row1.update(visible=True),
900
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_2.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","", concept_2.update(visible=False), row2.update(visible=False),
901
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_3.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","",concept_3.update(visible=False), row3.update(visible=False), row4.update(visible=False), gr.update(value=0),
902
+ box1.update(visible=False), box2.update(visible=False), box3.update(visible=False)]
903
+
904
+
905
+ clear_button.click(lambda: clear_components_output_vals, outputs =clear_components)
906
+
907
+ reconstruct_button.click(lambda: ddpm_edited_image.update(visible=True), outputs=[ddpm_edited_image]).then(fn = reconstruct,
908
+ inputs = [tar_prompt,
909
+ image_caption,
910
+ tar_cfg_scale,
911
+ skip,
912
+ wts, zs,
913
+ do_reconstruction,
914
+ reconstruction,
915
+ reconstruct_button],
916
+ outputs = [ddpm_edited_image,reconstruction, ddpm_edited_image, do_reconstruction, reconstruct_button])
917
+
918
+ randomize_seed.change(
919
+ fn = randomize_seed_fn,
920
+ inputs = [seed, randomize_seed],
921
+ outputs = [seed],
922
+ queue = False)
923
+
924
+ share_button.click(None, [], [], _js=share_js)
925
+
926
+ gr.Examples(
927
+ label='Examples',
928
+ fn=swap_visibilities,
929
+ run_on_click=True,
930
+ examples=get_example(),
931
+ inputs=[input_image,
932
+ edit_concept_1,
933
+ edit_concept_2,
934
+ tar_prompt,
935
+ sega_edited_image,
936
+ guidnace_scale_1,
937
+ guidnace_scale_2,
938
+ warmup_1,
939
+ warmup_2,
940
+ neg_guidance_1,
941
+ neg_guidance_2,
942
+ steps,
943
+ skip,
944
+ tar_cfg_scale,
945
+ sega_concepts_counter
946
+ ],
947
+ outputs=[share_btn_container, box1, concept_1, guidnace_scale_1,neg_guidance_1, row1, row2,box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3,sega_concepts_counter],
948
+ cache_examples=True
949
+ )
950
+
951
+
952
+ demo.queue()
953
+ demo.launch()
954
+ # demo.launch(share=True)
constants.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###############
2
+ # conststants #
3
+ ###############
4
+ DEFAULT_TARGET_GUIDANCE_SCALE = 15
5
+ DEFAULT_SOURCE_GUIDANCE_SCALE = 3.5
6
+ DEFAULT_DIFFUSION_STEPS = 100
7
+ DEFAULT_SKIP_STEPS = 36
8
+ DEFAULT_SEED = 0
9
+
10
+
11
+ DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE = 7
12
+ DEFAULT_WARMUP_STEPS = 2
13
+ DEFAULT_THRESHOLD = 0.95
14
+ DEFAULT_NEGATIVE_GUIDANCE=False
15
+
16
+ STYLE_SEGA_CONCEPT_GUIDANCE_SCALE = 8
17
+ STYLE_WARMUP_STEPS = 2
18
+ STYLE_THRESHOLD = 0.92
19
+
20
+ FACE_SEGA_CONCEPT_GUIDANCE_SCALE = 5
21
+ FACE_WARMUP_STEPS = 2
22
+ FACE_THRESHOLD = 0.95
23
+
24
+ OBJECT_SEGA_CONCEPT_GUIDANCE_SCALE = 15
25
+ OBJECT_WARMUP_STEPS = 5
26
+ OBJECT_THRESHOLD = 0.95
modified_pipeline_semantic_stable_diffusion.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import inspect
3
+ import warnings
4
+ from itertools import repeat
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ import torch
8
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.models.attention_processor import AttnProcessor, Attention
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import KarrasDiffusionSchedulers
15
+ from diffusers.utils import logging
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
18
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
19
+ # from . import SemanticStableDiffusionPipelineOutput
20
+
21
+ import numpy as np
22
+ from PIL import Image
23
+ from tqdm import tqdm
24
+ import torch.nn.functional as F
25
+ import math
26
+ from collections.abc import Iterable
27
+
28
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
29
+
30
+ class AttentionStore():
31
+ @staticmethod
32
+ def get_empty_store():
33
+ return {"down_cross": [], "mid_cross": [], "up_cross": [],
34
+ "down_self": [], "mid_self": [], "up_self": []}
35
+
36
+ def __call__(self, attn, is_cross: bool, place_in_unet: str, editing_prompts, PnP):
37
+ # attn.shape = batch_size * head_size, seq_len query, seq_len_key
38
+ bs = 2 + int(PnP) + editing_prompts
39
+ source_batch_size = int(attn.shape[0] // bs)
40
+ skip = 2 if PnP else 1 # skip PnP & unconditional
41
+ self.forward(
42
+ attn[skip*source_batch_size:],
43
+ is_cross,
44
+ place_in_unet)
45
+
46
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
47
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
48
+ if attn.shape[1] <= 32 ** 2: # avoid memory overhead
49
+ self.step_store[key].append(attn)
50
+
51
+ def between_steps(self, store_step=True):
52
+ if store_step:
53
+ if self.average:
54
+ if len(self.attention_store) == 0:
55
+ self.attention_store = self.step_store
56
+ else:
57
+ for key in self.attention_store:
58
+ for i in range(len(self.attention_store[key])):
59
+ self.attention_store[key][i] += self.step_store[key][i]
60
+ else:
61
+ if len(self.attention_store) == 0:
62
+ self.attention_store = [self.step_store]
63
+ else:
64
+ self.attention_store.append(self.step_store)
65
+
66
+ self.cur_step += 1
67
+ self.step_store = self.get_empty_store()
68
+
69
+ def get_attention(self, step: int):
70
+ if self.average:
71
+ attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store}
72
+ else:
73
+ assert(step is not None)
74
+ attention = self.attention_store[step]
75
+ return attention
76
+
77
+ def aggregate_attention(self, attention_maps, prompts, res: int,
78
+ from_where: List[str], is_cross: bool, select: int
79
+ ):
80
+ out = []
81
+ num_pixels = res ** 2
82
+ for location in from_where:
83
+ for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
84
+ if item.shape[1] == num_pixels:
85
+ cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
86
+ out.append(cross_maps)
87
+ out = torch.cat(out, dim=0)
88
+ # average over heads
89
+ out = out.sum(0) / out.shape[0]
90
+ return out
91
+
92
+ def __init__(self, average: bool):
93
+ self.step_store = self.get_empty_store()
94
+ self.attention_store = []
95
+ self.cur_step = 0
96
+ self.average = average
97
+
98
+ class CrossAttnProcessor:
99
+
100
+ def __init__(self, attention_store, place_in_unet, PnP, editing_prompts):
101
+ self.attnstore = attention_store
102
+ self.place_in_unet = place_in_unet
103
+ self.editing_prompts = editing_prompts
104
+ self.PnP = PnP
105
+
106
+ def __call__(
107
+ self,
108
+ attn: Attention,
109
+ hidden_states,
110
+ encoder_hidden_states=None,
111
+ attention_mask=None,
112
+ temb=None,
113
+ ):
114
+ assert(not attn.residual_connection)
115
+ assert(attn.spatial_norm is None)
116
+ assert(attn.group_norm is None)
117
+ assert(hidden_states.ndim != 4)
118
+ assert(encoder_hidden_states is not None) # is cross
119
+
120
+ batch_size, sequence_length, _ = (
121
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
122
+ )
123
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
124
+
125
+ query = attn.to_q(hidden_states)
126
+
127
+ if encoder_hidden_states is None:
128
+ encoder_hidden_states = hidden_states
129
+ elif attn.norm_cross:
130
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
131
+
132
+ key = attn.to_k(encoder_hidden_states)
133
+ value = attn.to_v(encoder_hidden_states)
134
+
135
+ query = attn.head_to_batch_dim(query)
136
+ key = attn.head_to_batch_dim(key)
137
+ value = attn.head_to_batch_dim(value)
138
+
139
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
140
+ self.attnstore(attention_probs,
141
+ is_cross=True,
142
+ place_in_unet=self.place_in_unet,
143
+ editing_prompts=self.editing_prompts,
144
+ PnP=self.PnP)
145
+
146
+ hidden_states = torch.bmm(attention_probs, value)
147
+ hidden_states = attn.batch_to_head_dim(hidden_states)
148
+
149
+ # linear proj
150
+ hidden_states = attn.to_out[0](hidden_states)
151
+ # dropout
152
+ hidden_states = attn.to_out[1](hidden_states)
153
+
154
+ hidden_states = hidden_states / attn.rescale_output_factor
155
+ return hidden_states
156
+
157
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
158
+ class GaussianSmoothing():
159
+
160
+ def __init__(self, device):
161
+ kernel_size = [3, 3]
162
+ sigma = [0.5, 0.5]
163
+
164
+ # The gaussian kernel is the product of the gaussian function of each dimension.
165
+ kernel = 1
166
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
167
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
168
+ mean = (size - 1) / 2
169
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
170
+
171
+ # Make sure sum of values in gaussian kernel equals 1.
172
+ kernel = kernel / torch.sum(kernel)
173
+
174
+ # Reshape to depthwise convolutional weight
175
+ kernel = kernel.view(1, 1, *kernel.size())
176
+ kernel = kernel.repeat(1, *[1] * (kernel.dim() - 1))
177
+
178
+ self.weight = kernel.to(device)
179
+
180
+ def __call__(self, input):
181
+ """
182
+ Arguments:
183
+ Apply gaussian filter to input.
184
+ input (torch.Tensor): Input to apply gaussian filter on.
185
+ Returns:
186
+ filtered (torch.Tensor): Filtered output.
187
+ """
188
+ return F.conv2d(input, weight=self.weight.to(input.dtype))
189
+
190
+ def load_512(image_path, size, left=0, right=0, top=0, bottom=0, device=None, dtype=None):
191
+ def pre_process(im, size, left=0, right=0, top=0, bottom=0):
192
+ if type(im) is str:
193
+ image = np.array(Image.open(im).convert('RGB'))[:, :, :3]
194
+ elif isinstance(im, Image.Image):
195
+ image = np.array((im).convert('RGB'))[:, :, :3]
196
+ else:
197
+ image = im
198
+ h, w, c = image.shape
199
+ left = min(left, w - 1)
200
+ right = min(right, w - left - 1)
201
+ top = min(top, h - left - 1)
202
+ bottom = min(bottom, h - top - 1)
203
+ image = image[top:h - bottom, left:w - right]
204
+ h, w, c = image.shape
205
+ if h < w:
206
+ offset = (w - h) // 2
207
+ image = image[:, offset:offset + h]
208
+ elif w < h:
209
+ offset = (h - w) // 2
210
+ image = image[offset:offset + w]
211
+ image = np.array(Image.fromarray(image).resize((size, size)))
212
+ image = torch.from_numpy(image).float().permute(2, 0, 1)
213
+ return image
214
+
215
+ tmps = []
216
+ if isinstance(image_path, list):
217
+ for item in image_path:
218
+ tmps.append(pre_process(item, size, left, right, top, bottom))
219
+ else:
220
+ tmps.append(pre_process(image_path, size, left, right, top, bottom))
221
+ image = torch.stack(tmps) / 127.5 - 1
222
+
223
+ image = image.to(device=device, dtype=dtype)
224
+ return image
225
+
226
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
227
+ def reset_dpm(scheduler):
228
+ if isinstance(scheduler, DPMSolverMultistepSchedulerInject):
229
+ scheduler.model_outputs = [
230
+ None,
231
+ ] * scheduler.config.solver_order
232
+ scheduler.lower_order_nums = 0
233
+
234
+ class SemanticStableDiffusionPipeline(DiffusionPipeline):
235
+ r"""
236
+ Pipeline for text-to-image generation with latent editing.
237
+
238
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
239
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
240
+
241
+ This model builds on the implementation of ['StableDiffusionPipeline']
242
+
243
+ Args:
244
+ vae ([`AutoencoderKL`]):
245
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
246
+ text_encoder ([`CLIPTextModel`]):
247
+ Frozen text-encoder. Stable Diffusion uses the text portion of
248
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
249
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
250
+ tokenizer (`CLIPTokenizer`):
251
+ Tokenizer of class
252
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
253
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
254
+ scheduler ([`SchedulerMixin`]):
255
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
256
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
257
+ safety_checker ([`Q16SafetyChecker`]):
258
+ Classification module that estimates whether generated images could be considered offensive or harmful.
259
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
260
+ feature_extractor ([`CLIPImageProcessor`]):
261
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
262
+ """
263
+
264
+ _optional_components = ["safety_checker", "feature_extractor"]
265
+
266
+ def __init__(
267
+ self,
268
+ vae: AutoencoderKL,
269
+ text_encoder: CLIPTextModel,
270
+ tokenizer: CLIPTokenizer,
271
+ unet: UNet2DConditionModel,
272
+ scheduler: KarrasDiffusionSchedulers,
273
+ safety_checker: StableDiffusionSafetyChecker,
274
+ feature_extractor: CLIPImageProcessor,
275
+ requires_safety_checker: bool = True,
276
+ ):
277
+ super().__init__()
278
+
279
+ if safety_checker is None and requires_safety_checker:
280
+ logger.warning(
281
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
282
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
283
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
284
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
285
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
286
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
287
+ )
288
+
289
+ if safety_checker is not None and feature_extractor is None:
290
+ raise ValueError(
291
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
292
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
293
+ )
294
+
295
+ self.register_modules(
296
+ vae=vae,
297
+ text_encoder=text_encoder,
298
+ tokenizer=tokenizer,
299
+ unet=unet,
300
+ scheduler=scheduler,
301
+ safety_checker=safety_checker,
302
+ feature_extractor=feature_extractor,
303
+ )
304
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
305
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
306
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
307
+
308
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
309
+ def run_safety_checker(self, image, device, dtype):
310
+ if self.safety_checker is None:
311
+ has_nsfw_concept = None
312
+ else:
313
+ if torch.is_tensor(image):
314
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
315
+ else:
316
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
317
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
318
+ image, has_nsfw_concept = self.safety_checker(
319
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
320
+ )
321
+ return image, has_nsfw_concept
322
+
323
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
324
+ def decode_latents(self, latents):
325
+ warnings.warn(
326
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
327
+ " use VaeImageProcessor instead",
328
+ FutureWarning,
329
+ )
330
+ latents = 1 / self.vae.config.scaling_factor * latents
331
+ image = self.vae.decode(latents, return_dict=False)[0]
332
+ image = (image / 2 + 0.5).clamp(0, 1)
333
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
334
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
335
+ return image
336
+
337
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
338
+ def prepare_extra_step_kwargs(self, generator, eta):
339
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
340
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
341
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
342
+ # and should be between [0, 1]
343
+
344
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
345
+ extra_step_kwargs = {}
346
+ if accepts_eta:
347
+ extra_step_kwargs["eta"] = eta
348
+
349
+ # check if the scheduler accepts generator
350
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
351
+ if accepts_generator:
352
+ extra_step_kwargs["generator"] = generator
353
+ return extra_step_kwargs
354
+
355
+
356
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
357
+ def check_inputs(
358
+ self,
359
+ prompt,
360
+ height,
361
+ width,
362
+ callback_steps,
363
+ negative_prompt=None,
364
+ prompt_embeds=None,
365
+ negative_prompt_embeds=None,
366
+ ):
367
+ if height % 8 != 0 or width % 8 != 0:
368
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
369
+
370
+ if (callback_steps is None) or (
371
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
372
+ ):
373
+ raise ValueError(
374
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
375
+ f" {type(callback_steps)}."
376
+ )
377
+
378
+ if prompt is not None and prompt_embeds is not None:
379
+ raise ValueError(
380
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
381
+ " only forward one of the two."
382
+ )
383
+ elif prompt is None and prompt_embeds is None:
384
+ raise ValueError(
385
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
386
+ )
387
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
388
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
389
+
390
+ if negative_prompt is not None and negative_prompt_embeds is not None:
391
+ raise ValueError(
392
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
393
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
394
+ )
395
+
396
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
397
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
398
+ raise ValueError(
399
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
400
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
401
+ f" {negative_prompt_embeds.shape}."
402
+ )
403
+
404
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
405
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
406
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
407
+ if isinstance(generator, list) and len(generator) != batch_size:
408
+ raise ValueError(
409
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
410
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
411
+ )
412
+
413
+ if latents is None:
414
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
415
+ else:
416
+ latents = latents.to(device)
417
+
418
+ # scale the initial noise by the standard deviation required by the scheduler
419
+ latents = latents * self.scheduler.init_noise_sigma
420
+ return latents
421
+
422
+ def prepare_unet(self, attention_store, PnP: bool):
423
+ attn_procs = {}
424
+ for name in self.unet.attn_processors.keys():
425
+ if name.startswith("mid_block"):
426
+ place_in_unet = "mid"
427
+ elif name.startswith("up_blocks"):
428
+ place_in_unet = "up"
429
+ elif name.startswith("down_blocks"):
430
+ place_in_unet = "down"
431
+ else:
432
+ continue
433
+
434
+ if "attn2" in name:
435
+ attn_procs[name] = CrossAttnProcessor(
436
+ attention_store=attention_store,
437
+ place_in_unet=place_in_unet,
438
+ PnP=PnP,
439
+ editing_prompts=self.enabled_editing_prompts)
440
+ else:
441
+ attn_procs[name] = AttnProcessor()
442
+
443
+ self.unet.set_attn_processor(attn_procs)
444
+
445
+ @torch.no_grad()
446
+ def __call__(
447
+ self,
448
+ prompt: Union[str, List[str]],
449
+ height: Optional[int] = None,
450
+ width: Optional[int] = None,
451
+ num_inference_steps: int = 50,
452
+ guidance_scale: float = 7.5,
453
+ negative_prompt: Optional[Union[str, List[str]]] = None,
454
+ num_images_per_prompt: int = 1,
455
+ eta: float = 0.0,
456
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
457
+ latents: Optional[torch.FloatTensor] = None,
458
+ output_type: Optional[str] = "pil",
459
+ return_dict: bool = True,
460
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
461
+ callback_steps: int = 1,
462
+ editing_prompt: Optional[Union[str, List[str]]] = None,
463
+ editing_prompt_embeddings: Optional[torch.Tensor] = None,
464
+ reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
465
+ edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
466
+ edit_warmup_steps: Optional[Union[int, List[int]]] = 10,
467
+ edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
468
+ edit_threshold: Optional[Union[float, List[float]]] = 0.9,
469
+ edit_momentum_scale: Optional[float] = 0.1,
470
+ edit_mom_beta: Optional[float] = 0.4,
471
+ edit_weights: Optional[List[float]] = None,
472
+ sem_guidance: Optional[List[torch.Tensor]] = None,
473
+
474
+ # masking
475
+ use_cross_attn_mask: bool = False,
476
+ use_intersect_mask: bool = True,
477
+ edit_tokens_for_attn_map: List[str] = None,
478
+
479
+ # Attention store (just for visualization purposes)
480
+ attn_store_steps: Optional[List[int]] = [],
481
+ store_averaged_over_steps: bool = True,
482
+
483
+ # DDPM additions
484
+ use_ddpm: bool = False,
485
+ wts: Optional[List[torch.Tensor]] = None,
486
+ zs: Optional[List[torch.Tensor]] = None
487
+ ):
488
+ r"""
489
+ Function invoked when calling the pipeline for generation.
490
+
491
+ Args:
492
+ prompt (`str` or `List[str]`):
493
+ The prompt or prompts to guide the image generation.
494
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
495
+ The height in pixels of the generated image.
496
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
497
+ The width in pixels of the generated image.
498
+ num_inference_steps (`int`, *optional*, defaults to 50):
499
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
500
+ expense of slower inference.
501
+ guidance_scale (`float`, *optional*, defaults to 7.5):
502
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
503
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
504
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
505
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
506
+ usually at the expense of lower image quality.
507
+ negative_prompt (`str` or `List[str]`, *optional*):
508
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
509
+ if `guidance_scale` is less than `1`).
510
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
511
+ The number of images to generate per prompt.
512
+ eta (`float`, *optional*, defaults to 0.0):
513
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
514
+ [`schedulers.DDIMScheduler`], will be ignored for others.
515
+ generator (`torch.Generator`, *optional*):
516
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
517
+ to make generation deterministic.
518
+ latents (`torch.FloatTensor`, *optional*):
519
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
520
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
521
+ tensor will ge generated by sampling using the supplied random `generator`.
522
+ output_type (`str`, *optional*, defaults to `"pil"`):
523
+ The output format of the generate image. Choose between
524
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
525
+ return_dict (`bool`, *optional*, defaults to `True`):
526
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
527
+ plain tuple.
528
+ callback (`Callable`, *optional*):
529
+ A function that will be called every `callback_steps` steps during inference. The function will be
530
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
531
+ callback_steps (`int`, *optional*, defaults to 1):
532
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
533
+ called at every step.
534
+ editing_prompt (`str` or `List[str]`, *optional*):
535
+ The prompt or prompts to use for Semantic guidance. Semantic guidance is disabled by setting
536
+ `editing_prompt = None`. Guidance direction of prompt should be specified via
537
+ `reverse_editing_direction`.
538
+ editing_prompt_embeddings (`torch.Tensor>`, *optional*):
539
+ Pre-computed embeddings to use for semantic guidance. Guidance direction of embedding should be
540
+ specified via `reverse_editing_direction`.
541
+ reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
542
+ Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
543
+ edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
544
+ Guidance scale for semantic guidance. If provided as list values should correspond to `editing_prompt`.
545
+ `edit_guidance_scale` is defined as `s_e` of equation 6 of [SEGA
546
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
547
+ edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
548
+ Number of diffusion steps (for each prompt) for which semantic guidance will not be applied. Momentum
549
+ will still be calculated for those steps and applied once all warmup periods are over.
550
+ `edit_warmup_steps` is defined as `delta` (δ) of [SEGA Paper](https://arxiv.org/pdf/2301.12247.pdf).
551
+ edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
552
+ Number of diffusion steps (for each prompt) after which semantic guidance will no longer be applied.
553
+ edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
554
+ Threshold of semantic guidance.
555
+ edit_momentum_scale (`float`, *optional*, defaults to 0.1):
556
+ Scale of the momentum to be added to the semantic guidance at each diffusion step. If set to 0.0
557
+ momentum will be disabled. Momentum is already built up during warmup, i.e. for diffusion steps smaller
558
+ than `sld_warmup_steps`. Momentum will only be added to latent guidance once all warmup periods are
559
+ finished. `edit_momentum_scale` is defined as `s_m` of equation 7 of [SEGA
560
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
561
+ edit_mom_beta (`float`, *optional*, defaults to 0.4):
562
+ Defines how semantic guidance momentum builds up. `edit_mom_beta` indicates how much of the previous
563
+ momentum will be kept. Momentum is already built up during warmup, i.e. for diffusion steps smaller
564
+ than `edit_warmup_steps`. `edit_mom_beta` is defined as `beta_m` (β) of equation 8 of [SEGA
565
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
566
+ edit_weights (`List[float]`, *optional*, defaults to `None`):
567
+ Indicates how much each individual concept should influence the overall guidance. If no weights are
568
+ provided all concepts are applied equally. `edit_mom_beta` is defined as `g_i` of equation 9 of [SEGA
569
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
570
+ sem_guidance (`List[torch.Tensor]`, *optional*):
571
+ List of pre-generated guidance vectors to be applied at generation. Length of the list has to
572
+ correspond to `num_inference_steps`.
573
+
574
+ Returns:
575
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] or `tuple`:
576
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] if `return_dict` is True,
577
+ otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the
578
+ second element is a list of `bool`s denoting whether the corresponding generated image likely represents
579
+ "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
580
+ """
581
+ if use_intersect_mask:
582
+ use_cross_attn_mask = True
583
+
584
+ if use_cross_attn_mask:
585
+ self.smoothing = GaussianSmoothing(self.device)
586
+
587
+ # 0. Default height and width to unet
588
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
589
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
590
+
591
+ # 1. Check inputs. Raise error if not correct
592
+ self.check_inputs(prompt, height, width, callback_steps)
593
+
594
+ if use_ddpm:
595
+ reset_dpm(self.scheduler)
596
+
597
+ # 2. Define call parameters
598
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
599
+
600
+ if editing_prompt:
601
+ enable_edit_guidance = True
602
+ if isinstance(editing_prompt, str):
603
+ editing_prompt = [editing_prompt]
604
+ self.enabled_editing_prompts = len(editing_prompt)
605
+ elif editing_prompt_embeddings is not None:
606
+ enable_edit_guidance = True
607
+ self.enabled_editing_prompts = editing_prompt_embeddings.shape[0]
608
+ else:
609
+ self.enabled_editing_prompts = 0
610
+ enable_edit_guidance = False
611
+
612
+ # get prompt text embeddings
613
+ text_inputs = self.tokenizer(
614
+ prompt,
615
+ padding="max_length",
616
+ max_length=self.tokenizer.model_max_length,
617
+ truncation=True,
618
+ return_tensors="pt",
619
+ )
620
+ text_input_ids = text_inputs.input_ids
621
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
622
+
623
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
624
+ text_input_ids, untruncated_ids
625
+ ):
626
+ removed_text = self.tokenizer.batch_decode(
627
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
628
+ )
629
+ logger.warning(
630
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
631
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
632
+ )
633
+
634
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
635
+
636
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
637
+ bs_embed, seq_len, _ = text_embeddings.shape
638
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
639
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
640
+
641
+ if enable_edit_guidance:
642
+ # get safety text embeddings
643
+ if editing_prompt_embeddings is None:
644
+ if edit_tokens_for_attn_map is not None:
645
+ edit_tokens = [[word.replace("</w>", "") for word in self.tokenizer.tokenize(item)] for item in editing_prompt]
646
+ #print(f"edit_tokens: {edit_tokens}")
647
+
648
+ edit_concepts_input = self.tokenizer(
649
+ [x for item in editing_prompt for x in repeat(item, batch_size)],
650
+ padding="max_length",
651
+ max_length=self.tokenizer.model_max_length,
652
+ truncation=True,
653
+ return_tensors="pt",
654
+ return_length=True
655
+ )
656
+
657
+ num_edit_tokens = edit_concepts_input.length -2 # not counting startoftext and endoftext
658
+ edit_concepts_input_ids = edit_concepts_input.input_ids
659
+ untruncated_ids = self.tokenizer(
660
+ [x for item in editing_prompt for x in repeat(item, batch_size)],
661
+ padding="longest",
662
+ return_tensors="pt").input_ids
663
+
664
+ if untruncated_ids.shape[-1] >= edit_concepts_input_ids.shape[-1] and not torch.equal(
665
+ edit_concepts_input_ids, untruncated_ids
666
+ ):
667
+ removed_text = self.tokenizer.batch_decode(
668
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
669
+ )
670
+ logger.warning(
671
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
672
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
673
+ )
674
+
675
+ edit_concepts = self.text_encoder(edit_concepts_input_ids.to(self.device))[0]
676
+ else:
677
+ edit_concepts = editing_prompt_embeddings.to(self.device).repeat(batch_size, 1, 1)
678
+
679
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
680
+ bs_embed_edit, seq_len_edit, _ = edit_concepts.shape
681
+ edit_concepts = edit_concepts.repeat(1, num_images_per_prompt, 1)
682
+ edit_concepts = edit_concepts.view(bs_embed_edit * num_images_per_prompt, seq_len_edit, -1)
683
+
684
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
685
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
686
+ # corresponds to doing no classifier free guidance.
687
+ do_classifier_free_guidance = guidance_scale > 1.0
688
+ # get unconditional embeddings for classifier free guidance
689
+
690
+ if do_classifier_free_guidance:
691
+ uncond_tokens: List[str]
692
+ if negative_prompt is None:
693
+ uncond_tokens = [""]
694
+ elif type(prompt) is not type(negative_prompt):
695
+ raise TypeError(
696
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
697
+ f" {type(prompt)}."
698
+ )
699
+ elif isinstance(negative_prompt, str):
700
+ uncond_tokens = [negative_prompt]
701
+ elif batch_size != len(negative_prompt):
702
+ raise ValueError(
703
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
704
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
705
+ " the batch size of `prompt`."
706
+ )
707
+ else:
708
+ uncond_tokens = negative_prompt
709
+
710
+ max_length = text_input_ids.shape[-1]
711
+ uncond_input = self.tokenizer(
712
+ uncond_tokens,
713
+ padding="max_length",
714
+ max_length=max_length,
715
+ truncation=True,
716
+ return_tensors="pt",
717
+ )
718
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
719
+
720
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
721
+ seq_len = uncond_embeddings.shape[1]
722
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
723
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
724
+
725
+ # For classifier free guidance, we need to do two forward passes.
726
+ # Here we concatenate the unconditional and text embeddings into a single batch
727
+ # to avoid doing two forward passes
728
+ self.text_cross_attention_maps = [prompt] if isinstance(prompt, str) else prompt
729
+ if enable_edit_guidance:
730
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings, edit_concepts])
731
+ self.text_cross_attention_maps += \
732
+ ([editing_prompt] if isinstance(editing_prompt, str) else editing_prompt)
733
+ else:
734
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
735
+ # get the initial random noise unless the user supplied it
736
+
737
+ # 4. Prepare timesteps
738
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
739
+ timesteps = self.scheduler.timesteps
740
+ if use_ddpm:
741
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps[-zs.shape[0]:])}
742
+ timesteps = timesteps[-zs.shape[0]:]
743
+
744
+ self.attention_store = AttentionStore(average=store_averaged_over_steps)
745
+ self.prepare_unet(self.attention_store, False)
746
+
747
+ # 5. Prepare latent variables
748
+ num_channels_latents = self.unet.config.in_channels
749
+ latents = self.prepare_latents(
750
+ batch_size * num_images_per_prompt,
751
+ num_channels_latents,
752
+ height,
753
+ width,
754
+ text_embeddings.dtype,
755
+ self.device,
756
+ generator,
757
+ latents,
758
+ )
759
+
760
+ # 6. Prepare extra step kwargs.
761
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
762
+
763
+ # Initialize edit_momentum to None
764
+ edit_momentum = None
765
+
766
+ self.uncond_estimates = None
767
+ self.text_estimates = None
768
+ self.edit_estimates = None
769
+ self.sem_guidance = None
770
+
771
+ for i, t in enumerate(self.progress_bar(timesteps)):
772
+ # expand the latents if we are doing classifier free guidance
773
+ latent_model_input = (
774
+ torch.cat([latents] * (2 + self.enabled_editing_prompts)) if do_classifier_free_guidance else latents
775
+ )
776
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
777
+
778
+ # predict the noise residual
779
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
780
+
781
+ # perform guidance
782
+ if do_classifier_free_guidance:
783
+ noise_pred_out = noise_pred.chunk(2 + self.enabled_editing_prompts) # [b,4, 64, 64]
784
+ noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
785
+ noise_pred_edit_concepts = noise_pred_out[2:]
786
+
787
+ # default text guidance
788
+ noise_guidance = guidance_scale * (noise_pred_text - noise_pred_uncond)
789
+ # noise_guidance = (noise_pred_text - noise_pred_edit_concepts[0])
790
+
791
+ if self.uncond_estimates is None:
792
+ self.uncond_estimates = torch.zeros((num_inference_steps + 1, *noise_pred_uncond.shape))
793
+ self.uncond_estimates[i] = noise_pred_uncond.detach().cpu()
794
+
795
+ if self.text_estimates is None:
796
+ self.text_estimates = torch.zeros((num_inference_steps + 1, *noise_pred_text.shape))
797
+ self.text_estimates[i] = noise_pred_text.detach().cpu()
798
+
799
+ if self.edit_estimates is None and enable_edit_guidance:
800
+ self.edit_estimates = torch.zeros(
801
+ (num_inference_steps + 1, len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
802
+ )
803
+
804
+ if self.sem_guidance is None:
805
+ self.sem_guidance = torch.zeros((num_inference_steps + 1, *noise_pred_text.shape))
806
+
807
+ if edit_momentum is None:
808
+ edit_momentum = torch.zeros_like(noise_guidance)
809
+
810
+ if enable_edit_guidance:
811
+ concept_weights = torch.zeros(
812
+ (len(noise_pred_edit_concepts), noise_guidance.shape[0]),
813
+ device=self.device,
814
+ dtype=noise_guidance.dtype,
815
+ )
816
+ noise_guidance_edit = torch.zeros(
817
+ (len(noise_pred_edit_concepts), *noise_guidance.shape),
818
+ device=self.device,
819
+ dtype=noise_guidance.dtype,
820
+ )
821
+ # noise_guidance_edit = torch.zeros_like(noise_guidance)
822
+ warmup_inds = []
823
+ for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
824
+ self.edit_estimates[i, c] = noise_pred_edit_concept
825
+ if isinstance(edit_guidance_scale, list):
826
+ edit_guidance_scale_c = edit_guidance_scale[c]
827
+ else:
828
+ edit_guidance_scale_c = edit_guidance_scale
829
+
830
+ if isinstance(edit_threshold, list):
831
+ edit_threshold_c = edit_threshold[c]
832
+ else:
833
+ edit_threshold_c = edit_threshold
834
+ if isinstance(reverse_editing_direction, list):
835
+ reverse_editing_direction_c = reverse_editing_direction[c]
836
+ else:
837
+ reverse_editing_direction_c = reverse_editing_direction
838
+ if edit_weights:
839
+ edit_weight_c = edit_weights[c]
840
+ else:
841
+ edit_weight_c = 1.0
842
+ if isinstance(edit_warmup_steps, list):
843
+ edit_warmup_steps_c = edit_warmup_steps[c]
844
+ else:
845
+ edit_warmup_steps_c = edit_warmup_steps
846
+
847
+ if isinstance(edit_cooldown_steps, list):
848
+ edit_cooldown_steps_c = edit_cooldown_steps[c]
849
+ elif edit_cooldown_steps is None:
850
+ edit_cooldown_steps_c = i + 1
851
+ else:
852
+ edit_cooldown_steps_c = edit_cooldown_steps
853
+ if i >= edit_warmup_steps_c:
854
+ warmup_inds.append(c)
855
+ if i >= edit_cooldown_steps_c:
856
+ noise_guidance_edit[c, :, :, :, :] = torch.zeros_like(noise_pred_edit_concept)
857
+ continue
858
+
859
+ noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
860
+ # tmp_weights = (noise_pred_text - noise_pred_edit_concept).sum(dim=(1, 2, 3))
861
+ tmp_weights = (noise_guidance - noise_pred_edit_concept).sum(dim=(1, 2, 3))
862
+
863
+ tmp_weights = torch.full_like(tmp_weights, edit_weight_c) # * (1 / enabled_editing_prompts)
864
+ if reverse_editing_direction_c:
865
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
866
+ concept_weights[c, :] = tmp_weights
867
+
868
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
869
+
870
+ if use_cross_attn_mask:
871
+ out = self.attention_store.aggregate_attention(
872
+ attention_maps=self.attention_store.step_store,
873
+ prompts=self.text_cross_attention_maps,
874
+ res=16,
875
+ from_where=["up","down"],
876
+ is_cross=True,
877
+ select=self.text_cross_attention_maps.index(editing_prompt[c]),
878
+ )
879
+
880
+ attn_map = out[:, :, 1:] # 0 -> startoftext
881
+ attn_map *= 100
882
+ attn_map = torch.nn.functional.softmax(attn_map, dim=-1)
883
+ attn_map = attn_map[:,:,:num_edit_tokens[c]] # -1 -> endoftext
884
+
885
+ assert(attn_map.shape[2]==num_edit_tokens[c])
886
+ if edit_tokens_for_attn_map is not None:
887
+ # select attn_map for specified tokens
888
+ token_idx = [edit_tokens[c].index(item) for item in edit_tokens_for_attn_map[c]]
889
+ attn_map = attn_map[:,:,token_idx]
890
+ assert(attn_map.shape[2] == len(edit_tokens_for_attn_map[c]))
891
+
892
+ # average over tokens
893
+ attn_map = torch.sum(attn_map, dim=2)
894
+
895
+ # gaussian_smoothing
896
+ attn_map = F.pad(attn_map.unsqueeze(0).unsqueeze(0), (1, 1, 1, 1), mode="reflect")
897
+ attn_map = self.smoothing(attn_map).squeeze(0).squeeze(0)
898
+
899
+ # torch.quantile function expects float32
900
+ if attn_map.dtype == torch.float32:
901
+ tmp = torch.quantile(
902
+ attn_map.flatten(),
903
+ edit_threshold_c
904
+ )
905
+ else:
906
+ tmp = torch.quantile(
907
+ attn_map.flatten().to(torch.float32),
908
+ edit_threshold_c
909
+ ).to(attn_map.dtype)
910
+
911
+ attn_mask = torch.where(attn_map >= tmp, 1.0, 0.0)
912
+
913
+ # resolution must match latent space dimension
914
+ attn_mask = F.interpolate(
915
+ attn_mask.unsqueeze(0).unsqueeze(0),
916
+ noise_guidance_edit_tmp.shape[-2:] # 64,64
917
+ )[0,0,:,:]
918
+
919
+ if not use_intersect_mask:
920
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
921
+
922
+ if use_intersect_mask:
923
+ noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
924
+ noise_guidance_edit_tmp_quantile = torch.sum(noise_guidance_edit_tmp_quantile, dim=1, keepdim=True)
925
+ noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1,4,1,1)
926
+
927
+ if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
928
+ tmp = torch.quantile(
929
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
930
+ edit_threshold_c,
931
+ dim=2,
932
+ keepdim=False,
933
+ )
934
+ else:
935
+ tmp = torch.quantile(
936
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
937
+ edit_threshold_c,
938
+ dim=2,
939
+ keepdim=False,
940
+ ).to(noise_guidance_edit_tmp_quantile.dtype)
941
+
942
+ sega_mask = torch.where(
943
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
944
+ torch.ones_like(noise_guidance_edit_tmp),
945
+ torch.zeros_like(noise_guidance_edit_tmp),
946
+ )
947
+
948
+ intersect_mask = sega_mask * attn_mask
949
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * intersect_mask
950
+
951
+ elif not use_cross_attn_mask:
952
+ # calculate quantile
953
+ noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
954
+ noise_guidance_edit_tmp_quantile = torch.sum(noise_guidance_edit_tmp_quantile, dim=1, keepdim=True)
955
+ noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1,4,1,1)
956
+
957
+ # torch.quantile function expects float32
958
+ if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
959
+ tmp = torch.quantile(
960
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
961
+ edit_threshold_c,
962
+ dim=2,
963
+ keepdim=False,
964
+ )
965
+ else:
966
+ tmp = torch.quantile(
967
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
968
+ edit_threshold_c,
969
+ dim=2,
970
+ keepdim=False,
971
+ ).to(noise_guidance_edit_tmp_quantile.dtype)
972
+
973
+ noise_guidance_edit_tmp = torch.where(
974
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
975
+ noise_guidance_edit_tmp,
976
+ torch.zeros_like(noise_guidance_edit_tmp),
977
+ )
978
+
979
+ noise_guidance_edit[c, :, :, :, :] = noise_guidance_edit_tmp
980
+
981
+ # noise_guidance_edit = noise_guidance_edit + noise_guidance_edit_tmp
982
+
983
+ warmup_inds = torch.tensor(warmup_inds).to(self.device)
984
+ if len(noise_pred_edit_concepts) > warmup_inds.shape[0] > 0:
985
+ concept_weights = concept_weights.to("cpu") # Offload to cpu
986
+ noise_guidance_edit = noise_guidance_edit.to("cpu")
987
+
988
+ concept_weights_tmp = torch.index_select(concept_weights.to(self.device), 0, warmup_inds)
989
+ concept_weights_tmp = torch.where(
990
+ concept_weights_tmp < 0, torch.zeros_like(concept_weights_tmp), concept_weights_tmp
991
+ )
992
+ concept_weights_tmp = concept_weights_tmp / concept_weights_tmp.sum(dim=0)
993
+ # concept_weights_tmp = torch.nan_to_num(concept_weights_tmp)
994
+
995
+ noise_guidance_edit_tmp = torch.index_select(
996
+ noise_guidance_edit.to(self.device), 0, warmup_inds
997
+ )
998
+ noise_guidance_edit_tmp = torch.einsum(
999
+ "cb,cbijk->bijk", concept_weights_tmp, noise_guidance_edit_tmp
1000
+ )
1001
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp
1002
+ noise_guidance = noise_guidance + noise_guidance_edit_tmp
1003
+
1004
+ self.sem_guidance[i] = noise_guidance_edit_tmp.detach().cpu()
1005
+
1006
+ del noise_guidance_edit_tmp
1007
+ del concept_weights_tmp
1008
+ concept_weights = concept_weights.to(self.device)
1009
+ noise_guidance_edit = noise_guidance_edit.to(self.device)
1010
+
1011
+ concept_weights = torch.where(
1012
+ concept_weights < 0, torch.zeros_like(concept_weights), concept_weights
1013
+ )
1014
+
1015
+ concept_weights = torch.nan_to_num(concept_weights)
1016
+
1017
+ noise_guidance_edit = torch.einsum("cb,cbijk->bijk", concept_weights, noise_guidance_edit)
1018
+
1019
+ noise_guidance_edit = noise_guidance_edit + edit_momentum_scale * edit_momentum
1020
+
1021
+ edit_momentum = edit_mom_beta * edit_momentum + (1 - edit_mom_beta) * noise_guidance_edit
1022
+
1023
+ if warmup_inds.shape[0] == len(noise_pred_edit_concepts):
1024
+ noise_guidance = noise_guidance + noise_guidance_edit
1025
+ self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
1026
+
1027
+ if sem_guidance is not None:
1028
+ edit_guidance = sem_guidance[i].to(self.device)
1029
+ noise_guidance = noise_guidance + edit_guidance
1030
+
1031
+ noise_pred = noise_pred_uncond + noise_guidance
1032
+ ## ddpm ###########################################################
1033
+ if use_ddpm:
1034
+ idx = t_to_idx[int(t)]
1035
+ latents = self.scheduler.step(noise_pred, t, latents, variance_noise=zs[idx],
1036
+ **extra_step_kwargs).prev_sample
1037
+
1038
+ ## ddpm ##########################################################
1039
+ # compute the previous noisy sample x_t -> x_t-1
1040
+ else: #if not use_ddpm:
1041
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1042
+
1043
+ # step callback
1044
+ store_step = i in attn_store_steps
1045
+ if store_step:
1046
+ print("storing attention")
1047
+ self.attention_store.between_steps(store_step)
1048
+
1049
+ # call the callback, if provided
1050
+ if callback is not None and i % callback_steps == 0:
1051
+ callback(i, t, latents)
1052
+
1053
+ # 8. Post-processing
1054
+ if not output_type == "latent":
1055
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1056
+ image, has_nsfw_concept = self.run_safety_checker(image, self.device, text_embeddings.dtype)
1057
+ else:
1058
+ image = latents
1059
+ has_nsfw_concept = None
1060
+
1061
+ if has_nsfw_concept is None:
1062
+ do_denormalize = [True] * image.shape[0]
1063
+ else:
1064
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1065
+
1066
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1067
+
1068
+ if not return_dict:
1069
+ return (image, has_nsfw_concept)
1070
+
1071
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1072
+
1073
+ def encode_text(self, prompts):
1074
+ text_inputs = self.tokenizer(
1075
+ prompts,
1076
+ padding="max_length",
1077
+ max_length=self.tokenizer.model_max_length,
1078
+ return_tensors="pt",
1079
+ )
1080
+ text_input_ids = text_inputs.input_ids
1081
+
1082
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
1083
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length:])
1084
+ logger.warning(
1085
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
1086
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
1087
+ )
1088
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
1089
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
1090
+
1091
+ return text_embeddings
1092
+
1093
+ @torch.no_grad()
1094
+ def invert(self,
1095
+ image_path: str,
1096
+ source_prompt: str = "",
1097
+ source_guidance_scale=3.5,
1098
+ num_inversion_steps: int = 30,
1099
+ skip: float = 0.15,
1100
+ eta: float = 1.0,
1101
+ generator: Optional[torch.Generator] = None,
1102
+ verbose=True,
1103
+ ):
1104
+ """
1105
+ Inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
1106
+ based on the code in https://github.com/inbarhub/DDPM_inversion
1107
+
1108
+ returns:
1109
+ zs - noise maps
1110
+ xts - intermediate inverted latents
1111
+ """
1112
+
1113
+ # self.eta = eta
1114
+ # assert (self.eta > 0)
1115
+
1116
+ train_steps = self.scheduler.config.num_train_timesteps
1117
+ timesteps = torch.from_numpy(
1118
+ np.linspace(train_steps - skip * train_steps - 1, 1, num_inversion_steps).astype(np.int64)).to(self.device)
1119
+
1120
+
1121
+ num_inversion_steps = timesteps.shape[0]
1122
+ self.scheduler.num_inference_steps = timesteps.shape[0]
1123
+ self.scheduler.timesteps = timesteps
1124
+
1125
+
1126
+ # 1. get embeddings
1127
+
1128
+ uncond_embedding = self.encode_text("")
1129
+
1130
+ # 2. encode image
1131
+ x0 = self.encode_image(image_path, dtype=uncond_embedding.dtype)
1132
+ batch_size = x0.shape[0]
1133
+
1134
+ if not source_prompt == "":
1135
+ text_embeddings = self.encode_text(source_prompt).repeat((batch_size, 1, 1))
1136
+ uncond_embedding = uncond_embedding.repeat((batch_size, 1, 1))
1137
+ # autoencoder reconstruction
1138
+ # image_rec = self.vae.decode(x0 / self.vae.config.scaling_factor, return_dict=False)[0]
1139
+ # image_rec = self.image_processor.postprocess(image_rec, output_type="pil")
1140
+
1141
+ # 3. find zs and xts
1142
+ variance_noise_shape = (
1143
+ num_inversion_steps,
1144
+ batch_size,
1145
+ self.unet.config.in_channels,
1146
+ self.unet.sample_size,
1147
+ self.unet.sample_size)
1148
+
1149
+ # intermediate latents
1150
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
1151
+ xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
1152
+
1153
+ for t in reversed(timesteps):
1154
+ idx = num_inversion_steps-t_to_idx[int(t)] - 1
1155
+ noise = randn_tensor(shape=x0.shape, generator=generator, device=self.device, dtype=x0.dtype)
1156
+ xts[idx] = self.scheduler.add_noise(x0, noise, t)
1157
+ xts = torch.cat([x0.unsqueeze(0), xts], dim=0)
1158
+
1159
+ reset_dpm(self.scheduler)
1160
+ # noise maps
1161
+ zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
1162
+
1163
+ for t in self.progress_bar(timesteps, verbose=verbose):
1164
+
1165
+ idx = num_inversion_steps-t_to_idx[int(t)]-1
1166
+ # 1. predict noise residual
1167
+ xt = xts[idx+1]
1168
+
1169
+ noise_pred = self.unet(xt, timestep=t, encoder_hidden_states=uncond_embedding).sample
1170
+
1171
+ if not source_prompt == "":
1172
+ noise_pred_cond = self.unet(xt, timestep=t, encoder_hidden_states=text_embeddings).sample
1173
+ noise_pred = noise_pred + source_guidance_scale * (noise_pred_cond - noise_pred)
1174
+
1175
+ xtm1 = xts[idx]
1176
+ z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, eta)
1177
+ zs[idx] = z
1178
+
1179
+ # correction to avoid error accumulation
1180
+ xts[idx] = xtm1_corrected
1181
+
1182
+ # TODO: I don't think that the noise map for the last step should be discarded ?!
1183
+ # if not zs is None:
1184
+ # zs[-1] = torch.zeros_like(zs[-1])
1185
+ # self.init_latents = xts[-1].expand(self.batch_size, -1, -1, -1)
1186
+ zs = zs.flip(0)
1187
+ # self.zs = zs
1188
+
1189
+
1190
+ return zs, xts
1191
+ # return zs, xts, image_rec
1192
+
1193
+ @torch.no_grad()
1194
+ def encode_image(self, image_path, dtype=None):
1195
+ image = load_512(image_path,
1196
+ size=self.unet.sample_size * self.vae_scale_factor,
1197
+ device=self.device,
1198
+ dtype=dtype)
1199
+ x0 = self.vae.encode(image).latent_dist.mode()
1200
+ x0 = self.vae.config.scaling_factor * x0
1201
+ return x0
1202
+
1203
+ def compute_noise_ddim(scheduler, prev_latents, latents, timestep, noise_pred, eta):
1204
+ # 1. get previous step value (=t-1)
1205
+ prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
1206
+
1207
+ # 2. compute alphas, betas
1208
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
1209
+ alpha_prod_t_prev = (
1210
+ scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
1211
+ )
1212
+
1213
+ beta_prod_t = 1 - alpha_prod_t
1214
+
1215
+ # 3. compute predicted original sample from predicted noise also called
1216
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1217
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
1218
+
1219
+ # 4. Clip "predicted x_0"
1220
+ if scheduler.config.clip_sample:
1221
+ pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
1222
+
1223
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
1224
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
1225
+ variance = scheduler._get_variance(timestep, prev_timestep)
1226
+ std_dev_t = eta * variance ** (0.5)
1227
+
1228
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1229
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t ** 2) ** (0.5) * noise_pred
1230
+
1231
+ # modifed so that updated xtm1 is returned as well (to avoid error accumulation)
1232
+ mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
1233
+ noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
1234
+
1235
+ return noise, mu_xt + (eta * variance ** 0.5) * noise
1236
+
1237
+ # Copied from pipelines.StableDiffusion.CycleDiffusionPipeline.compute_noise
1238
+ def compute_noise_sde_dpm_pp_2nd(scheduler, prev_latents, latents, timestep, noise_pred, eta):
1239
+
1240
+ def first_order_update(model_output, timestep, prev_timestep, sample):
1241
+ lambda_t, lambda_s = scheduler.lambda_t[prev_timestep], scheduler.lambda_t[timestep]
1242
+ alpha_t, alpha_s = scheduler.alpha_t[prev_timestep], scheduler.alpha_t[timestep]
1243
+ sigma_t, sigma_s = scheduler.sigma_t[prev_timestep], scheduler.sigma_t[timestep]
1244
+ h = lambda_t - lambda_s
1245
+
1246
+ mu_xt = (
1247
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
1248
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
1249
+ )
1250
+ sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
1251
+
1252
+ noise = (prev_latents - mu_xt) / sigma
1253
+
1254
+ prev_sample = mu_xt + sigma * noise
1255
+
1256
+ return noise, prev_sample
1257
+ def second_order_update(model_output_list, timestep_list, prev_timestep, sample):
1258
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
1259
+ m0, m1 = model_output_list[-1], model_output_list[-2]
1260
+ lambda_t, lambda_s0, lambda_s1 = scheduler.lambda_t[t], scheduler.lambda_t[s0], scheduler.lambda_t[s1]
1261
+ alpha_t, alpha_s0 = scheduler.alpha_t[t], scheduler.alpha_t[s0]
1262
+ sigma_t, sigma_s0 = scheduler.sigma_t[t], scheduler.sigma_t[s0]
1263
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
1264
+ r0 = h_0 / h
1265
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
1266
+
1267
+ mu_xt = (
1268
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
1269
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
1270
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
1271
+ )
1272
+ sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
1273
+
1274
+ noise = (prev_latents - mu_xt) / sigma
1275
+
1276
+ prev_sample = mu_xt + sigma * noise
1277
+
1278
+ return noise, prev_sample
1279
+
1280
+ step_index = (scheduler.timesteps == timestep).nonzero()
1281
+ if len(step_index) == 0:
1282
+ step_index = len(scheduler.timesteps) - 1
1283
+ else:
1284
+ step_index = step_index.item()
1285
+
1286
+ prev_timestep = 0 if step_index == len(scheduler.timesteps) - 1 else scheduler.timesteps[step_index + 1]
1287
+
1288
+ model_output = scheduler.convert_model_output(noise_pred, timestep, latents)
1289
+
1290
+ for i in range(scheduler.config.solver_order - 1):
1291
+ scheduler.model_outputs[i] = scheduler.model_outputs[i + 1]
1292
+ scheduler.model_outputs[-1] = model_output
1293
+
1294
+ if scheduler.lower_order_nums < 1:
1295
+ noise, prev_sample = first_order_update(model_output, timestep, prev_timestep, latents)
1296
+ else:
1297
+ timestep_list = [scheduler.timesteps[step_index - 1], timestep]
1298
+ noise, prev_sample = second_order_update(scheduler.model_outputs, timestep_list, prev_timestep, latents)
1299
+
1300
+ if scheduler.lower_order_nums < scheduler.config.solver_order:
1301
+ scheduler.lower_order_nums += 1
1302
+
1303
+ return noise, prev_sample
1304
+
1305
+ def compute_noise(scheduler, *args):
1306
+ if isinstance(scheduler, DDIMScheduler):
1307
+ return compute_noise_ddim(scheduler, *args)
1308
+ elif isinstance(scheduler, DPMSolverMultistepSchedulerInject) and scheduler.config.algorithm_type == 'sde-dpmsolver++'\
1309
+ and scheduler.config.solver_order == 2:
1310
+ return compute_noise_sde_dpm_pp_2nd(scheduler, *args)
1311
+ else:
1312
+ raise NotImplementedError
pipeline_semantic_stable_diffusion_img2img_solver.py ADDED
@@ -0,0 +1,1350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import warnings
3
+ from itertools import repeat
4
+ from typing import Callable, List, Optional, Union
5
+
6
+ import torch
7
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers.image_processor import VaeImageProcessor
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from diffusers.models.attention_processor import AttnProcessor, Attention
12
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
13
+ from diffusers.schedulers import DDIMScheduler
14
+ from scheduling_dpmsolver_multistep_inject import DPMSolverMultistepSchedulerInject
15
+ # from diffusers.utils import logging, randn_tensor
16
+ from diffusers.utils import logging
17
+ from diffusers.utils.torch_utils import randn_tensor
18
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
19
+ from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipelineOutput
20
+
21
+ import numpy as np
22
+ from PIL import Image
23
+ from tqdm import tqdm
24
+ import torch.nn.functional as F
25
+ import math
26
+ from collections.abc import Iterable
27
+
28
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
29
+
30
+
31
+ class AttentionStore():
32
+ @staticmethod
33
+ def get_empty_store():
34
+ return {"down_cross": [], "mid_cross": [], "up_cross": [],
35
+ "down_self": [], "mid_self": [], "up_self": []}
36
+
37
+ def __call__(self, attn, is_cross: bool, place_in_unet: str, editing_prompts, PnP=False):
38
+ # attn.shape = batch_size * head_size, seq_len query, seq_len_key
39
+ bs = 2 + int(PnP) + editing_prompts
40
+ skip = 2 if PnP else 1 # skip PnP & unconditional
41
+
42
+ head_size = int(attn.shape[0] / self.batch_size)
43
+ attn = torch.stack(attn.split(self.batch_size)).permute(1, 0, 2, 3)
44
+ source_batch_size = int(attn.shape[1] // bs)
45
+ self.forward(
46
+ attn[:, skip * source_batch_size:],
47
+ is_cross,
48
+ place_in_unet)
49
+
50
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
51
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
52
+ if attn.shape[1] <= 32 ** 2: # avoid memory overhead
53
+ self.step_store[key].append(attn)
54
+
55
+ def between_steps(self, store_step=True):
56
+ if store_step:
57
+ if self.average:
58
+ if len(self.attention_store) == 0:
59
+ self.attention_store = self.step_store
60
+ else:
61
+ for key in self.attention_store:
62
+ for i in range(len(self.attention_store[key])):
63
+ self.attention_store[key][i] += self.step_store[key][i]
64
+ else:
65
+ if len(self.attention_store) == 0:
66
+ self.attention_store = [self.step_store]
67
+ else:
68
+ self.attention_store.append(self.step_store)
69
+
70
+ self.cur_step += 1
71
+ self.step_store = self.get_empty_store()
72
+
73
+ def get_attention(self, step: int):
74
+ if self.average:
75
+ attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in
76
+ self.attention_store}
77
+ else:
78
+ assert (step is not None)
79
+ attention = self.attention_store[step]
80
+ return attention
81
+
82
+ def aggregate_attention(self, attention_maps, prompts, res: int,
83
+ from_where: List[str], is_cross: bool, select: int
84
+ ):
85
+ out = [[] for x in range(self.batch_size)]
86
+ num_pixels = res ** 2
87
+ for location in from_where:
88
+ for bs_item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
89
+ for batch, item in enumerate(bs_item):
90
+ if item.shape[1] == num_pixels:
91
+ cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
92
+ out[batch].append(cross_maps)
93
+
94
+ out = torch.stack([torch.cat(x, dim=0) for x in out])
95
+ # average over heads
96
+ out = out.sum(1) / out.shape[1]
97
+ return out
98
+
99
+ def __init__(self, average: bool, batch_size=1):
100
+ self.step_store = self.get_empty_store()
101
+ self.attention_store = []
102
+ self.cur_step = 0
103
+ self.average = average
104
+ self.batch_size = batch_size
105
+
106
+
107
+ class CrossAttnProcessor:
108
+
109
+ def __init__(self, attention_store, place_in_unet, PnP, editing_prompts):
110
+ self.attnstore = attention_store
111
+ self.place_in_unet = place_in_unet
112
+ self.editing_prompts = editing_prompts
113
+ self.PnP = PnP
114
+
115
+ def __call__(
116
+ self,
117
+ attn: Attention,
118
+ hidden_states,
119
+ encoder_hidden_states=None,
120
+ attention_mask=None,
121
+ temb=None,
122
+ ):
123
+ assert (not attn.residual_connection)
124
+ assert (attn.spatial_norm is None)
125
+ assert (attn.group_norm is None)
126
+ assert (hidden_states.ndim != 4)
127
+ assert (encoder_hidden_states is not None) # is cross
128
+
129
+ batch_size, sequence_length, _ = (
130
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
131
+ )
132
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
133
+
134
+ query = attn.to_q(hidden_states)
135
+
136
+ if encoder_hidden_states is None:
137
+ encoder_hidden_states = hidden_states
138
+ elif attn.norm_cross:
139
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
140
+
141
+ key = attn.to_k(encoder_hidden_states)
142
+ value = attn.to_v(encoder_hidden_states)
143
+
144
+ query = attn.head_to_batch_dim(query)
145
+ key = attn.head_to_batch_dim(key)
146
+ value = attn.head_to_batch_dim(value)
147
+
148
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
149
+ self.attnstore(attention_probs,
150
+ is_cross=True,
151
+ place_in_unet=self.place_in_unet,
152
+ editing_prompts=self.editing_prompts,
153
+ PnP=self.PnP)
154
+
155
+ hidden_states = torch.bmm(attention_probs, value)
156
+ hidden_states = attn.batch_to_head_dim(hidden_states)
157
+
158
+ # linear proj
159
+ hidden_states = attn.to_out[0](hidden_states)
160
+ # dropout
161
+ hidden_states = attn.to_out[1](hidden_states)
162
+
163
+ hidden_states = hidden_states / attn.rescale_output_factor
164
+ return hidden_states
165
+
166
+
167
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
168
+ class GaussianSmoothing():
169
+
170
+ def __init__(self, device):
171
+ kernel_size = [3, 3]
172
+ sigma = [0.5, 0.5]
173
+
174
+ # The gaussian kernel is the product of the gaussian function of each dimension.
175
+ kernel = 1
176
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
177
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
178
+ mean = (size - 1) / 2
179
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
180
+
181
+ # Make sure sum of values in gaussian kernel equals 1.
182
+ kernel = kernel / torch.sum(kernel)
183
+
184
+ # Reshape to depthwise convolutional weight
185
+ kernel = kernel.view(1, 1, *kernel.size())
186
+ kernel = kernel.repeat(1, *[1] * (kernel.dim() - 1))
187
+
188
+ self.weight = kernel.to(device)
189
+
190
+ def __call__(self, input):
191
+ """
192
+ Arguments:
193
+ Apply gaussian filter to input.
194
+ input (torch.Tensor): Input to apply gaussian filter on.
195
+ Returns:
196
+ filtered (torch.Tensor): Filtered output.
197
+ """
198
+ return F.conv2d(input, weight=self.weight.to(input.dtype))
199
+
200
+
201
+ def load_512(image_path, size, left=0, right=0, top=0, bottom=0, device=None, dtype=None):
202
+ def pre_process(im, size, left=0, right=0, top=0, bottom=0):
203
+ if type(im) is str:
204
+ image = np.array(Image.open(im).convert('RGB'))[:, :, :3]
205
+ elif isinstance(im, Image.Image):
206
+ image = np.array((im).convert('RGB'))[:, :, :3]
207
+ else:
208
+ image = im
209
+ h, w, c = image.shape
210
+ left = min(left, w - 1)
211
+ right = min(right, w - left - 1)
212
+ top = min(top, h - left - 1)
213
+ bottom = min(bottom, h - top - 1)
214
+ image = image[top:h - bottom, left:w - right]
215
+ h, w, c = image.shape
216
+ if h < w:
217
+ offset = (w - h) // 2
218
+ image = image[:, offset:offset + h]
219
+ elif w < h:
220
+ offset = (h - w) // 2
221
+ image = image[offset:offset + w]
222
+ image = np.array(Image.fromarray(image).resize((size, size)))
223
+ image = torch.from_numpy(image).float().permute(2, 0, 1)
224
+ return image
225
+
226
+ tmps = []
227
+ if isinstance(image_path, list):
228
+ for item in image_path:
229
+ tmps.append(pre_process(item, size, left, right, top, bottom))
230
+ else:
231
+ tmps.append(pre_process(image_path, size, left, right, top, bottom))
232
+ image = torch.stack(tmps) / 127.5 - 1
233
+
234
+ image = image.to(device=device, dtype=dtype)
235
+ return image
236
+
237
+
238
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
239
+
240
+ def reset_dpm(scheduler):
241
+ if isinstance(scheduler, DPMSolverMultistepSchedulerInject):
242
+ scheduler.model_outputs = [
243
+ None,
244
+ ] * scheduler.config.solver_order
245
+ scheduler.lower_order_nums = 0
246
+
247
+
248
+ class SemanticStableDiffusionImg2ImgPipeline_DPMSolver(DiffusionPipeline):
249
+ r"""
250
+ Pipeline for text-to-image generation with latent editing.
251
+
252
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
253
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
254
+
255
+ This model builds on the implementation of ['StableDiffusionPipeline']
256
+
257
+ Args:
258
+ vae ([`AutoencoderKL`]):
259
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
260
+ text_encoder ([`CLIPTextModel`]):
261
+ Frozen text-encoder. Stable Diffusion uses the text portion of
262
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
263
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
264
+ tokenizer (`CLIPTokenizer`):
265
+ Tokenizer of class
266
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
267
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
268
+ scheduler ([`SchedulerMixin`]):
269
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
270
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
271
+ safety_checker ([`Q16SafetyChecker`]):
272
+ Classification module that estimates whether generated images could be considered offensive or harmful.
273
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
274
+ feature_extractor ([`CLIPImageProcessor`]):
275
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
276
+ """
277
+
278
+ _optional_components = ["safety_checker", "feature_extractor"]
279
+
280
+ def __init__(
281
+ self,
282
+ vae: AutoencoderKL,
283
+ text_encoder: CLIPTextModel,
284
+ tokenizer: CLIPTokenizer,
285
+ unet: UNet2DConditionModel,
286
+ scheduler: Union[DDIMScheduler,DPMSolverMultistepSchedulerInject],
287
+ safety_checker: StableDiffusionSafetyChecker,
288
+ feature_extractor: CLIPImageProcessor,
289
+ requires_safety_checker: bool = True,
290
+ ):
291
+ super().__init__()
292
+
293
+ if not isinstance(scheduler, DDIMScheduler) or not isinstance(scheduler, DPMSolverMultistepSchedulerInject):
294
+ scheduler = DPMSolverMultistepSchedulerInject.from_config(scheduler.config, algorithm_type="sde-dpmsolver++", solver_order=2)
295
+ logger.warning("This pipeline only supports DDIMScheduler and DPMSolverMultistepSchedulerInject. "
296
+ "The scheduler has been changed to DPMSolverMultistepSchedulerInject.")
297
+
298
+ if safety_checker is None and requires_safety_checker:
299
+ logger.warning(
300
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
301
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
302
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
303
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
304
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
305
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
306
+ )
307
+
308
+ if safety_checker is not None and feature_extractor is None:
309
+ raise ValueError(
310
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
311
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
312
+ )
313
+
314
+ self.register_modules(
315
+ vae=vae,
316
+ text_encoder=text_encoder,
317
+ tokenizer=tokenizer,
318
+ unet=unet,
319
+ scheduler=scheduler,
320
+ safety_checker=safety_checker,
321
+ feature_extractor=feature_extractor,
322
+ )
323
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
324
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
325
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
326
+
327
+ def progress_bar(self, iterable=None, total=None, verbose=True):
328
+ if not hasattr(self, "_progress_bar_config"):
329
+ self._progress_bar_config = {}
330
+ elif not isinstance(self._progress_bar_config, dict):
331
+ raise ValueError(
332
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
333
+ )
334
+ if not verbose:
335
+ return iterable
336
+ elif iterable is not None:
337
+ return tqdm(iterable, **self._progress_bar_config)
338
+ elif total is not None:
339
+ return tqdm(total=total, **self._progress_bar_config)
340
+ else:
341
+ raise ValueError("Either `total` or `iterable` has to be defined.")
342
+
343
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
344
+ def run_safety_checker(self, image, device, dtype):
345
+ if self.safety_checker is None:
346
+ has_nsfw_concept = None
347
+ else:
348
+ if torch.is_tensor(image):
349
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
350
+ else:
351
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
352
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
353
+ image, has_nsfw_concept = self.safety_checker(
354
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
355
+ )
356
+ return image, has_nsfw_concept
357
+
358
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
359
+ def decode_latents(self, latents):
360
+ warnings.warn(
361
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
362
+ " use VaeImageProcessor instead",
363
+ FutureWarning,
364
+ )
365
+ latents = 1 / self.vae.config.scaling_factor * latents
366
+ image = self.vae.decode(latents, return_dict=False)[0]
367
+ image = (image / 2 + 0.5).clamp(0, 1)
368
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
369
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
370
+ return image
371
+
372
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
373
+ def prepare_extra_step_kwargs(self, eta):
374
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
375
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
376
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
377
+ # and should be between [0, 1]
378
+
379
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
380
+ extra_step_kwargs = {}
381
+ if accepts_eta:
382
+ extra_step_kwargs["eta"] = eta
383
+
384
+ return extra_step_kwargs
385
+
386
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
387
+ def check_inputs(
388
+ self,
389
+ prompt,
390
+ height,
391
+ width,
392
+ callback_steps,
393
+ negative_prompt=None,
394
+ prompt_embeds=None,
395
+ negative_prompt_embeds=None,
396
+ ):
397
+ if height % 8 != 0 or width % 8 != 0:
398
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
399
+
400
+ if (callback_steps is None) or (
401
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
402
+ ):
403
+ raise ValueError(
404
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
405
+ f" {type(callback_steps)}."
406
+ )
407
+
408
+ if prompt is not None and prompt_embeds is not None:
409
+ raise ValueError(
410
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
411
+ " only forward one of the two."
412
+ )
413
+ elif prompt is None and prompt_embeds is None:
414
+ raise ValueError(
415
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
416
+ )
417
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
418
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
419
+
420
+ if negative_prompt is not None and negative_prompt_embeds is not None:
421
+ raise ValueError(
422
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
423
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
424
+ )
425
+
426
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
427
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
428
+ raise ValueError(
429
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
430
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
431
+ f" {negative_prompt_embeds.shape}."
432
+ )
433
+
434
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
435
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, latents):
436
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
437
+
438
+ if latents.shape != shape:
439
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
440
+
441
+ latents = latents.to(device)
442
+
443
+ # scale the initial noise by the standard deviation required by the scheduler
444
+ latents = latents * self.scheduler.init_noise_sigma
445
+ return latents
446
+
447
+ def prepare_unet(self, attention_store, PnP: bool = False):
448
+ attn_procs = {}
449
+ for name in self.unet.attn_processors.keys():
450
+ if name.startswith("mid_block"):
451
+ place_in_unet = "mid"
452
+ elif name.startswith("up_blocks"):
453
+ place_in_unet = "up"
454
+ elif name.startswith("down_blocks"):
455
+ place_in_unet = "down"
456
+ else:
457
+ continue
458
+
459
+ if "attn2" in name:
460
+ attn_procs[name] = CrossAttnProcessor(
461
+ attention_store=attention_store,
462
+ place_in_unet=place_in_unet,
463
+ PnP=PnP,
464
+ editing_prompts=self.enabled_editing_prompts)
465
+ else:
466
+ attn_procs[name] = AttnProcessor()
467
+
468
+ self.unet.set_attn_processor(attn_procs)
469
+
470
+ @torch.no_grad()
471
+ def __call__(
472
+ self,
473
+ prompt: Union[str, List[str]] = "",
474
+ height: Optional[int] = None,
475
+ width: Optional[int] = None,
476
+ # num_inference_steps: int = 50,
477
+ guidance_scale: float = 7.5,
478
+ negative_prompt: Optional[Union[str, List[str]]] = None,
479
+ # num_images_per_prompt: int = 1,
480
+ eta: float = 1.0,
481
+ # generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
482
+ # latents: Optional[torch.FloatTensor] = None,
483
+ output_type: Optional[str] = "pil",
484
+ return_dict: bool = True,
485
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
486
+ callback_steps: int = 1,
487
+ editing_prompt: Optional[Union[str, List[str]]] = None,
488
+ editing_prompt_embeddings: Optional[torch.Tensor] = None,
489
+ reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
490
+ edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
491
+ edit_warmup_steps: Optional[Union[int, List[int]]] = 10,
492
+ edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
493
+ edit_threshold: Optional[Union[float, List[float]]] = 0.9,
494
+ user_mask: Optional[torch.FloatTensor] = None,
495
+ edit_momentum_scale: Optional[float] = 0.1,
496
+ edit_mom_beta: Optional[float] = 0.4,
497
+ edit_weights: Optional[List[float]] = None,
498
+ sem_guidance: Optional[List[torch.Tensor]] = None,
499
+ verbose=True,
500
+ use_cross_attn_mask: bool = False,
501
+ # Attention store (just for visualization purposes)
502
+ attn_store_steps: Optional[List[int]] = [],
503
+ store_averaged_over_steps: bool = True,
504
+ use_intersect_mask: bool = False,
505
+ init_latents = None,
506
+ zs = None,
507
+
508
+ ):
509
+ r"""
510
+ Function invoked when calling the pipeline for generation.
511
+
512
+ Args:
513
+ prompt (`str` or `List[str]`):
514
+ The prompt or prompts to guide the image generation.
515
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
516
+ The height in pixels of the generated image.
517
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
518
+ The width in pixels of the generated image.
519
+ num_inference_steps (`int`, *optional*, defaults to 50):
520
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
521
+ expense of slower inference.
522
+ guidance_scale (`float`, *optional*, defaults to 7.5):
523
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
524
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
525
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
526
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
527
+ usually at the expense of lower image quality.
528
+ negative_prompt (`str` or `List[str]`, *optional*):
529
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
530
+ if `guidance_scale` is less than `1`).
531
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
532
+ The number of images to generate per prompt.
533
+ eta (`float`, *optional*, defaults to 0.0):
534
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
535
+ [`schedulers.DDIMScheduler`], will be ignored for others.
536
+ generator (`torch.Generator`, *optional*):
537
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
538
+ to make generation deterministic.
539
+ latents (`torch.FloatTensor`, *optional*):
540
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
541
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
542
+ tensor will ge generated by sampling using the supplied random `generator`.
543
+ output_type (`str`, *optional*, defaults to `"pil"`):
544
+ The output format of the generate image. Choose between
545
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
546
+ return_dict (`bool`, *optional*, defaults to `True`):
547
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
548
+ plain tuple.
549
+ callback (`Callable`, *optional*):
550
+ A function that will be called every `callback_steps` steps during inference. The function will be
551
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
552
+ callback_steps (`int`, *optional*, defaults to 1):
553
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
554
+ called at every step.
555
+ editing_prompt (`str` or `List[str]`, *optional*):
556
+ The prompt or prompts to use for Semantic guidance. Semantic guidance is disabled by setting
557
+ `editing_prompt = None`. Guidance direction of prompt should be specified via
558
+ `reverse_editing_direction`.
559
+ editing_prompt_embeddings (`torch.Tensor>`, *optional*):
560
+ Pre-computed embeddings to use for semantic guidance. Guidance direction of embedding should be
561
+ specified via `reverse_editing_direction`.
562
+ reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
563
+ Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
564
+ edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
565
+ Guidance scale for semantic guidance. If provided as list values should correspond to `editing_prompt`.
566
+ `edit_guidance_scale` is defined as `s_e` of equation 6 of [SEGA
567
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
568
+ edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
569
+ Number of diffusion steps (for each prompt) for which semantic guidance will not be applied. Momentum
570
+ will still be calculated for those steps and applied once all warmup periods are over.
571
+ `edit_warmup_steps` is defined as `delta` (δ) of [SEGA Paper](https://arxiv.org/pdf/2301.12247.pdf).
572
+ edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
573
+ Number of diffusion steps (for each prompt) after which semantic guidance will no longer be applied.
574
+ edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
575
+ Threshold of semantic guidance.
576
+ edit_momentum_scale (`float`, *optional*, defaults to 0.1):
577
+ Scale of the momentum to be added to the semantic guidance at each diffusion step. If set to 0.0
578
+ momentum will be disabled. Momentum is already built up during warmup, i.e. for diffusion steps smaller
579
+ than `sld_warmup_steps`. Momentum will only be added to latent guidance once all warmup periods are
580
+ finished. `edit_momentum_scale` is defined as `s_m` of equation 7 of [SEGA
581
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
582
+ edit_mom_beta (`float`, *optional*, defaults to 0.4):
583
+ Defines how semantic guidance momentum builds up. `edit_mom_beta` indicates how much of the previous
584
+ momentum will be kept. Momentum is already built up during warmup, i.e. for diffusion steps smaller
585
+ than `edit_warmup_steps`. `edit_mom_beta` is defined as `beta_m` (β) of equation 8 of [SEGA
586
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
587
+ edit_weights (`List[float]`, *optional*, defaults to `None`):
588
+ Indicates how much each individual concept should influence the overall guidance. If no weights are
589
+ provided all concepts are applied equally. `edit_mom_beta` is defined as `g_i` of equation 9 of [SEGA
590
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
591
+ sem_guidance (`List[torch.Tensor]`, *optional*):
592
+ List of pre-generated guidance vectors to be applied at generation. Length of the list has to
593
+ correspond to `num_inference_steps`.
594
+
595
+ Returns:
596
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] or `tuple`:
597
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] if `return_dict` is True,
598
+ otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the
599
+ second element is a list of `bool`s denoting whether the corresponding generated image likely represents
600
+ "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
601
+ """
602
+ # eta = self.eta
603
+ num_images_per_prompt = 1
604
+ # latents = self.init_latents
605
+ latents = init_latents
606
+
607
+ use_ddpm = True
608
+ # zs = self.zs
609
+ reset_dpm(self.scheduler)
610
+
611
+ if use_intersect_mask:
612
+ use_cross_attn_mask = True
613
+
614
+ if use_cross_attn_mask:
615
+ self.smoothing = GaussianSmoothing(self.device)
616
+
617
+ # 0. Default height and width to unet
618
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
619
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
620
+
621
+ # 1. Check inputs. Raise error if not correct
622
+ self.check_inputs(prompt, height, width, callback_steps)
623
+
624
+ org_prompt = prompt
625
+ if isinstance(prompt, list):
626
+ assert len(prompt) == self.batch_size
627
+ elif isinstance(prompt, str):
628
+ prompt = list(repeat(prompt, self.batch_size))
629
+
630
+ # 2. Define call parameters
631
+ batch_size = self.batch_size
632
+
633
+ if editing_prompt:
634
+ enable_edit_guidance = True
635
+ if isinstance(editing_prompt, str):
636
+ editing_prompt = [editing_prompt]
637
+ self.enabled_editing_prompts = len(editing_prompt)
638
+ elif editing_prompt_embeddings is not None:
639
+ enable_edit_guidance = True
640
+ self.enabled_editing_prompts = editing_prompt_embeddings.shape[0]
641
+ else:
642
+ self.enabled_editing_prompts = 0
643
+ enable_edit_guidance = False
644
+
645
+ # get prompt text embeddings
646
+ text_inputs = self.tokenizer(
647
+ prompt,
648
+ padding="max_length",
649
+ max_length=self.tokenizer.model_max_length,
650
+ truncation=True,
651
+ return_tensors="pt",
652
+ )
653
+ text_input_ids = text_inputs.input_ids
654
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
655
+
656
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
657
+ text_input_ids, untruncated_ids
658
+ ):
659
+ removed_text = self.tokenizer.batch_decode(
660
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]
661
+ )
662
+ logger.warning(
663
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
664
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
665
+ )
666
+
667
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
668
+
669
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
670
+ bs_embed, seq_len, _ = text_embeddings.shape
671
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
672
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
673
+
674
+ if enable_edit_guidance:
675
+ # get safety text embeddings
676
+ if editing_prompt_embeddings is None:
677
+ edit_concepts_input = self.tokenizer(
678
+ [x for item in editing_prompt for x in repeat(item, batch_size)],
679
+ padding="max_length",
680
+ max_length=self.tokenizer.model_max_length,
681
+ truncation=True,
682
+ return_tensors="pt",
683
+ return_length=True
684
+ )
685
+
686
+ num_edit_tokens = edit_concepts_input.length - 2 # not counting startoftext and endoftext
687
+ edit_concepts_input_ids = edit_concepts_input.input_ids
688
+ untruncated_ids = self.tokenizer(
689
+ [x for item in editing_prompt for x in repeat(item, batch_size)],
690
+ padding="longest",
691
+ return_tensors="pt").input_ids
692
+
693
+ if untruncated_ids.shape[-1] >= edit_concepts_input_ids.shape[-1] and not torch.equal(
694
+ edit_concepts_input_ids, untruncated_ids
695
+ ):
696
+ removed_text = self.tokenizer.batch_decode(
697
+ untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]
698
+ )
699
+ logger.warning(
700
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
701
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
702
+ )
703
+
704
+ edit_concepts = self.text_encoder(edit_concepts_input_ids.to(self.device))[0]
705
+ else:
706
+ edit_concepts = editing_prompt_embeddings.to(self.device).repeat(batch_size, 1, 1)
707
+
708
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
709
+ bs_embed_edit, seq_len_edit, _ = edit_concepts.shape
710
+ edit_concepts = edit_concepts.repeat(1, num_images_per_prompt, 1)
711
+ edit_concepts = edit_concepts.view(bs_embed_edit * num_images_per_prompt, seq_len_edit, -1)
712
+
713
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
714
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
715
+ # corresponds to doing no classifier free guidance.
716
+ do_classifier_free_guidance = guidance_scale > 1.0
717
+ # get unconditional embeddings for classifier free guidance
718
+
719
+ if do_classifier_free_guidance:
720
+ uncond_tokens: List[str]
721
+ if negative_prompt is None:
722
+ uncond_tokens = [""]
723
+ elif type(prompt) is not type(negative_prompt):
724
+ raise TypeError(
725
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
726
+ f" {type(prompt)}."
727
+ )
728
+ elif isinstance(negative_prompt, str):
729
+ uncond_tokens = [negative_prompt]
730
+ elif batch_size != len(negative_prompt):
731
+ raise ValueError(
732
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
733
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
734
+ " the batch size of `prompt`."
735
+ )
736
+ else:
737
+ uncond_tokens = negative_prompt
738
+
739
+ max_length = text_input_ids.shape[-1]
740
+ uncond_input = self.tokenizer(
741
+ uncond_tokens,
742
+ padding="max_length",
743
+ max_length=max_length,
744
+ truncation=True,
745
+ return_tensors="pt",
746
+ )
747
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
748
+
749
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
750
+ seq_len = uncond_embeddings.shape[1]
751
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
752
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
753
+
754
+ # For classifier free guidance, we need to do two forward passes.
755
+ # Here we concatenate the unconditional and text embeddings into a single batch
756
+ # to avoid doing two forward passes
757
+ self.text_cross_attention_maps = [org_prompt] if isinstance(org_prompt, str) else org_prompt
758
+ if enable_edit_guidance:
759
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings, edit_concepts])
760
+ self.text_cross_attention_maps += \
761
+ ([editing_prompt] if isinstance(editing_prompt, str) else editing_prompt)
762
+ else:
763
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
764
+
765
+ # 4. Prepare timesteps
766
+ #self.scheduler.set_timesteps(num_inference_steps, device=self.device)
767
+ timesteps = self.scheduler.timesteps
768
+
769
+ if use_ddpm:
770
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps[-zs.shape[0]:])}
771
+ timesteps = timesteps[-zs.shape[0]:]
772
+
773
+ if use_cross_attn_mask:
774
+ self.attention_store = AttentionStore(average=store_averaged_over_steps, batch_size=batch_size)
775
+ self.prepare_unet(self.attention_store, PnP=False)
776
+ # 5. Prepare latent variables
777
+ num_channels_latents = self.unet.config.in_channels
778
+ latents = self.prepare_latents(
779
+ batch_size * num_images_per_prompt,
780
+ num_channels_latents,
781
+ height,
782
+ width,
783
+ text_embeddings.dtype,
784
+ self.device,
785
+ latents,
786
+ )
787
+
788
+ # 6. Prepare extra step kwargs.
789
+ extra_step_kwargs = self.prepare_extra_step_kwargs(eta)
790
+
791
+ # Initialize edit_momentum to None
792
+ edit_momentum = None
793
+
794
+ self.uncond_estimates = None
795
+ self.text_estimates = None
796
+ self.edit_estimates = None
797
+ self.sem_guidance = None
798
+ self.activation_mask = None
799
+
800
+ for i, t in enumerate(self.progress_bar(timesteps, verbose=verbose)):
801
+ idx = t_to_idx[int(t)]
802
+
803
+
804
+ # expand the latents if we are doing classifier free guidance
805
+
806
+ if do_classifier_free_guidance:
807
+ latent_model_input = torch.cat([latents] * (2 + self.enabled_editing_prompts))
808
+ else:
809
+ latent_model_input = latents
810
+
811
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
812
+
813
+ text_embed_input = text_embeddings
814
+
815
+ # predict the noise residual
816
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embed_input).sample
817
+
818
+ # perform guidance
819
+ if do_classifier_free_guidance:
820
+
821
+ noise_pred_out = noise_pred.chunk(2 + self.enabled_editing_prompts) # [b,4, 64, 64]
822
+ noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
823
+ noise_pred_edit_concepts = noise_pred_out[2:]
824
+
825
+ # default text guidance
826
+ noise_guidance = guidance_scale * (noise_pred_text - noise_pred_uncond)
827
+
828
+ if self.uncond_estimates is None:
829
+ self.uncond_estimates = torch.zeros((len(timesteps), *noise_pred_uncond.shape))
830
+ self.uncond_estimates[i] = noise_pred_uncond.detach().cpu()
831
+
832
+ if self.text_estimates is None:
833
+ self.text_estimates = torch.zeros((len(timesteps), *noise_pred_text.shape))
834
+ self.text_estimates[i] = noise_pred_text.detach().cpu()
835
+
836
+ if edit_momentum is None:
837
+ edit_momentum = torch.zeros_like(noise_guidance)
838
+
839
+ if sem_guidance is not None and len(sem_guidance) > i:
840
+ edit_guidance = sem_guidance[i].to(self.device)
841
+ edit_momentum = edit_mom_beta * edit_momentum + (1 - edit_mom_beta) * edit_guidance
842
+ noise_guidance = noise_guidance + edit_guidance
843
+
844
+ elif enable_edit_guidance:
845
+ if self.activation_mask is None:
846
+ self.activation_mask = torch.zeros(
847
+ (len(timesteps), len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
848
+ )
849
+ if self.edit_estimates is None and enable_edit_guidance:
850
+ self.edit_estimates = torch.zeros(
851
+ (len(timesteps), len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
852
+ )
853
+
854
+ if self.sem_guidance is None:
855
+ self.sem_guidance = torch.zeros((len(timesteps), *noise_pred_text.shape))
856
+
857
+ concept_weights = torch.zeros(
858
+ (len(noise_pred_edit_concepts), noise_guidance.shape[0]),
859
+ device=self.device,
860
+ dtype=noise_guidance.dtype,
861
+ )
862
+ noise_guidance_edit = torch.zeros(
863
+ (len(noise_pred_edit_concepts), *noise_guidance.shape),
864
+ device=self.device,
865
+ dtype=noise_guidance.dtype,
866
+ )
867
+ # noise_guidance_edit = torch.zeros_like(noise_guidance)
868
+ warmup_inds = []
869
+ for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
870
+ self.edit_estimates[i, c] = noise_pred_edit_concept
871
+ if isinstance(edit_guidance_scale, list):
872
+ edit_guidance_scale_c = edit_guidance_scale[c]
873
+ else:
874
+ edit_guidance_scale_c = edit_guidance_scale
875
+
876
+ if isinstance(edit_threshold, list):
877
+ edit_threshold_c = edit_threshold[c]
878
+ else:
879
+ edit_threshold_c = edit_threshold
880
+ if isinstance(reverse_editing_direction, list):
881
+ reverse_editing_direction_c = reverse_editing_direction[c]
882
+ else:
883
+ reverse_editing_direction_c = reverse_editing_direction
884
+ if edit_weights:
885
+ edit_weight_c = edit_weights[c]
886
+ else:
887
+ edit_weight_c = 1.0
888
+ if isinstance(edit_warmup_steps, list):
889
+ edit_warmup_steps_c = edit_warmup_steps[c]
890
+ else:
891
+ edit_warmup_steps_c = edit_warmup_steps
892
+
893
+ if isinstance(edit_cooldown_steps, list):
894
+ edit_cooldown_steps_c = edit_cooldown_steps[c]
895
+ elif edit_cooldown_steps is None:
896
+ edit_cooldown_steps_c = i + 1
897
+ else:
898
+ edit_cooldown_steps_c = edit_cooldown_steps
899
+ if i >= edit_warmup_steps_c:
900
+ warmup_inds.append(c)
901
+ if i >= edit_cooldown_steps_c:
902
+ noise_guidance_edit[c, :, :, :, :] = torch.zeros_like(noise_pred_edit_concept)
903
+ continue
904
+
905
+ noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
906
+ # tmp_weights = (noise_pred_text - noise_pred_edit_concept).sum(dim=(1, 2, 3))
907
+ tmp_weights = (noise_guidance - noise_pred_edit_concept).sum(dim=(1, 2, 3))
908
+
909
+ tmp_weights = torch.full_like(tmp_weights, edit_weight_c) # * (1 / enabled_editing_prompts)
910
+ if reverse_editing_direction_c:
911
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
912
+ concept_weights[c, :] = tmp_weights
913
+
914
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
915
+
916
+ if user_mask is not None:
917
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * user_mask
918
+
919
+ if use_cross_attn_mask:
920
+ out = self.attention_store.aggregate_attention(
921
+ attention_maps=self.attention_store.step_store,
922
+ prompts=self.text_cross_attention_maps,
923
+ res=16,
924
+ from_where=["up", "down"],
925
+ is_cross=True,
926
+ select=self.text_cross_attention_maps.index(editing_prompt[c]),
927
+ )
928
+ attn_map = out[:, :, :, 1:1 + num_edit_tokens[c]] # 0 -> startoftext
929
+
930
+ # average over all tokens
931
+ assert (attn_map.shape[3] == num_edit_tokens[c])
932
+ attn_map = torch.sum(attn_map, dim=3)
933
+
934
+ # gaussian_smoothing
935
+ attn_map = F.pad(attn_map.unsqueeze(1), (1, 1, 1, 1), mode="reflect")
936
+ attn_map = self.smoothing(attn_map).squeeze(1)
937
+
938
+ # create binary mask
939
+ if attn_map.dtype == torch.float32:
940
+ tmp = torch.quantile(attn_map.flatten(start_dim=1), edit_threshold_c, dim=1)
941
+ else:
942
+ tmp = torch.quantile(attn_map.flatten(start_dim=1).to(torch.float32), edit_threshold_c, dim=1).to(attn_map.dtype)
943
+ attn_mask = torch.where(attn_map >= tmp.unsqueeze(1).unsqueeze(1).repeat(1,16,16), 1.0, 0.0)
944
+
945
+ # resolution must match latent space dimension
946
+ attn_mask = F.interpolate(
947
+ attn_mask.unsqueeze(1),
948
+ noise_guidance_edit_tmp.shape[-2:] # 64,64
949
+ ).repeat(1, 4, 1, 1)
950
+ self.activation_mask[i, c] = attn_mask.detach().cpu()
951
+ if not use_intersect_mask:
952
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
953
+
954
+ if use_intersect_mask:
955
+ noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
956
+ noise_guidance_edit_tmp_quantile = torch.sum(noise_guidance_edit_tmp_quantile, dim=1,
957
+ keepdim=True)
958
+ noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1, 4, 1, 1)
959
+
960
+ # torch.quantile function expects float32
961
+ if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
962
+ tmp = torch.quantile(
963
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
964
+ edit_threshold_c,
965
+ dim=2,
966
+ keepdim=False,
967
+ )
968
+ else:
969
+ tmp = torch.quantile(
970
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
971
+ edit_threshold_c,
972
+ dim=2,
973
+ keepdim=False,
974
+ ).to(noise_guidance_edit_tmp_quantile.dtype)
975
+
976
+ intersect_mask = torch.where(
977
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
978
+ torch.ones_like(noise_guidance_edit_tmp),
979
+ torch.zeros_like(noise_guidance_edit_tmp),
980
+ ) * attn_mask
981
+
982
+ self.activation_mask[i, c] = intersect_mask.detach().cpu()
983
+
984
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * intersect_mask
985
+
986
+ elif not use_cross_attn_mask:
987
+ # calculate quantile
988
+ noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
989
+ noise_guidance_edit_tmp_quantile = torch.sum(noise_guidance_edit_tmp_quantile, dim=1,
990
+ keepdim=True)
991
+ noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1, 4, 1, 1)
992
+
993
+ # torch.quantile function expects float32
994
+ if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
995
+ tmp = torch.quantile(
996
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
997
+ edit_threshold_c,
998
+ dim=2,
999
+ keepdim=False,
1000
+ )
1001
+ else:
1002
+ tmp = torch.quantile(
1003
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
1004
+ edit_threshold_c,
1005
+ dim=2,
1006
+ keepdim=False,
1007
+ ).to(noise_guidance_edit_tmp_quantile.dtype)
1008
+
1009
+ self.activation_mask[i, c] = torch.where(
1010
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
1011
+ torch.ones_like(noise_guidance_edit_tmp),
1012
+ torch.zeros_like(noise_guidance_edit_tmp),
1013
+ ).detach().cpu()
1014
+
1015
+ noise_guidance_edit_tmp = torch.where(
1016
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
1017
+ noise_guidance_edit_tmp,
1018
+ torch.zeros_like(noise_guidance_edit_tmp),
1019
+ )
1020
+
1021
+ noise_guidance_edit[c, :, :, :, :] = noise_guidance_edit_tmp
1022
+
1023
+ warmup_inds = torch.tensor(warmup_inds).to(self.device)
1024
+ if len(noise_pred_edit_concepts) > warmup_inds.shape[0] > 0:
1025
+ concept_weights = concept_weights.to("cpu") # Offload to cpu
1026
+ noise_guidance_edit = noise_guidance_edit.to("cpu")
1027
+
1028
+ concept_weights_tmp = torch.index_select(concept_weights.to(self.device), 0, warmup_inds)
1029
+ concept_weights_tmp = torch.where(
1030
+ concept_weights_tmp < 0, torch.zeros_like(concept_weights_tmp), concept_weights_tmp
1031
+ )
1032
+ concept_weights_tmp = concept_weights_tmp / concept_weights_tmp.sum(dim=0)
1033
+ # concept_weights_tmp = torch.nan_to_num(concept_weights_tmp)
1034
+
1035
+ noise_guidance_edit_tmp = torch.index_select(
1036
+ noise_guidance_edit.to(self.device), 0, warmup_inds
1037
+ )
1038
+ noise_guidance_edit_tmp = torch.einsum(
1039
+ "cb,cbijk->bijk", concept_weights_tmp, noise_guidance_edit_tmp
1040
+ )
1041
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp
1042
+ noise_guidance = noise_guidance + noise_guidance_edit_tmp
1043
+
1044
+ self.sem_guidance[i] = noise_guidance_edit_tmp.detach().cpu()
1045
+
1046
+ del noise_guidance_edit_tmp
1047
+ del concept_weights_tmp
1048
+ concept_weights = concept_weights.to(self.device)
1049
+ noise_guidance_edit = noise_guidance_edit.to(self.device)
1050
+
1051
+ concept_weights = torch.where(
1052
+ concept_weights < 0, torch.zeros_like(concept_weights), concept_weights
1053
+ )
1054
+
1055
+ concept_weights = torch.nan_to_num(concept_weights)
1056
+
1057
+ noise_guidance_edit = torch.einsum("cb,cbijk->bijk", concept_weights, noise_guidance_edit)
1058
+
1059
+ noise_guidance_edit = noise_guidance_edit + edit_momentum_scale * edit_momentum
1060
+
1061
+ edit_momentum = edit_mom_beta * edit_momentum + (1 - edit_mom_beta) * noise_guidance_edit
1062
+
1063
+ if warmup_inds.shape[0] == len(noise_pred_edit_concepts):
1064
+ noise_guidance = noise_guidance + noise_guidance_edit
1065
+ self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
1066
+
1067
+ noise_pred = noise_pred_uncond + noise_guidance
1068
+
1069
+ # compute the previous noisy sample x_t -> x_t-1
1070
+ if use_ddpm:
1071
+ idx = t_to_idx[int(t)]
1072
+ latents = self.scheduler.step(noise_pred, t, latents, variance_noise=zs[idx],
1073
+ **extra_step_kwargs).prev_sample
1074
+
1075
+ else: #if not use_ddpm:
1076
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1077
+
1078
+ # step callback
1079
+ if use_cross_attn_mask:
1080
+ store_step = i in attn_store_steps
1081
+ if store_step:
1082
+ print(f"storing attention for step {i}")
1083
+ self.attention_store.between_steps(store_step)
1084
+
1085
+ # call the callback, if provided
1086
+ if callback is not None and i % callback_steps == 0:
1087
+ callback(i, t, latents)
1088
+
1089
+ # 8. Post-processing
1090
+ if not output_type == "latent":
1091
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1092
+ image, has_nsfw_concept = self.run_safety_checker(image, self.device, text_embeddings.dtype)
1093
+ else:
1094
+ image = latents
1095
+ has_nsfw_concept = None
1096
+
1097
+ if has_nsfw_concept is None:
1098
+ do_denormalize = [True] * image.shape[0]
1099
+ else:
1100
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1101
+
1102
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1103
+
1104
+ if not return_dict:
1105
+ return (image, has_nsfw_concept)
1106
+
1107
+ return SemanticStableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1108
+
1109
+ def encode_text(self, prompts):
1110
+ text_inputs = self.tokenizer(
1111
+ prompts,
1112
+ padding="max_length",
1113
+ max_length=self.tokenizer.model_max_length,
1114
+ return_tensors="pt",
1115
+ )
1116
+ text_input_ids = text_inputs.input_ids
1117
+
1118
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
1119
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length:])
1120
+ logger.warning(
1121
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
1122
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
1123
+ )
1124
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
1125
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
1126
+
1127
+ return text_embeddings
1128
+
1129
+ @torch.no_grad()
1130
+ def invert(self,
1131
+ image_path: str,
1132
+ source_prompt: str = "",
1133
+ source_guidance_scale=3.5,
1134
+ num_inversion_steps: int = 30,
1135
+ skip: float = 0.15,
1136
+ eta: float = 1.0,
1137
+ generator: Optional[torch.Generator] = None,
1138
+ verbose=True,
1139
+ ):
1140
+ """
1141
+ Inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
1142
+ based on the code in https://github.com/inbarhub/DDPM_inversion
1143
+
1144
+ returns:
1145
+ zs - noise maps
1146
+ xts - intermediate inverted latents
1147
+ """
1148
+
1149
+ # self.eta = eta
1150
+ # assert (self.eta > 0)
1151
+ skip = skip/100
1152
+ print("YOOOOOOOOOOOOOOOOO ", skip, num_inversion_steps)
1153
+ train_steps = self.scheduler.config.num_train_timesteps
1154
+ timesteps = torch.from_numpy(
1155
+ np.linspace(train_steps - skip * train_steps - 1, 1, num_inversion_steps).astype(np.int64)).to(self.device)
1156
+
1157
+
1158
+ self.num_inversion_steps = timesteps.shape[0]
1159
+ self.scheduler.num_inference_steps = timesteps.shape[0]
1160
+ self.scheduler.timesteps = timesteps
1161
+
1162
+ # Reset attn processor, we do not want to store attn maps during inversion
1163
+ self.unet.set_default_attn_processor()
1164
+
1165
+ # 1. get embeddings
1166
+
1167
+ uncond_embedding = self.encode_text("")
1168
+
1169
+ # 2. encode image
1170
+ x0 = self.encode_image(image_path, dtype=uncond_embedding.dtype)
1171
+ self.batch_size = x0.shape[0]
1172
+
1173
+ if not source_prompt == "":
1174
+ text_embeddings = self.encode_text(source_prompt).repeat((self.batch_size, 1, 1))
1175
+ uncond_embedding = uncond_embedding.repeat((self.batch_size, 1, 1))
1176
+ # autoencoder reconstruction
1177
+ # image_rec = self.vae.decode(x0 / self.vae.config.scaling_factor, return_dict=False)[0]
1178
+ # image_rec = self.image_processor.postprocess(image_rec, output_type="pil")
1179
+ # 3. find zs and xts
1180
+ variance_noise_shape = (
1181
+ self.num_inversion_steps,
1182
+ self.batch_size,
1183
+ self.unet.config.in_channels,
1184
+ self.unet.sample_size,
1185
+ self.unet.sample_size)
1186
+
1187
+ # intermediate latents
1188
+ t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
1189
+ xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
1190
+
1191
+ for t in reversed(timesteps):
1192
+ idx = self.num_inversion_steps-t_to_idx[int(t)] - 1
1193
+ noise = randn_tensor(shape=x0.shape, generator=generator, device=self.device, dtype=x0.dtype)
1194
+ xts[idx] = self.scheduler.add_noise(x0, noise, t)
1195
+ xts = torch.cat([x0.unsqueeze(0), xts], dim=0)
1196
+
1197
+ reset_dpm(self.scheduler)
1198
+ # noise maps
1199
+ zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
1200
+
1201
+ for t in self.progress_bar(timesteps, verbose=verbose):
1202
+
1203
+ idx = self.num_inversion_steps-t_to_idx[int(t)]-1
1204
+ # 1. predict noise residual
1205
+ xt = xts[idx+1]
1206
+
1207
+ noise_pred = self.unet(xt, timestep=t, encoder_hidden_states=uncond_embedding).sample
1208
+
1209
+ if not source_prompt == "":
1210
+ noise_pred_cond = self.unet(xt, timestep=t, encoder_hidden_states=text_embeddings).sample
1211
+ noise_pred = noise_pred + source_guidance_scale * (noise_pred_cond - noise_pred)
1212
+
1213
+ xtm1 = xts[idx]
1214
+ z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, eta)
1215
+ zs[idx] = z
1216
+
1217
+ # correction to avoid error accumulation
1218
+ xts[idx] = xtm1_corrected
1219
+
1220
+ # TODO: I don't think that the noise map for the last step should be discarded ?!
1221
+ # if not zs is None:
1222
+ # zs[-1] = torch.zeros_like(zs[-1])
1223
+ # self.init_latents = xts[-1].expand(self.batch_size, -1, -1, -1)
1224
+ zs = zs.flip(0)
1225
+ # self.zs = zs
1226
+
1227
+
1228
+ return zs, xts
1229
+ # return zs, xts, image_rec
1230
+
1231
+ @torch.no_grad()
1232
+ def encode_image(self, image_path, dtype=None):
1233
+ image = load_512(image_path,
1234
+ size=self.unet.sample_size * self.vae_scale_factor,
1235
+ device=self.device,
1236
+ dtype=dtype)
1237
+ x0 = self.vae.encode(image).latent_dist.mode()
1238
+ x0 = self.vae.config.scaling_factor * x0
1239
+ return x0
1240
+
1241
+ def compute_noise_ddim(scheduler, prev_latents, latents, timestep, noise_pred, eta):
1242
+ # 1. get previous step value (=t-1)
1243
+ prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
1244
+
1245
+ # 2. compute alphas, betas
1246
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
1247
+ alpha_prod_t_prev = (
1248
+ scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
1249
+ )
1250
+
1251
+ beta_prod_t = 1 - alpha_prod_t
1252
+
1253
+ # 3. compute predicted original sample from predicted noise also called
1254
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1255
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
1256
+
1257
+ # 4. Clip "predicted x_0"
1258
+ if scheduler.config.clip_sample:
1259
+ pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
1260
+
1261
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
1262
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
1263
+ variance = scheduler._get_variance(timestep, prev_timestep)
1264
+ std_dev_t = eta * variance ** (0.5)
1265
+
1266
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1267
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t ** 2) ** (0.5) * noise_pred
1268
+
1269
+ # modifed so that updated xtm1 is returned as well (to avoid error accumulation)
1270
+ mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
1271
+ noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
1272
+
1273
+ return noise, mu_xt + (eta * variance ** 0.5) * noise
1274
+
1275
+ # Copied from pipelines.StableDiffusion.CycleDiffusionPipeline.compute_noise
1276
+ def compute_noise_sde_dpm_pp_2nd(scheduler, prev_latents, latents, timestep, noise_pred, eta):
1277
+
1278
+ def first_order_update(model_output, timestep, prev_timestep, sample):
1279
+ lambda_t, lambda_s = scheduler.lambda_t[prev_timestep], scheduler.lambda_t[timestep]
1280
+ alpha_t, alpha_s = scheduler.alpha_t[prev_timestep], scheduler.alpha_t[timestep]
1281
+ sigma_t, sigma_s = scheduler.sigma_t[prev_timestep], scheduler.sigma_t[timestep]
1282
+ h = lambda_t - lambda_s
1283
+
1284
+ mu_xt = (
1285
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
1286
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
1287
+ )
1288
+ sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
1289
+
1290
+ noise = (prev_latents - mu_xt) / sigma
1291
+
1292
+ prev_sample = mu_xt + sigma * noise
1293
+
1294
+ return noise, prev_sample
1295
+ def second_order_update(model_output_list, timestep_list, prev_timestep, sample):
1296
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
1297
+ m0, m1 = model_output_list[-1], model_output_list[-2]
1298
+ lambda_t, lambda_s0, lambda_s1 = scheduler.lambda_t[t], scheduler.lambda_t[s0], scheduler.lambda_t[s1]
1299
+ alpha_t, alpha_s0 = scheduler.alpha_t[t], scheduler.alpha_t[s0]
1300
+ sigma_t, sigma_s0 = scheduler.sigma_t[t], scheduler.sigma_t[s0]
1301
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
1302
+ r0 = h_0 / h
1303
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
1304
+
1305
+ mu_xt = (
1306
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
1307
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
1308
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
1309
+ )
1310
+ sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
1311
+
1312
+ noise = (prev_latents - mu_xt) / sigma
1313
+
1314
+ prev_sample = mu_xt + sigma * noise
1315
+
1316
+ return noise, prev_sample
1317
+
1318
+ step_index = (scheduler.timesteps == timestep).nonzero()
1319
+ if len(step_index) == 0:
1320
+ step_index = len(scheduler.timesteps) - 1
1321
+ else:
1322
+ step_index = step_index.item()
1323
+
1324
+ prev_timestep = 0 if step_index == len(scheduler.timesteps) - 1 else scheduler.timesteps[step_index + 1]
1325
+
1326
+ model_output = scheduler.convert_model_output(noise_pred, timestep, latents)
1327
+
1328
+ for i in range(scheduler.config.solver_order - 1):
1329
+ scheduler.model_outputs[i] = scheduler.model_outputs[i + 1]
1330
+ scheduler.model_outputs[-1] = model_output
1331
+
1332
+ if scheduler.lower_order_nums < 1:
1333
+ noise, prev_sample = first_order_update(model_output, timestep, prev_timestep, latents)
1334
+ else:
1335
+ timestep_list = [scheduler.timesteps[step_index - 1], timestep]
1336
+ noise, prev_sample = second_order_update(scheduler.model_outputs, timestep_list, prev_timestep, latents)
1337
+
1338
+ if scheduler.lower_order_nums < scheduler.config.solver_order:
1339
+ scheduler.lower_order_nums += 1
1340
+
1341
+ return noise, prev_sample
1342
+
1343
+ def compute_noise(scheduler, *args):
1344
+ if isinstance(scheduler, DDIMScheduler):
1345
+ return compute_noise_ddim(scheduler, *args)
1346
+ elif isinstance(scheduler, DPMSolverMultistepSchedulerInject) and scheduler.config.algorithm_type == 'sde-dpmsolver++'\
1347
+ and scheduler.config.solver_order == 2:
1348
+ return compute_noise_sde_dpm_pp_2nd(scheduler, *args)
1349
+ else:
1350
+ raise NotImplementedError
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ diffusers
2
+ accelerate
3
+ transformers
4
+ torch
5
+ torchvision
scheduling_dpmsolver_multistep_inject.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 TSAIL Team and 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
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ # from diffusers.utils import randn_tensor
25
+ from diffusers.utils.torch_utils import randn_tensor
26
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
27
+
28
+
29
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
30
+ def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999):
31
+ """
32
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
33
+ (1-beta) over time from t = [0,1].
34
+
35
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
36
+ to that part of the diffusion process.
37
+
38
+
39
+ Args:
40
+ num_diffusion_timesteps (`int`): the number of betas to produce.
41
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
42
+ prevent singularities.
43
+
44
+ Returns:
45
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
46
+ """
47
+
48
+ def alpha_bar(time_step):
49
+ return math.cos((time_step + 0.008) / 1.008 * math.pi / 2) ** 2
50
+
51
+ betas = []
52
+ for i in range(num_diffusion_timesteps):
53
+ t1 = i / num_diffusion_timesteps
54
+ t2 = (i + 1) / num_diffusion_timesteps
55
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
56
+ return torch.tensor(betas, dtype=torch.float32)
57
+
58
+
59
+ class DPMSolverMultistepSchedulerInject(SchedulerMixin, ConfigMixin):
60
+ """
61
+ DPM-Solver (and the improved version DPM-Solver++) is a fast dedicated high-order solver for diffusion ODEs with
62
+ the convergence order guarantee. Empirically, sampling by DPM-Solver with only 20 steps can generate high-quality
63
+ samples, and it can generate quite good samples even in only 10 steps.
64
+
65
+ For more details, see the original paper: https://arxiv.org/abs/2206.00927 and https://arxiv.org/abs/2211.01095
66
+
67
+ Currently, we support the multistep DPM-Solver for both noise prediction models and data prediction models. We
68
+ recommend to use `solver_order=2` for guided sampling, and `solver_order=3` for unconditional sampling.
69
+
70
+ We also support the "dynamic thresholding" method in Imagen (https://arxiv.org/abs/2205.11487). For pixel-space
71
+ diffusion models, you can set both `algorithm_type="dpmsolver++"` and `thresholding=True` to use the dynamic
72
+ thresholding. Note that the thresholding method is unsuitable for latent-space diffusion models (such as
73
+ stable-diffusion).
74
+
75
+ We also support the SDE variant of DPM-Solver and DPM-Solver++, which is a fast SDE solver for the reverse
76
+ diffusion SDE. Currently we only support the first-order and second-order solvers. We recommend using the
77
+ second-order `sde-dpmsolver++`.
78
+
79
+ [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
80
+ function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
81
+ [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
82
+ [`~SchedulerMixin.from_pretrained`] functions.
83
+
84
+ Args:
85
+ num_train_timesteps (`int`): number of diffusion steps used to train the model.
86
+ beta_start (`float`): the starting `beta` value of inference.
87
+ beta_end (`float`): the final `beta` value.
88
+ beta_schedule (`str`):
89
+ the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
90
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
91
+ trained_betas (`np.ndarray`, optional):
92
+ option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
93
+ solver_order (`int`, default `2`):
94
+ the order of DPM-Solver; can be `1` or `2` or `3`. We recommend to use `solver_order=2` for guided
95
+ sampling, and `solver_order=3` for unconditional sampling.
96
+ prediction_type (`str`, default `epsilon`, optional):
97
+ prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
98
+ process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
99
+ https://imagen.research.google/video/paper.pdf)
100
+ thresholding (`bool`, default `False`):
101
+ whether to use the "dynamic thresholding" method (introduced by Imagen, https://arxiv.org/abs/2205.11487).
102
+ For pixel-space diffusion models, you can set both `algorithm_type=dpmsolver++` and `thresholding=True` to
103
+ use the dynamic thresholding. Note that the thresholding method is unsuitable for latent-space diffusion
104
+ models (such as stable-diffusion).
105
+ dynamic_thresholding_ratio (`float`, default `0.995`):
106
+ the ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen
107
+ (https://arxiv.org/abs/2205.11487).
108
+ sample_max_value (`float`, default `1.0`):
109
+ the threshold value for dynamic thresholding. Valid only when `thresholding=True` and
110
+ `algorithm_type="dpmsolver++`.
111
+ algorithm_type (`str`, default `dpmsolver++`):
112
+ the algorithm type for the solver. Either `dpmsolver` or `dpmsolver++` or `sde-dpmsolver` or
113
+ `sde-dpmsolver++`. The `dpmsolver` type implements the algorithms in https://arxiv.org/abs/2206.00927, and
114
+ the `dpmsolver++` type implements the algorithms in https://arxiv.org/abs/2211.01095. We recommend to use
115
+ `dpmsolver++` or `sde-dpmsolver++` with `solver_order=2` for guided sampling (e.g. stable-diffusion).
116
+ solver_type (`str`, default `midpoint`):
117
+ the solver type for the second-order solver. Either `midpoint` or `heun`. The solver type slightly affects
118
+ the sample quality, especially for small number of steps. We empirically find that `midpoint` solvers are
119
+ slightly better, so we recommend to use the `midpoint` type.
120
+ lower_order_final (`bool`, default `True`):
121
+ whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. We empirically
122
+ find this trick can stabilize the sampling of DPM-Solver for steps < 15, especially for steps <= 10.
123
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
124
+ This parameter controls whether to use Karras sigmas (Karras et al. (2022) scheme) for step sizes in the
125
+ noise schedule during the sampling process. If True, the sigmas will be determined according to a sequence
126
+ of noise levels {σi} as defined in Equation (5) of the paper https://arxiv.org/pdf/2206.00364.pdf.
127
+ lambda_min_clipped (`float`, default `-inf`):
128
+ the clipping threshold for the minimum value of lambda(t) for numerical stability. This is critical for
129
+ cosine (squaredcos_cap_v2) noise schedule.
130
+ variance_type (`str`, *optional*):
131
+ Set to "learned" or "learned_range" for diffusion models that predict variance. For example, OpenAI's
132
+ guided-diffusion (https://github.com/openai/guided-diffusion) predicts both mean and variance of the
133
+ Gaussian distribution in the model's output. DPM-Solver only needs the "mean" output because it is based on
134
+ diffusion ODEs. whether the model's output contains the predicted Gaussian variance. For example, OpenAI's
135
+ guided-diffusion (https://github.com/openai/guided-diffusion) predicts both mean and variance of the
136
+ Gaussian distribution in the model's output. DPM-Solver only needs the "mean" output because it is based on
137
+ diffusion ODEs.
138
+ """
139
+
140
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
141
+ order = 1
142
+
143
+ @register_to_config
144
+ def __init__(
145
+ self,
146
+ num_train_timesteps: int = 1000,
147
+ beta_start: float = 0.0001,
148
+ beta_end: float = 0.02,
149
+ beta_schedule: str = "linear",
150
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
151
+ solver_order: int = 2,
152
+ prediction_type: str = "epsilon",
153
+ thresholding: bool = False,
154
+ dynamic_thresholding_ratio: float = 0.995,
155
+ sample_max_value: float = 1.0,
156
+ algorithm_type: str = "dpmsolver++",
157
+ solver_type: str = "midpoint",
158
+ lower_order_final: bool = True,
159
+ use_karras_sigmas: Optional[bool] = False,
160
+ lambda_min_clipped: float = -float("inf"),
161
+ variance_type: Optional[str] = None,
162
+ ):
163
+ if trained_betas is not None:
164
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
165
+ elif beta_schedule == "linear":
166
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
167
+ elif beta_schedule == "scaled_linear":
168
+ # this schedule is very specific to the latent diffusion model.
169
+ self.betas = (
170
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
171
+ )
172
+ elif beta_schedule == "squaredcos_cap_v2":
173
+ # Glide cosine schedule
174
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
175
+ else:
176
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
177
+
178
+ self.alphas = 1.0 - self.betas
179
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
180
+ # Currently we only support VP-type noise schedule
181
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
182
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
183
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
184
+
185
+ # standard deviation of the initial noise distribution
186
+ self.init_noise_sigma = 1.0
187
+
188
+ # settings for DPM-Solver
189
+ if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
190
+ if algorithm_type == "deis":
191
+ self.register_to_config(algorithm_type="dpmsolver++")
192
+ else:
193
+ raise NotImplementedError(f"{algorithm_type} does is not implemented for {self.__class__}")
194
+
195
+ if solver_type not in ["midpoint", "heun"]:
196
+ if solver_type in ["logrho", "bh1", "bh2"]:
197
+ self.register_to_config(solver_type="midpoint")
198
+ else:
199
+ raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}")
200
+
201
+ # setable values
202
+ self.num_inference_steps = None
203
+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
204
+ self.timesteps = torch.from_numpy(timesteps)
205
+ self.model_outputs = [None] * solver_order
206
+ self.lower_order_nums = 0
207
+ self.use_karras_sigmas = use_karras_sigmas
208
+
209
+ def set_timesteps(self, num_inference_steps: int = None, device: Union[str, torch.device] = None):
210
+ """
211
+ Sets the timesteps used for the diffusion chain. Supporting function to be run before inference.
212
+
213
+ Args:
214
+ num_inference_steps (`int`):
215
+ the number of diffusion steps used when generating samples with a pre-trained model.
216
+ device (`str` or `torch.device`, optional):
217
+ the device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
218
+ """
219
+ # Clipping the minimum of all lambda(t) for numerical stability.
220
+ # This is critical for cosine (squaredcos_cap_v2) noise schedule.
221
+ clipped_idx = torch.searchsorted(torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped)
222
+ timesteps = (
223
+ np.linspace(0, self.config.num_train_timesteps - 1 - clipped_idx, num_inference_steps + 1)
224
+ .round()[::-1][:-1]
225
+ .copy()
226
+ .astype(np.int64)
227
+ )
228
+
229
+ if self.use_karras_sigmas:
230
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
231
+ log_sigmas = np.log(sigmas)
232
+ sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
233
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
234
+ timesteps = np.flip(timesteps).copy().astype(np.int64)
235
+
236
+ # when num_inference_steps == num_train_timesteps, we can end up with
237
+ # duplicates in timesteps.
238
+ _, unique_indices = np.unique(timesteps, return_index=True)
239
+ timesteps = timesteps[np.sort(unique_indices)]
240
+
241
+ self.timesteps = torch.from_numpy(timesteps).to(device)
242
+
243
+ self.num_inference_steps = len(timesteps)
244
+
245
+ self.model_outputs = [
246
+ None,
247
+ ] * self.config.solver_order
248
+ self.lower_order_nums = 0
249
+
250
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
251
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
252
+ """
253
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
254
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
255
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
256
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
257
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
258
+
259
+ https://arxiv.org/abs/2205.11487
260
+ """
261
+ dtype = sample.dtype
262
+ batch_size, channels, height, width = sample.shape
263
+
264
+ if dtype not in (torch.float32, torch.float64):
265
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
266
+
267
+ # Flatten sample for doing quantile calculation along each image
268
+ sample = sample.reshape(batch_size, channels * height * width)
269
+
270
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
271
+
272
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
273
+ s = torch.clamp(
274
+ s, min=1, max=self.config.sample_max_value
275
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
276
+
277
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
278
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
279
+
280
+ sample = sample.reshape(batch_size, channels, height, width)
281
+ sample = sample.to(dtype)
282
+
283
+ return sample
284
+
285
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
286
+ def _sigma_to_t(self, sigma, log_sigmas):
287
+ # get log sigma
288
+ log_sigma = np.log(sigma)
289
+
290
+ # get distribution
291
+ dists = log_sigma - log_sigmas[:, np.newaxis]
292
+
293
+ # get sigmas range
294
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
295
+ high_idx = low_idx + 1
296
+
297
+ low = log_sigmas[low_idx]
298
+ high = log_sigmas[high_idx]
299
+
300
+ # interpolate sigmas
301
+ w = (low - log_sigma) / (low - high)
302
+ w = np.clip(w, 0, 1)
303
+
304
+ # transform interpolation to time range
305
+ t = (1 - w) * low_idx + w * high_idx
306
+ t = t.reshape(sigma.shape)
307
+ return t
308
+
309
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
310
+ def _convert_to_karras(self, in_sigmas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor:
311
+ """Constructs the noise schedule of Karras et al. (2022)."""
312
+
313
+ sigma_min: float = in_sigmas[-1].item()
314
+ sigma_max: float = in_sigmas[0].item()
315
+
316
+ rho = 7.0 # 7.0 is the value used in the paper
317
+ ramp = np.linspace(0, 1, num_inference_steps)
318
+ min_inv_rho = sigma_min ** (1 / rho)
319
+ max_inv_rho = sigma_max ** (1 / rho)
320
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
321
+ return sigmas
322
+
323
+ def convert_model_output(
324
+ self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor
325
+ ) -> torch.FloatTensor:
326
+ """
327
+ Convert the model output to the corresponding type that the algorithm (DPM-Solver / DPM-Solver++) needs.
328
+
329
+ DPM-Solver is designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to
330
+ discretize an integral of the data prediction model. So we need to first convert the model output to the
331
+ corresponding type to match the algorithm.
332
+
333
+ Note that the algorithm type and the model type is decoupled. That is to say, we can use either DPM-Solver or
334
+ DPM-Solver++ for both noise prediction model and data prediction model.
335
+
336
+ Args:
337
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
338
+ timestep (`int`): current discrete timestep in the diffusion chain.
339
+ sample (`torch.FloatTensor`):
340
+ current instance of sample being created by diffusion process.
341
+
342
+ Returns:
343
+ `torch.FloatTensor`: the converted model output.
344
+ """
345
+
346
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
347
+ if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
348
+ if self.config.prediction_type == "epsilon":
349
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
350
+ if self.config.variance_type in ["learned", "learned_range"]:
351
+ model_output = model_output[:, :3]
352
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
353
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
354
+ elif self.config.prediction_type == "sample":
355
+ x0_pred = model_output
356
+ elif self.config.prediction_type == "v_prediction":
357
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
358
+ x0_pred = alpha_t * sample - sigma_t * model_output
359
+ else:
360
+ raise ValueError(
361
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
362
+ " `v_prediction` for the DPMSolverMultistepScheduler."
363
+ )
364
+
365
+ if self.config.thresholding:
366
+ x0_pred = self._threshold_sample(x0_pred)
367
+
368
+ return x0_pred
369
+
370
+ # DPM-Solver needs to solve an integral of the noise prediction model.
371
+ elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
372
+ if self.config.prediction_type == "epsilon":
373
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
374
+ if self.config.variance_type in ["learned", "learned_range"]:
375
+ epsilon = model_output[:, :3]
376
+ else:
377
+ epsilon = model_output
378
+ elif self.config.prediction_type == "sample":
379
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
380
+ epsilon = (sample - alpha_t * model_output) / sigma_t
381
+ elif self.config.prediction_type == "v_prediction":
382
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
383
+ epsilon = alpha_t * model_output + sigma_t * sample
384
+ else:
385
+ raise ValueError(
386
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
387
+ " `v_prediction` for the DPMSolverMultistepScheduler."
388
+ )
389
+
390
+ if self.config.thresholding:
391
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
392
+ x0_pred = (sample - sigma_t * epsilon) / alpha_t
393
+ x0_pred = self._threshold_sample(x0_pred)
394
+ epsilon = (sample - alpha_t * x0_pred) / sigma_t
395
+
396
+ return epsilon
397
+
398
+ def dpm_solver_first_order_update(
399
+ self,
400
+ model_output: torch.FloatTensor,
401
+ timestep: int,
402
+ prev_timestep: int,
403
+ sample: torch.FloatTensor,
404
+ noise: Optional[torch.FloatTensor] = None,
405
+ ) -> torch.FloatTensor:
406
+ """
407
+ One step for the first-order DPM-Solver (equivalent to DDIM).
408
+
409
+ See https://arxiv.org/abs/2206.00927 for the detailed derivation.
410
+
411
+ Args:
412
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
413
+ timestep (`int`): current discrete timestep in the diffusion chain.
414
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
415
+ sample (`torch.FloatTensor`):
416
+ current instance of sample being created by diffusion process.
417
+
418
+ Returns:
419
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
420
+ """
421
+ lambda_t, lambda_s = self.lambda_t[prev_timestep], self.lambda_t[timestep]
422
+ alpha_t, alpha_s = self.alpha_t[prev_timestep], self.alpha_t[timestep]
423
+ sigma_t, sigma_s = self.sigma_t[prev_timestep], self.sigma_t[timestep]
424
+ h = lambda_t - lambda_s
425
+ if self.config.algorithm_type == "dpmsolver++":
426
+
427
+ x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
428
+ elif self.config.algorithm_type == "dpmsolver":
429
+
430
+ x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output
431
+ elif self.config.algorithm_type == "sde-dpmsolver++":
432
+ assert noise is not None
433
+ x_t = (
434
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
435
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
436
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
437
+ )
438
+ elif self.config.algorithm_type == "sde-dpmsolver":
439
+ assert noise is not None
440
+ x_t = (
441
+ (alpha_t / alpha_s) * sample
442
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output
443
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
444
+ )
445
+ return x_t
446
+
447
+ def multistep_dpm_solver_second_order_update(
448
+ self,
449
+ model_output_list: List[torch.FloatTensor],
450
+ timestep_list: List[int],
451
+ prev_timestep: int,
452
+ sample: torch.FloatTensor,
453
+ noise: Optional[torch.FloatTensor] = None,
454
+ ) -> torch.FloatTensor:
455
+ """
456
+ One step for the second-order multistep DPM-Solver.
457
+
458
+ Args:
459
+ model_output_list (`List[torch.FloatTensor]`):
460
+ direct outputs from learned diffusion model at current and latter timesteps.
461
+ timestep (`int`): current and latter discrete timestep in the diffusion chain.
462
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
463
+ sample (`torch.FloatTensor`):
464
+ current instance of sample being created by diffusion process.
465
+
466
+ Returns:
467
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
468
+ """
469
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
470
+ m0, m1 = model_output_list[-1], model_output_list[-2]
471
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
472
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
473
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
474
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
475
+ r0 = h_0 / h
476
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
477
+ if self.config.algorithm_type == "dpmsolver++":
478
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
479
+ if self.config.solver_type == "midpoint":
480
+ x_t = (
481
+ (sigma_t / sigma_s0) * sample
482
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
483
+ - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
484
+ )
485
+ elif self.config.solver_type == "heun":
486
+ x_t = (
487
+ (sigma_t / sigma_s0) * sample
488
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
489
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
490
+ )
491
+ elif self.config.algorithm_type == "dpmsolver":
492
+
493
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
494
+ if self.config.solver_type == "midpoint":
495
+ x_t = (
496
+ (alpha_t / alpha_s0) * sample
497
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
498
+ - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
499
+ )
500
+ elif self.config.solver_type == "heun":
501
+ x_t = (
502
+ (alpha_t / alpha_s0) * sample
503
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
504
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
505
+ )
506
+ elif self.config.algorithm_type == "sde-dpmsolver++":
507
+ assert noise is not None
508
+ if self.config.solver_type == "midpoint":
509
+ x_t = (
510
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
511
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
512
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
513
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
514
+ )
515
+ elif self.config.solver_type == "heun":
516
+ x_t = (
517
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
518
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
519
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
520
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
521
+ )
522
+ elif self.config.algorithm_type == "sde-dpmsolver":
523
+ assert noise is not None
524
+ if self.config.solver_type == "midpoint":
525
+ x_t = (
526
+ (alpha_t / alpha_s0) * sample
527
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
528
+ - (sigma_t * (torch.exp(h) - 1.0)) * D1
529
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
530
+ )
531
+ elif self.config.solver_type == "heun":
532
+ x_t = (
533
+ (alpha_t / alpha_s0) * sample
534
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
535
+ - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
536
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
537
+ )
538
+ return x_t
539
+
540
+ def multistep_dpm_solver_third_order_update(
541
+ self,
542
+ model_output_list: List[torch.FloatTensor],
543
+ timestep_list: List[int],
544
+ prev_timestep: int,
545
+ sample: torch.FloatTensor,
546
+ ) -> torch.FloatTensor:
547
+ """
548
+ One step for the third-order multistep DPM-Solver.
549
+
550
+ Args:
551
+ model_output_list (`List[torch.FloatTensor]`):
552
+ direct outputs from learned diffusion model at current and latter timesteps.
553
+ timestep (`int`): current and latter discrete timestep in the diffusion chain.
554
+ prev_timestep (`int`): previous discrete timestep in the diffusion chain.
555
+ sample (`torch.FloatTensor`):
556
+ current instance of sample being created by diffusion process.
557
+
558
+ Returns:
559
+ `torch.FloatTensor`: the sample tensor at the previous timestep.
560
+ """
561
+ t, s0, s1, s2 = prev_timestep, timestep_list[-1], timestep_list[-2], timestep_list[-3]
562
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
563
+ lambda_t, lambda_s0, lambda_s1, lambda_s2 = (
564
+ self.lambda_t[t],
565
+ self.lambda_t[s0],
566
+ self.lambda_t[s1],
567
+ self.lambda_t[s2],
568
+ )
569
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
570
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
571
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
572
+ r0, r1 = h_0 / h, h_1 / h
573
+ D0 = m0
574
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
575
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
576
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
577
+ if self.config.algorithm_type == "dpmsolver++":
578
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
579
+ x_t = (
580
+ (sigma_t / sigma_s0) * sample
581
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
582
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
583
+ - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
584
+ )
585
+ elif self.config.algorithm_type == "dpmsolver":
586
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
587
+ x_t = (
588
+ (alpha_t / alpha_s0) * sample
589
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
590
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
591
+ - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
592
+ )
593
+ return x_t
594
+
595
+ def step(
596
+ self,
597
+ model_output: torch.FloatTensor,
598
+ timestep: int,
599
+ sample: torch.FloatTensor,
600
+ generator=None,
601
+ return_dict: bool = True,
602
+ variance_noise: Optional[torch.FloatTensor] = None,
603
+ ) -> Union[SchedulerOutput, Tuple]:
604
+ """
605
+ Step function propagating the sample with the multistep DPM-Solver.
606
+
607
+ Args:
608
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
609
+ timestep (`int`): current discrete timestep in the diffusion chain.
610
+ sample (`torch.FloatTensor`):
611
+ current instance of sample being created by diffusion process.
612
+ return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
613
+
614
+ Returns:
615
+ [`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
616
+ True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
617
+
618
+ """
619
+ if self.num_inference_steps is None:
620
+ raise ValueError(
621
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
622
+ )
623
+
624
+ if isinstance(timestep, torch.Tensor):
625
+ timestep = timestep.to(self.timesteps.device)
626
+ step_index = (self.timesteps == timestep).nonzero()
627
+ if len(step_index) == 0:
628
+ step_index = len(self.timesteps) - 1
629
+ else:
630
+ step_index = step_index.item()
631
+ prev_timestep = 0 if step_index == len(self.timesteps) - 1 else self.timesteps[step_index + 1]
632
+ lower_order_final = (
633
+ (step_index == len(self.timesteps) - 1) and self.config.lower_order_final and len(self.timesteps) < 15
634
+ )
635
+ lower_order_second = (
636
+ (step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
637
+ )
638
+
639
+ model_output = self.convert_model_output(model_output, timestep, sample)
640
+ for i in range(self.config.solver_order - 1):
641
+ self.model_outputs[i] = self.model_outputs[i + 1]
642
+ self.model_outputs[-1] = model_output
643
+
644
+ if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"] and variance_noise is None:
645
+ noise = randn_tensor(
646
+ model_output.shape, generator=generator, device=model_output.device, dtype=model_output.dtype
647
+ )
648
+ elif self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
649
+ noise = variance_noise
650
+ else:
651
+ noise = None
652
+
653
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
654
+ prev_sample = self.dpm_solver_first_order_update(
655
+ model_output, timestep, prev_timestep, sample, noise=noise
656
+ )
657
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
658
+ timestep_list = [self.timesteps[step_index - 1], timestep]
659
+ prev_sample = self.multistep_dpm_solver_second_order_update(
660
+ self.model_outputs, timestep_list, prev_timestep, sample, noise=noise
661
+ )
662
+ else:
663
+ raise NotImplementedError()
664
+
665
+ if self.lower_order_nums < self.config.solver_order:
666
+ self.lower_order_nums += 1
667
+
668
+ if not return_dict:
669
+ return (prev_sample,)
670
+
671
+ return SchedulerOutput(prev_sample=prev_sample)
672
+
673
+ def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
674
+ """
675
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
676
+ current timestep.
677
+
678
+ Args:
679
+ sample (`torch.FloatTensor`): input sample
680
+
681
+ Returns:
682
+ `torch.FloatTensor`: scaled input sample
683
+ """
684
+ return sample
685
+
686
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
687
+ def add_noise(
688
+ self,
689
+ original_samples: torch.FloatTensor,
690
+ noise: torch.FloatTensor,
691
+ timesteps: torch.IntTensor,
692
+ ) -> torch.FloatTensor:
693
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
694
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
695
+ timesteps = timesteps.to(original_samples.device)
696
+
697
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
698
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
699
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
700
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
701
+
702
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
703
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
704
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
705
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
706
+
707
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
708
+ return noisy_samples
709
+
710
+ def __len__(self):
711
+ return self.config.num_train_timesteps
share_btn.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = r"""async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file,
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ function getButtonText(componentId) {
27
+ const buttonEl = gradioEl.querySelector(`${componentId} button`);
28
+ return buttonEl ? buttonEl.textContent : '';
29
+ }
30
+
31
+ const gradioEl = document.querySelector('body > gradio-app');
32
+ const imgEls = [gradioEl.querySelector('#input_image img'), gradioEl.querySelector('#output_image img')];
33
+ const concepts = [
34
+ { value: getButtonText('#box1'), parent: gradioEl.querySelector('#box1 span[data-testid="block-info"]') },
35
+ { value: getButtonText('#box2'), parent: gradioEl.querySelector('#box2 span[data-testid="block-info"]') },
36
+ { value: getButtonText('#box3'), parent: gradioEl.querySelector('#box3 span[data-testid="block-info"]') }
37
+ ];
38
+
39
+ const promptTxt = gradioEl.querySelector('#target_prompt input').value;
40
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
41
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
42
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
43
+ if(!imgEls[1]){
44
+ return;
45
+ };
46
+ shareBtnEl.style.pointerEvents = 'none';
47
+ shareIconEl.style.display = 'none';
48
+ loadingIconEl.style.removeProperty('display');
49
+
50
+ async function processImage(imgEl, imgId) {
51
+ const res = await fetch(imgEl.src);
52
+ const blob = await res.blob();
53
+ const fileType = blob.type.includes('png') ? 'png' : 'jpg';
54
+ const fileName = `diffuse-the-rest-${imgId}.${fileType}`;
55
+ return new File([blob], fileName, { type: blob.type });
56
+ }
57
+
58
+ const files = await Promise.all(imgEls.map((imgEl, index) => processImage(imgEl, Date.now() + index % 200)));
59
+ const urls = await Promise.all(files.map((file) => uploadFile(file)));
60
+
61
+ const labels = ['Source image', 'Target image'];
62
+ const htmlImgs = urls.map((url, index) => `<div>${labels[index]}: <img src='${url}' width='400' height='400' style="margin: 0"></div>`);
63
+
64
+ let descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>${htmlImgs.join(`\n`)}</div>`;
65
+
66
+ if (promptTxt) {
67
+ descriptionMd += `<span style="font-size:1.2em">Target image prompt: <b>${promptTxt}</b></span><br>`;
68
+ } else {
69
+ descriptionMd += `<span style="font-size:1.2em">Target image prompt: <b>""</b></span><br>`;
70
+ }
71
+
72
+ const conceptHeaders = [];
73
+ const conceptDescriptions = [];
74
+ const conceptTableRows = [];
75
+ concepts.forEach((concept, index) => {
76
+ if (concept.value) {
77
+ const label = concept.parent.textContent.includes('Negative') ? `remove concept` : `add concept`;
78
+ conceptHeaders.push(`<th>${label}</th>`);
79
+ conceptDescriptions.push(`${label}: ${concept.value}`);
80
+ conceptTableRows.push(`<td>${concept.value}</td>`);
81
+ }
82
+ });
83
+
84
+ let title = 'Editing';
85
+ if (promptTxt) {
86
+ title += ` "${promptTxt}"`;
87
+ }
88
+ if (conceptDescriptions.length > 0) {
89
+ title += ` to ${conceptDescriptions.join(', ')}`;
90
+ descriptionMd += `<table style="font-size: 1.1em">
91
+ <tr>
92
+ ${conceptHeaders.join('\n')}
93
+ </tr>
94
+ <tr>
95
+ ${conceptTableRows.join('\n')}
96
+ </tr>
97
+ </table>`;
98
+ }
99
+
100
+ const params = new URLSearchParams({
101
+ title: title,
102
+ description: descriptionMd,
103
+ preview: true,
104
+ });
105
+ const paramsStr = params.toString();
106
+ window.open(`https://huggingface.co/spaces/editing-images/ledits/discussions/new?${paramsStr}`, '_blank');
107
+ shareBtnEl.style.removeProperty('pointer-events');
108
+ shareIconEl.style.removeProperty('display');
109
+ loadingIconEl.style.display = 'none';
110
+ }"""
style.css ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This CSS file is modified from:
3
+ https://huggingface.co/spaces/DeepFloyd/IF/blob/main/style.css
4
+ */
5
+
6
+ h1 {
7
+ text-align: center;
8
+ }
9
+
10
+ .gradio-container {
11
+ font-family: 'IBM Plex Sans', sans-serif;
12
+ }
13
+
14
+ .gr-button {
15
+ color: white;
16
+ border-color: black;
17
+ background: black;
18
+ }
19
+
20
+ input[type='range'] {
21
+ accent-color: black;
22
+ }
23
+
24
+ .dark input[type='range'] {
25
+ accent-color: #dfdfdf;
26
+ }
27
+
28
+ .container {
29
+ max-width: 730px;
30
+ margin: auto;
31
+ }
32
+
33
+
34
+ .gr-button:focus {
35
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
36
+ outline: none;
37
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
38
+ --tw-border-opacity: 1;
39
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
40
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
41
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
42
+ --tw-ring-opacity: .5;
43
+ }
44
+
45
+ .gr-form {
46
+ flex: 1 1 50%;
47
+ border-top-right-radius: 0;
48
+ border-bottom-right-radius: 0;
49
+ }
50
+
51
+ #prompt-container {
52
+ gap: 0;
53
+ }
54
+
55
+ #prompt-text-input,
56
+ #negative-prompt-text-input {
57
+ padding: .45rem 0.625rem
58
+ }
59
+
60
+ /* #component-16 {
61
+ border-top-width: 1px !important;
62
+ margin-top: 1em
63
+ } */
64
+
65
+ .image_duplication {
66
+ position: absolute;
67
+ width: 100px;
68
+ left: 50px
69
+ }
70
+
71
+ #component-0 {
72
+ max-width: 730px;
73
+ margin: auto;
74
+ padding-top: 1.5rem;
75
+ }
76
+ #share-btn-container{padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;margin-top: 0.35em;}
77
+ div#share-btn-container > div {flex-direction: row;background: black;align-items: center}
78
+ #share-btn-container:hover {background-color: #060606}
79
+ #share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;font-size: 15px;}
80
+ #share-btn * {all: unset}
81
+ #share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}
82
+ #share-btn-container .wrap {display: none !important}
83
+ #share-btn-container.hidden {display: none!important}
utils.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PIL
2
+ from PIL import Image, ImageDraw ,ImageFont
3
+ from matplotlib import pyplot as plt
4
+ import torchvision.transforms as T
5
+ import os
6
+ import torch
7
+ import yaml
8
+
9
+ def show_torch_img(img):
10
+ img = to_np_image(img)
11
+ plt.imshow(img)
12
+ plt.axis("off")
13
+
14
+ def to_np_image(all_images):
15
+ all_images = (all_images.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()[0]
16
+ return all_images
17
+
18
+ def tensor_to_pil(tensor_imgs):
19
+ if type(tensor_imgs) == list:
20
+ tensor_imgs = torch.cat(tensor_imgs)
21
+ tensor_imgs = (tensor_imgs / 2 + 0.5).clamp(0, 1)
22
+ to_pil = T.ToPILImage()
23
+ pil_imgs = [to_pil(img) for img in tensor_imgs]
24
+ return pil_imgs
25
+
26
+ def pil_to_tensor(pil_imgs):
27
+ to_torch = T.ToTensor()
28
+ if type(pil_imgs) == PIL.Image.Image:
29
+ tensor_imgs = to_torch(pil_imgs).unsqueeze(0)*2-1
30
+ elif type(pil_imgs) == list:
31
+ tensor_imgs = torch.cat([to_torch(pil_imgs).unsqueeze(0)*2-1 for img in pil_imgs]).to(device)
32
+ else:
33
+ raise Exception("Input need to be PIL.Image or list of PIL.Image")
34
+ return tensor_imgs
35
+
36
+
37
+ ## TODO implement this
38
+ # n = 10
39
+ # num_rows = 4
40
+ # num_col = n // num_rows
41
+ # num_col = num_col + 1 if n % num_rows else num_col
42
+ # num_col
43
+ def add_margin(pil_img, top = 0, right = 0, bottom = 0,
44
+ left = 0, color = (255,255,255)):
45
+ width, height = pil_img.size
46
+ new_width = width + right + left
47
+ new_height = height + top + bottom
48
+ result = Image.new(pil_img.mode, (new_width, new_height), color)
49
+
50
+ result.paste(pil_img, (left, top))
51
+ return result
52
+
53
+ def image_grid(imgs, rows = 1, cols = None,
54
+ size = None,
55
+ titles = None, text_pos = (0, 0)):
56
+ if type(imgs) == list and type(imgs[0]) == torch.Tensor:
57
+ imgs = torch.cat(imgs)
58
+ if type(imgs) == torch.Tensor:
59
+ imgs = tensor_to_pil(imgs)
60
+
61
+ if not size is None:
62
+ imgs = [img.resize((size,size)) for img in imgs]
63
+ if cols is None:
64
+ cols = len(imgs)
65
+ assert len(imgs) >= rows*cols
66
+
67
+ top=20
68
+ w, h = imgs[0].size
69
+ delta = 0
70
+ if len(imgs)> 1 and not imgs[1].size[1] == h:
71
+ delta = top
72
+ h = imgs[1].size[1]
73
+ if not titles is None:
74
+ font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf",
75
+ size = 20, encoding="unic")
76
+ h = top + h
77
+ grid = Image.new('RGB', size=(cols*w, rows*h+delta))
78
+ for i, img in enumerate(imgs):
79
+
80
+ if not titles is None:
81
+ img = add_margin(img, top = top, bottom = 0,left=0)
82
+ draw = ImageDraw.Draw(img)
83
+ draw.text(text_pos, titles[i],(0,0,0),
84
+ font = font)
85
+ if not delta == 0 and i > 0:
86
+ grid.paste(img, box=(i%cols*w, i//cols*h+delta))
87
+ else:
88
+ grid.paste(img, box=(i%cols*w, i//cols*h))
89
+
90
+ return grid
91
+
92
+
93
+ """
94
+ input_folder - dataset folder
95
+ """
96
+ def load_dataset(input_folder):
97
+ # full_file_names = glob.glob(input_folder)
98
+ # class_names = [x[0] for x in os.walk(input_folder)]
99
+ class_names = next(os.walk(input_folder))[1]
100
+ class_names[:] = [d for d in class_names if not d[0] == '.']
101
+ file_names=[]
102
+ for class_name in class_names:
103
+ cur_path = os.path.join(input_folder, class_name)
104
+ filenames = next(os.walk(cur_path), (None, None, []))[2]
105
+ filenames = [f for f in filenames if not f[0] == '.']
106
+ file_names.append(filenames)
107
+ return class_names, file_names
108
+
109
+
110
+ def dataset_from_yaml(yaml_location):
111
+ with open(yaml_location, 'r') as stream:
112
+ data_loaded = yaml.safe_load(stream)
113
+
114
+ return data_loaded