Linoy Tsaban commited on
Commit
4b8437d
·
1 Parent(s): 3e64644

Upload folder using huggingface_hub

Browse files
app.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pipeline_semantic_stable_diffusion_xl_img2img_ddpm import *
10
+ from torch import inference_mode
11
+ from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline, AutoencoderKL
12
+ from diffusers import DDIMScheduler
13
+ from share_btn import community_icon_html, loading_icon_html, share_js
14
+ import torch
15
+ from huggingface_hub import hf_hub_download
16
+ from diffusers import DiffusionPipeline
17
+ from cog_sdxl.dataset_and_utils import TokenEmbeddingsHandler
18
+ import json
19
+ from safetensors.torch import load_file
20
+ import lora
21
+ import copy
22
+ import json
23
+ import gc
24
+ import random
25
+
26
+ with open("sdxl_loras.json", "r") as file:
27
+ data = json.load(file)
28
+ sdxl_loras_raw = [
29
+ {
30
+ "image": item["image"],
31
+ "title": item["title"],
32
+ "repo": item["repo"],
33
+ "trigger_word": item["trigger_word"],
34
+ "weights": item["weights"],
35
+ "is_compatible": item["is_compatible"],
36
+ "is_pivotal": item.get("is_pivotal", False),
37
+ "text_embedding_weights": item.get("text_embedding_weights", None),
38
+ # "likes": item.get("likes", 0),
39
+ # "downloads": item.get("downloads", 0),
40
+ "is_nc": item.get("is_nc", False),
41
+ "edit_guidance_scale": item["edit_guidance_scale"],
42
+ "threshold": item["threshold"]
43
+ }
44
+ for item in data
45
+ ]
46
+
47
+ state_dicts = {}
48
+
49
+ for item in sdxl_loras_raw:
50
+ saved_name = hf_hub_download(item["repo"], item["weights"])
51
+ if not saved_name.endswith('.safetensors'):
52
+ state_dict = torch.load(saved_name)
53
+ else:
54
+ state_dict = load_file(saved_name)
55
+
56
+ state_dicts[item["repo"]] = {
57
+ "saved_name": saved_name,
58
+ "state_dict": state_dict
59
+ } | item
60
+
61
+
62
+
63
+ sd_model_id = "stabilityai/stable-diffusion-xl-base-1.0"
64
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
65
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
66
+ sd_pipe = SemanticStableDiffusionXLImg2ImgPipeline_DDPMInversion.from_pretrained(sd_model_id,
67
+ torch_dtype=torch.float16, variant="fp16", use_safetensors=True,vae=vae,
68
+ )
69
+ sd_pipe.scheduler = DDIMScheduler.from_config(sd_model_id, subfolder = "scheduler")
70
+
71
+ original_pipe = copy.deepcopy(sd_pipe)
72
+ sd_pipe.to(device)
73
+
74
+ last_lora = ""
75
+ last_merged = False
76
+ last_fused = False
77
+
78
+
79
+ def load_lora(sdxl_loras, lora_scale = 1.0, progress=gr.Progress(track_tqdm=True)):
80
+ global last_lora, last_merged, last_fused, sd_pipe
81
+
82
+ randomize()
83
+ random_lora_index = random.randrange(0, len(sdxl_loras), 1)
84
+
85
+ repo_name = sdxl_loras[random_lora_index]["repo"]
86
+ weight_name = sdxl_loras[random_lora_index]["weights"]
87
+
88
+ full_path_lora = state_dicts[repo_name]["saved_name"]
89
+ loaded_state_dict = copy.deepcopy(state_dicts[repo_name]["state_dict"])
90
+ cross_attention_kwargs = None
91
+ print(repo_name)
92
+ if last_lora != repo_name:
93
+ if last_merged:
94
+ del sd_pipe
95
+ gc.collect()
96
+ sd_pipe = copy.deepcopy(original_pipe)
97
+ sd_pipe.to(device)
98
+ elif(last_fused):
99
+ sd_pipe.unfuse_lora()
100
+ sd_pipe.unload_lora_weights()
101
+ is_compatible = sdxl_loras[random_lora_index]["is_compatible"]
102
+
103
+ if is_compatible:
104
+ sd_pipe.load_lora_weights(loaded_state_dict)
105
+ sd_pipe.fuse_lora(lora_scale)
106
+ last_fused = True
107
+ else:
108
+ is_pivotal = sdxl_loras[random_lora_index]["is_pivotal"]
109
+ if(is_pivotal):
110
+ sd_pipe.load_lora_weights(loaded_state_dict)
111
+ sd_pipe.fuse_lora(lora_scale)
112
+ last_fused = True
113
+
114
+ #Add the textual inversion embeddings from pivotal tuning models
115
+ text_embedding_name = sdxl_loras[random_lora_index]["text_embedding_weights"]
116
+ text_encoders = [sd_pipe.text_encoder, sd_pipe.text_encoder_2]
117
+ tokenizers = [sd_pipe.tokenizer, sd_pipe.tokenizer_2]
118
+ embedding_path = hf_hub_download(repo_id=repo_name, filename=text_embedding_name, repo_type="model")
119
+ embhandler = TokenEmbeddingsHandler(text_encoders, tokenizers)
120
+ embhandler.load_embeddings(embedding_path)
121
+
122
+ else:
123
+ merge_incompatible_lora(full_path_lora, lora_scale)
124
+ last_fused = False
125
+ last_merged = True
126
+ print("DONE")
127
+ return random_lora_index
128
+
129
+
130
+
131
+ ## SEGA ##
132
+
133
+ def edit(sdxl_loras,
134
+ input_image,
135
+ wts, zs,
136
+ do_inversion,
137
+
138
+ ):
139
+ show_share_button = gr.update(visible=True)
140
+
141
+ random_lora_index = load_lora(sdxl_loras)
142
+
143
+ src_prompt = ""
144
+ skip = 18
145
+ steps = 50
146
+ tar_cfg_scale = 15
147
+ src_cfg_scale = 3.5
148
+ tar_prompt = ""
149
+
150
+ if do_inversion:
151
+ image = load_image(input_image, device=device).to(torch.float16)
152
+ with inference_mode():
153
+ x0 = sd_pipe.vae.encode(image).latent_dist.sample() * sd_pipe.vae.config.scaling_factor
154
+ # invert and retrieve noise maps and latent
155
+ zs_tensor, wts_tensor = sd_pipe.invert(x0,
156
+ source_prompt= src_prompt,
157
+ # source_prompt_2 = None,
158
+ source_guidance_scale = src_cfg_scale,
159
+ negative_prompt = "blurry, ugly, bad quality",
160
+ # negative_prompt_2 = None,
161
+ num_inversion_steps = steps,
162
+ skip_steps = skip,
163
+ # eta = 1.0,
164
+ )
165
+
166
+ wts = gr.State(value=wts_tensor)
167
+ zs = gr.State(value=zs_tensor)
168
+ do_inversion = False
169
+
170
+
171
+ latnets = wts.value[skip].expand(1, -1, -1, -1)
172
+
173
+ editing_prompt = [sdxl_loras[random_lora_index]["trigger_word"]]
174
+ reverse_editing_direction = [False]
175
+ edit_warmup_steps = [2]
176
+ edit_guidance_scale = [sdxl_loras[random_lora_index]["edit_guidance_scale"]]
177
+ edit_threshold = [sdxl_loras[random_lora_index]["threshold"]]
178
+
179
+
180
+ editing_args = dict(
181
+ editing_prompt = editing_prompt,
182
+ reverse_editing_direction = reverse_editing_direction,
183
+ edit_warmup_steps=edit_warmup_steps,
184
+ edit_guidance_scale=edit_guidance_scale,
185
+ edit_threshold=edit_threshold,
186
+ edit_momentum_scale=0.3,
187
+ edit_mom_beta=0.6,
188
+ eta=1,)
189
+
190
+ sega_out = sd_pipe(prompt=tar_prompt, latents=latnets, guidance_scale = tar_cfg_scale,
191
+ # num_images_per_prompt=1,
192
+ # num_inference_steps=steps,
193
+ wts=wts.value, zs=zs.value[skip:], **editing_args)
194
+
195
+ lora_repo = sdxl_loras[random_lora_index]["repo"]
196
+ lora_desc = f"### LoRA Used To Edit this Image: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨ {'(non-commercial LoRA, `cc-by-nc`)' if sdxl_loras[random_lora_index]['is_nc'] else '' }"
197
+ lora_image = sdxl_loras[random_lora_index]["image"]
198
+
199
+ return sega_out.images[0], wts, zs, do_inversion, lora_image, lora_desc, gr.update(visible=True), gr.update(visible=True)
200
+
201
+
202
+
203
+
204
+ def randomize_seed_fn(seed, randomize_seed):
205
+ if randomize_seed:
206
+ seed = random.randint(0, np.iinfo(np.int32).max)
207
+ torch.manual_seed(seed)
208
+ return seed
209
+
210
+ def randomize():
211
+ seed = random.randint(0, np.iinfo(np.int32).max)
212
+ torch.manual_seed(seed)
213
+ torch.cuda.manual_seed(seed)
214
+ random.seed(seed)
215
+ np.random.seed(seed)
216
+
217
+
218
+ def crop_image(image):
219
+ h, w, c = image.shape
220
+ if h < w:
221
+ offset = (w - h) // 2
222
+ image = image[:, offset:offset + h]
223
+ elif w < h:
224
+ offset = (h - w) // 2
225
+ image = image[offset:offset + w]
226
+ image = np.array(Image.fromarray(image).resize((1024, 1024)))
227
+ return image
228
+
229
+
230
+
231
+
232
+ ########
233
+ # demo #
234
+ ########
235
+
236
+ with gr.Blocks(css="style.css") as demo:
237
+
238
+
239
+ def reset_do_inversion():
240
+ return True
241
+
242
+
243
+ gr.HTML(
244
+ """<h1><img src="https://i.imgur.com/jpMRW5y.png" alt="LEDITS LoRA Photobooth"></h1>""",
245
+ )
246
+ wts = gr.State()
247
+ zs = gr.State()
248
+ reconstruction = gr.State()
249
+ do_inversion = gr.State(value=True)
250
+ gr_sdxl_loras = gr.State(value=sdxl_loras_raw)
251
+
252
+ with gr.Row():
253
+ input_image = gr.Image(label="Input Image", interactive=True, source="webcam", height=512, width=512)
254
+ sega_edited_image = gr.Image(label=f"LEDITS Edited Image", interactive=False, elem_id="output_image", height=512, width=512)
255
+ # input_image.style(height=365, width=365)
256
+ # sega_edited_image.style(height=365, width=365)
257
+
258
+ with gr.Row():
259
+ lora_image = gr.Image(interactive=False, height=128, width=128, visible=False)
260
+ lora_desc = gr.HTML(visible=False)
261
+
262
+
263
+ with gr.Row():
264
+ run_button = gr.Button("Run again!", visible=True)
265
+
266
+
267
+ run_button.click(
268
+ fn=edit,
269
+ inputs=[gr_sdxl_loras,
270
+ input_image,
271
+ wts, zs,
272
+ do_inversion,
273
+
274
+ ],
275
+ outputs=[sega_edited_image, wts, zs, do_inversion, lora_image, lora_desc, lora_image, lora_desc])
276
+
277
+ input_image.change(
278
+ fn = reset_do_inversion,
279
+ outputs = [do_inversion],
280
+ queue = False).then(
281
+ fn=edit,
282
+ inputs=[gr_sdxl_loras,
283
+ input_image,
284
+ wts, zs,
285
+ do_inversion,
286
+
287
+
288
+ ],
289
+ outputs=[sega_edited_image, wts, zs, do_inversion, lora_image, lora_desc, lora_image, lora_desc]
290
+ )
291
+
292
+
293
+
294
+
295
+
296
+ demo.queue()
297
+ demo.launch(share=True)
cog_sdxl_dataset_and_utils.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dataset_and_utils.py file taken from https://github.com/replicate/cog-sdxl/blob/main/dataset_and_utils.py
2
+ import os
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import PIL
8
+ import torch
9
+ import torch.utils.checkpoint
10
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
11
+ from PIL import Image
12
+ from safetensors import safe_open
13
+ from safetensors.torch import save_file
14
+ from torch.utils.data import Dataset
15
+ from transformers import AutoTokenizer, PretrainedConfig
16
+
17
+
18
+ def prepare_image(
19
+ pil_image: PIL.Image.Image, w: int = 512, h: int = 512
20
+ ) -> torch.Tensor:
21
+ pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1)
22
+ arr = np.array(pil_image.convert("RGB"))
23
+ arr = arr.astype(np.float32) / 127.5 - 1
24
+ arr = np.transpose(arr, [2, 0, 1])
25
+ image = torch.from_numpy(arr).unsqueeze(0)
26
+ return image
27
+
28
+
29
+ def prepare_mask(
30
+ pil_image: PIL.Image.Image, w: int = 512, h: int = 512
31
+ ) -> torch.Tensor:
32
+ pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1)
33
+ arr = np.array(pil_image.convert("L"))
34
+ arr = arr.astype(np.float32) / 255.0
35
+ arr = np.expand_dims(arr, 0)
36
+ image = torch.from_numpy(arr).unsqueeze(0)
37
+ return image
38
+
39
+
40
+ class PreprocessedDataset(Dataset):
41
+ def __init__(
42
+ self,
43
+ csv_path: str,
44
+ tokenizer_1,
45
+ tokenizer_2,
46
+ vae_encoder,
47
+ text_encoder_1=None,
48
+ text_encoder_2=None,
49
+ do_cache: bool = False,
50
+ size: int = 512,
51
+ text_dropout: float = 0.0,
52
+ scale_vae_latents: bool = True,
53
+ substitute_caption_map: Dict[str, str] = {},
54
+ ):
55
+ super().__init__()
56
+
57
+ self.data = pd.read_csv(csv_path)
58
+ self.csv_path = csv_path
59
+
60
+ self.caption = self.data["caption"]
61
+ # make it lowercase
62
+ self.caption = self.caption.str.lower()
63
+ for key, value in substitute_caption_map.items():
64
+ self.caption = self.caption.str.replace(key.lower(), value)
65
+
66
+ self.image_path = self.data["image_path"]
67
+
68
+ if "mask_path" not in self.data.columns:
69
+ self.mask_path = None
70
+ else:
71
+ self.mask_path = self.data["mask_path"]
72
+
73
+ if text_encoder_1 is None:
74
+ self.return_text_embeddings = False
75
+ else:
76
+ self.text_encoder_1 = text_encoder_1
77
+ self.text_encoder_2 = text_encoder_2
78
+ self.return_text_embeddings = True
79
+ assert (
80
+ NotImplementedError
81
+ ), "Preprocessing Text Encoder is not implemented yet"
82
+
83
+ self.tokenizer_1 = tokenizer_1
84
+ self.tokenizer_2 = tokenizer_2
85
+
86
+ self.vae_encoder = vae_encoder
87
+ self.scale_vae_latents = scale_vae_latents
88
+ self.text_dropout = text_dropout
89
+
90
+ self.size = size
91
+
92
+ if do_cache:
93
+ self.vae_latents = []
94
+ self.tokens_tuple = []
95
+ self.masks = []
96
+
97
+ self.do_cache = True
98
+
99
+ print("Captions to train on: ")
100
+ for idx in range(len(self.data)):
101
+ token, vae_latent, mask = self._process(idx)
102
+ self.vae_latents.append(vae_latent)
103
+ self.tokens_tuple.append(token)
104
+ self.masks.append(mask)
105
+
106
+ del self.vae_encoder
107
+
108
+ else:
109
+ self.do_cache = False
110
+
111
+ @torch.no_grad()
112
+ def _process(
113
+ self, idx: int
114
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]:
115
+ image_path = self.image_path[idx]
116
+ image_path = os.path.join(os.path.dirname(self.csv_path), image_path)
117
+
118
+ image = PIL.Image.open(image_path).convert("RGB")
119
+ image = prepare_image(image, self.size, self.size).to(
120
+ dtype=self.vae_encoder.dtype, device=self.vae_encoder.device
121
+ )
122
+
123
+ caption = self.caption[idx]
124
+
125
+ print(caption)
126
+
127
+ # tokenizer_1
128
+ ti1 = self.tokenizer_1(
129
+ caption,
130
+ padding="max_length",
131
+ max_length=77,
132
+ truncation=True,
133
+ add_special_tokens=True,
134
+ return_tensors="pt",
135
+ ).input_ids
136
+
137
+ ti2 = self.tokenizer_2(
138
+ caption,
139
+ padding="max_length",
140
+ max_length=77,
141
+ truncation=True,
142
+ add_special_tokens=True,
143
+ return_tensors="pt",
144
+ ).input_ids
145
+
146
+ vae_latent = self.vae_encoder.encode(image).latent_dist.sample()
147
+
148
+ if self.scale_vae_latents:
149
+ vae_latent = vae_latent * self.vae_encoder.config.scaling_factor
150
+
151
+ if self.mask_path is None:
152
+ mask = torch.ones_like(
153
+ vae_latent, dtype=self.vae_encoder.dtype, device=self.vae_encoder.device
154
+ )
155
+
156
+ else:
157
+ mask_path = self.mask_path[idx]
158
+ mask_path = os.path.join(os.path.dirname(self.csv_path), mask_path)
159
+
160
+ mask = PIL.Image.open(mask_path)
161
+ mask = prepare_mask(mask, self.size, self.size).to(
162
+ dtype=self.vae_encoder.dtype, device=self.vae_encoder.device
163
+ )
164
+
165
+ mask = torch.nn.functional.interpolate(
166
+ mask, size=(vae_latent.shape[-2], vae_latent.shape[-1]), mode="nearest"
167
+ )
168
+ mask = mask.repeat(1, vae_latent.shape[1], 1, 1)
169
+
170
+ assert len(mask.shape) == 4 and len(vae_latent.shape) == 4
171
+
172
+ return (ti1.squeeze(), ti2.squeeze()), vae_latent.squeeze(), mask.squeeze()
173
+
174
+ def __len__(self) -> int:
175
+ return len(self.data)
176
+
177
+ def atidx(
178
+ self, idx: int
179
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]:
180
+ if self.do_cache:
181
+ return self.tokens_tuple[idx], self.vae_latents[idx], self.masks[idx]
182
+ else:
183
+ return self._process(idx)
184
+
185
+ def __getitem__(
186
+ self, idx: int
187
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]:
188
+ token, vae_latent, mask = self.atidx(idx)
189
+ return token, vae_latent, mask
190
+
191
+
192
+ def import_model_class_from_model_name_or_path(
193
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
194
+ ):
195
+ text_encoder_config = PretrainedConfig.from_pretrained(
196
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
197
+ )
198
+ model_class = text_encoder_config.architectures[0]
199
+
200
+ if model_class == "CLIPTextModel":
201
+ from transformers import CLIPTextModel
202
+
203
+ return CLIPTextModel
204
+ elif model_class == "CLIPTextModelWithProjection":
205
+ from transformers import CLIPTextModelWithProjection
206
+
207
+ return CLIPTextModelWithProjection
208
+ else:
209
+ raise ValueError(f"{model_class} is not supported.")
210
+
211
+
212
+ def load_models(pretrained_model_name_or_path, revision, device, weight_dtype):
213
+ tokenizer_one = AutoTokenizer.from_pretrained(
214
+ pretrained_model_name_or_path,
215
+ subfolder="tokenizer",
216
+ revision=revision,
217
+ use_fast=False,
218
+ )
219
+ tokenizer_two = AutoTokenizer.from_pretrained(
220
+ pretrained_model_name_or_path,
221
+ subfolder="tokenizer_2",
222
+ revision=revision,
223
+ use_fast=False,
224
+ )
225
+
226
+ # Load scheduler and models
227
+ noise_scheduler = DDPMScheduler.from_pretrained(
228
+ pretrained_model_name_or_path, subfolder="scheduler"
229
+ )
230
+ # import correct text encoder classes
231
+ text_encoder_cls_one = import_model_class_from_model_name_or_path(
232
+ pretrained_model_name_or_path, revision
233
+ )
234
+ text_encoder_cls_two = import_model_class_from_model_name_or_path(
235
+ pretrained_model_name_or_path, revision, subfolder="text_encoder_2"
236
+ )
237
+ text_encoder_one = text_encoder_cls_one.from_pretrained(
238
+ pretrained_model_name_or_path, subfolder="text_encoder", revision=revision
239
+ )
240
+ text_encoder_two = text_encoder_cls_two.from_pretrained(
241
+ pretrained_model_name_or_path, subfolder="text_encoder_2", revision=revision
242
+ )
243
+
244
+ vae = AutoencoderKL.from_pretrained(
245
+ pretrained_model_name_or_path, subfolder="vae", revision=revision
246
+ )
247
+ unet = UNet2DConditionModel.from_pretrained(
248
+ pretrained_model_name_or_path, subfolder="unet", revision=revision
249
+ )
250
+
251
+ vae.requires_grad_(False)
252
+ text_encoder_one.requires_grad_(False)
253
+ text_encoder_two.requires_grad_(False)
254
+
255
+ unet.to(device, dtype=weight_dtype)
256
+ vae.to(device, dtype=torch.float32)
257
+ text_encoder_one.to(device, dtype=weight_dtype)
258
+ text_encoder_two.to(device, dtype=weight_dtype)
259
+
260
+ return (
261
+ tokenizer_one,
262
+ tokenizer_two,
263
+ noise_scheduler,
264
+ text_encoder_one,
265
+ text_encoder_two,
266
+ vae,
267
+ unet,
268
+ )
269
+
270
+
271
+ def unet_attn_processors_state_dict(unet) -> Dict[str, torch.tensor]:
272
+ """
273
+ Returns:
274
+ a state dict containing just the attention processor parameters.
275
+ """
276
+ attn_processors = unet.attn_processors
277
+
278
+ attn_processors_state_dict = {}
279
+
280
+ for attn_processor_key, attn_processor in attn_processors.items():
281
+ for parameter_key, parameter in attn_processor.state_dict().items():
282
+ attn_processors_state_dict[
283
+ f"{attn_processor_key}.{parameter_key}"
284
+ ] = parameter
285
+
286
+ return attn_processors_state_dict
287
+
288
+
289
+ class TokenEmbeddingsHandler:
290
+ def __init__(self, text_encoders, tokenizers):
291
+ self.text_encoders = text_encoders
292
+ self.tokenizers = tokenizers
293
+
294
+ self.train_ids: Optional[torch.Tensor] = None
295
+ self.inserting_toks: Optional[List[str]] = None
296
+ self.embeddings_settings = {}
297
+
298
+ def initialize_new_tokens(self, inserting_toks: List[str]):
299
+ idx = 0
300
+ for tokenizer, text_encoder in zip(self.tokenizers, self.text_encoders):
301
+ assert isinstance(
302
+ inserting_toks, list
303
+ ), "inserting_toks should be a list of strings."
304
+ assert all(
305
+ isinstance(tok, str) for tok in inserting_toks
306
+ ), "All elements in inserting_toks should be strings."
307
+
308
+ self.inserting_toks = inserting_toks
309
+ special_tokens_dict = {"additional_special_tokens": self.inserting_toks}
310
+ tokenizer.add_special_tokens(special_tokens_dict)
311
+ text_encoder.resize_token_embeddings(len(tokenizer))
312
+
313
+ self.train_ids = tokenizer.convert_tokens_to_ids(self.inserting_toks)
314
+
315
+ # random initialization of new tokens
316
+
317
+ std_token_embedding = (
318
+ text_encoder.text_model.embeddings.token_embedding.weight.data.std()
319
+ )
320
+
321
+ print(f"{idx} text encodedr's std_token_embedding: {std_token_embedding}")
322
+
323
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
324
+ self.train_ids
325
+ ] = (
326
+ torch.randn(
327
+ len(self.train_ids), text_encoder.text_model.config.hidden_size
328
+ )
329
+ .to(device=self.device)
330
+ .to(dtype=self.dtype)
331
+ * std_token_embedding
332
+ )
333
+ self.embeddings_settings[
334
+ f"original_embeddings_{idx}"
335
+ ] = text_encoder.text_model.embeddings.token_embedding.weight.data.clone()
336
+ self.embeddings_settings[f"std_token_embedding_{idx}"] = std_token_embedding
337
+
338
+ inu = torch.ones((len(tokenizer),), dtype=torch.bool)
339
+ inu[self.train_ids] = False
340
+
341
+ self.embeddings_settings[f"index_no_updates_{idx}"] = inu
342
+
343
+ print(self.embeddings_settings[f"index_no_updates_{idx}"].shape)
344
+
345
+ idx += 1
346
+
347
+ def save_embeddings(self, file_path: str):
348
+ assert (
349
+ self.train_ids is not None
350
+ ), "Initialize new tokens before saving embeddings."
351
+ tensors = {}
352
+ for idx, text_encoder in enumerate(self.text_encoders):
353
+ assert text_encoder.text_model.embeddings.token_embedding.weight.data.shape[
354
+ 0
355
+ ] == len(self.tokenizers[0]), "Tokenizers should be the same."
356
+ new_token_embeddings = (
357
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
358
+ self.train_ids
359
+ ]
360
+ )
361
+ tensors[f"text_encoders_{idx}"] = new_token_embeddings
362
+
363
+ save_file(tensors, file_path)
364
+
365
+ @property
366
+ def dtype(self):
367
+ return self.text_encoders[0].dtype
368
+
369
+ @property
370
+ def device(self):
371
+ return self.text_encoders[0].device
372
+
373
+ def _load_embeddings(self, loaded_embeddings, tokenizer, text_encoder):
374
+ # Assuming new tokens are of the format <s_i>
375
+ self.inserting_toks = [f"<s{i}>" for i in range(loaded_embeddings.shape[0])]
376
+ special_tokens_dict = {"additional_special_tokens": self.inserting_toks}
377
+ tokenizer.add_special_tokens(special_tokens_dict)
378
+ text_encoder.resize_token_embeddings(len(tokenizer))
379
+
380
+ self.train_ids = tokenizer.convert_tokens_to_ids(self.inserting_toks)
381
+ assert self.train_ids is not None, "New tokens could not be converted to IDs."
382
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
383
+ self.train_ids
384
+ ] = loaded_embeddings.to(device=self.device).to(dtype=self.dtype)
385
+
386
+ @torch.no_grad()
387
+ def retract_embeddings(self):
388
+ for idx, text_encoder in enumerate(self.text_encoders):
389
+ index_no_updates = self.embeddings_settings[f"index_no_updates_{idx}"]
390
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
391
+ index_no_updates
392
+ ] = (
393
+ self.embeddings_settings[f"original_embeddings_{idx}"][index_no_updates]
394
+ .to(device=text_encoder.device)
395
+ .to(dtype=text_encoder.dtype)
396
+ )
397
+
398
+ # for the parts that were updated, we need to normalize them
399
+ # to have the same std as before
400
+ std_token_embedding = self.embeddings_settings[f"std_token_embedding_{idx}"]
401
+
402
+ index_updates = ~index_no_updates
403
+ new_embeddings = (
404
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
405
+ index_updates
406
+ ]
407
+ )
408
+ off_ratio = std_token_embedding / new_embeddings.std()
409
+
410
+ new_embeddings = new_embeddings * (off_ratio**0.1)
411
+ text_encoder.text_model.embeddings.token_embedding.weight.data[
412
+ index_updates
413
+ ] = new_embeddings
414
+
415
+ def load_embeddings(self, file_path: str):
416
+ with safe_open(file_path, framework="pt", device=self.device.type) as f:
417
+ for idx in range(len(self.text_encoders)):
418
+ text_encoder = self.text_encoders[idx]
419
+ tokenizer = self.tokenizers[idx]
420
+
421
+ loaded_embeddings = f.get_tensor(f"text_encoders_{idx}")
422
+ self._load_embeddings(loaded_embeddings, tokenizer, text_encoder)
images/3d_style_4.jpeg ADDED
images/LineAni.Redmond.png ADDED
images/LogoRedmond-LogoLoraForSDXL.jpeg ADDED
images/ToyRedmond-ToyLoraForSDXL10.png ADDED
images/corgi_brick.jpeg ADDED
images/crayon.png ADDED
images/dog.png ADDED
images/embroid.png ADDED
images/jojoso1.jpg ADDED
images/josef_koudelka.webp ADDED
images/lego-minifig-xl.jpeg ADDED
images/papercut_SDXL.jpeg ADDED
images/pikachu.webp ADDED
images/pixel-art-xl.jpeg ADDED
images/riding-min.jpg ADDED
images/the_fish.jpg ADDED
images/uglysonic.webp ADDED
images/voxel-xl-lora.png ADDED
images/watercolor.png ADDED
images/william_eggleston.webp ADDED
pipeline_semantic_stable_diffusion_xl_img2img_ddpm.py ADDED
@@ -0,0 +1,1758 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import os
17
+ #from itertools import repeat
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
19
+ import numpy as np
20
+ from PIL import Image
21
+ from tqdm import tqdm
22
+ import torch.nn.functional as F
23
+ import math
24
+
25
+ import torch
26
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
27
+
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
30
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
31
+ from diffusers.models.attention_processor import (
32
+ AttnProcessor2_0,
33
+ LoRAAttnProcessor2_0,
34
+ LoRAXFormersAttnProcessor,
35
+ XFormersAttnProcessor,
36
+ AttnProcessor,
37
+ Attention
38
+ )
39
+ from diffusers.schedulers import DDIMScheduler
40
+ from diffusers.utils import (
41
+ is_accelerate_available,
42
+ is_accelerate_version,
43
+ is_invisible_watermark_available,
44
+ logging,
45
+ # randn_tensor,
46
+ replace_example_docstring,
47
+ )
48
+
49
+ from diffusers.utils.torch_utils import randn_tensor
50
+ from diffusers.pipeline_utils import DiffusionPipeline
51
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
52
+
53
+
54
+ if is_invisible_watermark_available():
55
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
56
+
57
+
58
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
59
+
60
+ EXAMPLE_DOC_STRING = """
61
+ Examples:
62
+ ```py
63
+ >>> import torch
64
+ >>> from diffusers import StableDiffusionXLPipeline
65
+
66
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
67
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
68
+ ... )
69
+ >>> pipe = pipe.to("cuda")
70
+
71
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
72
+ >>> image = pipe(prompt).images[0]
73
+ ```
74
+ """
75
+
76
+
77
+ class AttentionStore():
78
+ @staticmethod
79
+ def get_empty_store():
80
+ return {"down_cross": [], "mid_cross": [], "up_cross": [],
81
+ "down_self": [], "mid_self": [], "up_self": []}
82
+
83
+ def __call__(self, attn, is_cross: bool, place_in_unet: str, editing_prompts):
84
+ # attn.shape = batch_size * head_size, seq_len query, seq_len_key
85
+ bs = 2 + editing_prompts
86
+ source_batch_size = int(attn.shape[0] // bs)
87
+ skip = 1 # skip unconditional
88
+ self.forward(
89
+ attn[skip*source_batch_size:],
90
+ is_cross,
91
+ place_in_unet)
92
+
93
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
94
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
95
+ #print(f"{key} : {attn.shape[1]}")
96
+ self.step_store[key].append(attn)
97
+
98
+ def between_steps(self, store_step=True):
99
+ if store_step:
100
+ if self.average:
101
+ if len(self.attention_store) == 0:
102
+ self.attention_store = self.step_store
103
+ else:
104
+ for key in self.attention_store:
105
+ for i in range(len(self.attention_store[key])):
106
+ self.attention_store[key][i] += self.step_store[key][i]
107
+ else:
108
+ if len(self.attention_store) == 0:
109
+ self.attention_store = [self.step_store]
110
+ else:
111
+ self.attention_store.append(self.step_store)
112
+
113
+ self.cur_step += 1
114
+ self.step_store = self.get_empty_store()
115
+
116
+ def get_attention(self, step: int):
117
+ if self.average:
118
+ attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store}
119
+ else:
120
+ assert(step is not None)
121
+ attention = self.attention_store[step]
122
+ return attention
123
+
124
+ def aggregate_attention(self, attention_maps, prompts, res: int,
125
+ from_where: List[str], is_cross: bool, select: int
126
+ ):
127
+ out = []
128
+ num_pixels = res ** 2
129
+ for location in from_where:
130
+ for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
131
+ if item.shape[1] == num_pixels:
132
+ cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
133
+ out.append(cross_maps)
134
+ out = torch.cat(out, dim=0)
135
+ # average over heads
136
+ out = out.sum(0) / out.shape[0]
137
+ return out
138
+
139
+ def __init__(self, average: bool):
140
+ self.step_store = self.get_empty_store()
141
+ self.attention_store = []
142
+ self.cur_step = 0
143
+ self.average = average
144
+
145
+ class CrossAttnProcessor:
146
+
147
+ def __init__(self, attention_store, place_in_unet, editing_prompts):
148
+ self.attnstore = attention_store
149
+ self.place_in_unet = place_in_unet
150
+ self.editing_prompts = editing_prompts
151
+
152
+ def __call__(
153
+ self,
154
+ attn: Attention,
155
+ hidden_states,
156
+ encoder_hidden_states=None,
157
+ attention_mask=None,
158
+ temb=None,
159
+ ):
160
+ assert(not attn.residual_connection)
161
+ assert(attn.spatial_norm is None)
162
+ assert(attn.group_norm is None)
163
+ assert(hidden_states.ndim != 4)
164
+ assert(encoder_hidden_states is not None) # is cross
165
+
166
+ batch_size, sequence_length, _ = (
167
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
168
+ )
169
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
170
+
171
+ query = attn.to_q(hidden_states)
172
+
173
+ if encoder_hidden_states is None:
174
+ encoder_hidden_states = hidden_states
175
+ elif attn.norm_cross:
176
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
177
+
178
+ key = attn.to_k(encoder_hidden_states)
179
+ value = attn.to_v(encoder_hidden_states)
180
+
181
+ query = attn.head_to_batch_dim(query)
182
+ key = attn.head_to_batch_dim(key)
183
+ value = attn.head_to_batch_dim(value)
184
+
185
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
186
+ self.attnstore(attention_probs,
187
+ is_cross=True,
188
+ place_in_unet=self.place_in_unet,
189
+ editing_prompts=self.editing_prompts)
190
+
191
+ hidden_states = torch.bmm(attention_probs, value)
192
+ hidden_states = attn.batch_to_head_dim(hidden_states)
193
+
194
+ # linear proj
195
+ hidden_states = attn.to_out[0](hidden_states)
196
+ # dropout
197
+ hidden_states = attn.to_out[1](hidden_states)
198
+
199
+ hidden_states = hidden_states / attn.rescale_output_factor
200
+ return hidden_states
201
+
202
+
203
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
204
+ class GaussianSmoothing():
205
+
206
+ def __init__(self, device):
207
+ kernel_size = [3, 3]
208
+ sigma = [0.5, 0.5]
209
+
210
+ # The gaussian kernel is the product of the gaussian function of each dimension.
211
+ kernel = 1
212
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
213
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
214
+ mean = (size - 1) / 2
215
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
216
+
217
+ # Make sure sum of values in gaussian kernel equals 1.
218
+ kernel = kernel / torch.sum(kernel)
219
+
220
+ # Reshape to depthwise convolutional weight
221
+ kernel = kernel.view(1, 1, *kernel.size())
222
+ kernel = kernel.repeat(1, *[1] * (kernel.dim() - 1))
223
+
224
+ self.weight = kernel.to(device)
225
+
226
+ def __call__(self, input):
227
+ """
228
+ Arguments:
229
+ Apply gaussian filter to input.
230
+ input (torch.Tensor): Input to apply gaussian filter on.
231
+ Returns:
232
+ filtered (torch.Tensor): Filtered output.
233
+ """
234
+ return F.conv2d(input, weight=self.weight.to(input.dtype))
235
+
236
+
237
+ def load_image(image_path, size=1024, left=0, right=0, top=0, bottom=0, device=None, dtype=None):
238
+ print(f"load image of size {size}x{size}")
239
+ if type(image_path) is str:
240
+ image = np.array(Image.open(image_path).convert('RGB'))[:, :, :3]
241
+ else:
242
+ image = image_path
243
+ h, w, c = image.shape
244
+ left = min(left, w-1)
245
+ right = min(right, w - left - 1)
246
+ top = min(top, h - left - 1)
247
+ bottom = min(bottom, h - top - 1)
248
+ image = image[top:h-bottom, left:w-right]
249
+ h, w, c = image.shape
250
+ if h < w:
251
+ offset = (w - h) // 2
252
+ image = image[:, offset:offset + h]
253
+ elif w < h:
254
+ offset = (h - w) // 2
255
+ image = image[offset:offset + w]
256
+ image = np.array(Image.fromarray(image).resize((size, size)))
257
+ image = torch.from_numpy(image).float() / 127.5 - 1
258
+ image = image.permute(2, 0, 1).unsqueeze(0)
259
+
260
+ image = image.to(device=device, dtype=dtype)
261
+ return image
262
+
263
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
264
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
265
+ """
266
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
267
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
268
+ """
269
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
270
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
271
+ # rescale the results from guidance (fixes overexposure)
272
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
273
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
274
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
275
+ return noise_cfg
276
+
277
+
278
+ class SemanticStableDiffusionXLImg2ImgPipeline_DDPMInversion(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin):
279
+ r"""
280
+ Pipeline for text-to-image generation using Stable Diffusion XL.
281
+
282
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
283
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
284
+
285
+ In addition the pipeline inherits the following loading methods:
286
+ - *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
287
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
288
+
289
+ as well as the following saving methods:
290
+ - *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
291
+
292
+ Args:
293
+ vae ([`AutoencoderKL`]):
294
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
295
+ text_encoder ([`CLIPTextModel`]):
296
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
297
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
298
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
299
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
300
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
301
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
302
+ specifically the
303
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
304
+ variant.
305
+ tokenizer (`CLIPTokenizer`):
306
+ Tokenizer of class
307
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
308
+ tokenizer_2 (`CLIPTokenizer`):
309
+ Second Tokenizer of class
310
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
311
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
312
+ scheduler ([`SchedulerMixin`]):
313
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
314
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
315
+ """
316
+
317
+ def __init__(
318
+ self,
319
+ vae: AutoencoderKL,
320
+ text_encoder: CLIPTextModel,
321
+ text_encoder_2: CLIPTextModelWithProjection,
322
+ tokenizer: CLIPTokenizer,
323
+ tokenizer_2: CLIPTokenizer,
324
+ unet: UNet2DConditionModel,
325
+ scheduler: DDIMScheduler,
326
+ force_zeros_for_empty_prompt: bool = True,
327
+ add_watermarker: Optional[bool] = None,
328
+ ):
329
+ super().__init__()
330
+
331
+ if not isinstance(scheduler, DDIMScheduler):
332
+ scheduler = DDIMScheduler.from_config(scheduler.config)
333
+ logger.warning("This pipeline only supports DDIMScheduler. "
334
+ "The scheduler has been changed to DDIMScheduler.")
335
+
336
+ self.register_modules(
337
+ vae=vae,
338
+ text_encoder=text_encoder,
339
+ text_encoder_2=text_encoder_2,
340
+ tokenizer=tokenizer,
341
+ tokenizer_2=tokenizer_2,
342
+ unet=unet,
343
+ scheduler=scheduler,
344
+ )
345
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
346
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
347
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
348
+ self.default_sample_size = self.unet.config.sample_size
349
+
350
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
351
+
352
+ if add_watermarker:
353
+ self.watermark = StableDiffusionXLWatermarker()
354
+ else:
355
+ self.watermark = None
356
+
357
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
358
+ def enable_vae_slicing(self):
359
+ r"""
360
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
361
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
362
+ """
363
+ self.vae.enable_slicing()
364
+
365
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
366
+ def disable_vae_slicing(self):
367
+ r"""
368
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
369
+ computing decoding in one step.
370
+ """
371
+ self.vae.disable_slicing()
372
+
373
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
374
+ def enable_vae_tiling(self):
375
+ r"""
376
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
377
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
378
+ processing larger images.
379
+ """
380
+ self.vae.enable_tiling()
381
+
382
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
383
+ def disable_vae_tiling(self):
384
+ r"""
385
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
386
+ computing decoding in one step.
387
+ """
388
+ self.vae.disable_tiling()
389
+
390
+ def enable_model_cpu_offload(self, gpu_id=0):
391
+ r"""
392
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
393
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
394
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
395
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
396
+ """
397
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
398
+ from accelerate import cpu_offload_with_hook
399
+ else:
400
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
401
+
402
+ device = torch.device(f"cuda:{gpu_id}")
403
+
404
+ if self.device.type != "cpu":
405
+ self.to("cpu", silence_dtype_warnings=True)
406
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
407
+
408
+ model_sequence = (
409
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
410
+ )
411
+ model_sequence.extend([self.unet, self.vae])
412
+
413
+ hook = None
414
+ for cpu_offloaded_model in model_sequence:
415
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
416
+
417
+ # We'll offload the last model manually.
418
+ self.final_offload_hook = hook
419
+
420
+ def encode_prompt(
421
+ self,
422
+ prompt: str,
423
+ prompt_2: Optional[str] = None,
424
+ device: Optional[torch.device] = None,
425
+ num_images_per_prompt: int = 1,
426
+ do_classifier_free_guidance: bool = True,
427
+ negative_prompt: Optional[str] = None,
428
+ negative_prompt_2: Optional[str] = None,
429
+ prompt_embeds: Optional[torch.FloatTensor] = None,
430
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
431
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
432
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
433
+ lora_scale: Optional[float] = None,
434
+ enable_edit_guidance: bool = True,
435
+ editing_prompt: Optional[str] = None,
436
+ ):
437
+ r"""
438
+ Encodes the prompt into text encoder hidden states.
439
+
440
+ Args:
441
+ prompt (`str` or `List[str]`, *optional*):
442
+ prompt to be encoded
443
+ prompt_2 (`str` or `List[str]`, *optional*):
444
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
445
+ used in both text-encoders
446
+ device: (`torch.device`):
447
+ torch device
448
+ num_images_per_prompt (`int`):
449
+ number of images that should be generated per prompt
450
+ do_classifier_free_guidance (`bool`):
451
+ whether to use classifier free guidance or not
452
+ negative_prompt (`str` or `List[str]`, *optional*):
453
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
454
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
455
+ less than `1`).
456
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
457
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
458
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
459
+ prompt_embeds (`torch.FloatTensor`, *optional*):
460
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
461
+ provided, text embeddings will be generated from `prompt` input argument.
462
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
463
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
464
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
465
+ argument.
466
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
467
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
468
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
469
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
470
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
471
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
472
+ input argument.
473
+ lora_scale (`float`, *optional*):
474
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
475
+ """
476
+ device = device or self._execution_device
477
+
478
+ # set lora scale so that monkey patched LoRA
479
+ # function of text encoder can correctly access it
480
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
481
+ self._lora_scale = lora_scale
482
+
483
+ if prompt is not None and isinstance(prompt, str):
484
+ batch_size = 1
485
+ elif prompt is not None and isinstance(prompt, list):
486
+ batch_size = len(prompt)
487
+ else:
488
+ batch_size = prompt_embeds.shape[0]
489
+
490
+ # Define tokenizers and text encoders
491
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
492
+ text_encoders = (
493
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
494
+ )
495
+
496
+ if prompt_embeds is None:
497
+ prompt_2 = prompt_2 or prompt
498
+ # textual inversion: procecss multi-vector tokens if necessary
499
+ prompt_embeds_list = []
500
+ prompts = [prompt, prompt_2]
501
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
502
+ if isinstance(self, TextualInversionLoaderMixin):
503
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
504
+
505
+ text_inputs = tokenizer(
506
+ prompt,
507
+ padding="max_length",
508
+ max_length=tokenizer.model_max_length,
509
+ truncation=True,
510
+ return_tensors="pt",
511
+ )
512
+
513
+ text_input_ids = text_inputs.input_ids
514
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
515
+
516
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
517
+ text_input_ids, untruncated_ids
518
+ ):
519
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
520
+ logger.warning(
521
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
522
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
523
+ )
524
+
525
+ prompt_embeds = text_encoder(
526
+ text_input_ids.to(device),
527
+ output_hidden_states=True,
528
+ )
529
+
530
+ # We are only ALWAYS interested in the pooled output of the final text encoder
531
+ pooled_prompt_embeds = prompt_embeds[0]
532
+ prompt_embeds = prompt_embeds.hidden_states[-2]
533
+
534
+ prompt_embeds_list.append(prompt_embeds)
535
+
536
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
537
+
538
+ # get unconditional embeddings for classifier free guidance
539
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
540
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
541
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
542
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
543
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
544
+ negative_prompt = negative_prompt or ""
545
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
546
+
547
+ uncond_tokens: List[str]
548
+ if prompt is not None and type(prompt) is not type(negative_prompt):
549
+ raise TypeError(
550
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
551
+ f" {type(prompt)}."
552
+ )
553
+ elif isinstance(negative_prompt, str):
554
+ uncond_tokens = [negative_prompt, negative_prompt_2]
555
+ elif batch_size != len(negative_prompt):
556
+ raise ValueError(
557
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
558
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
559
+ " the batch size of `prompt`."
560
+ )
561
+ else:
562
+ uncond_tokens = [negative_prompt, negative_prompt_2]
563
+
564
+ negative_prompt_embeds_list = []
565
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
566
+ if isinstance(self, TextualInversionLoaderMixin):
567
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
568
+
569
+ max_length = prompt_embeds.shape[1]
570
+ uncond_input = tokenizer(
571
+ negative_prompt,
572
+ padding="max_length",
573
+ max_length=max_length,
574
+ truncation=True,
575
+ return_tensors="pt",
576
+ )
577
+
578
+ negative_prompt_embeds = text_encoder(
579
+ uncond_input.input_ids.to(device),
580
+ output_hidden_states=True,
581
+ )
582
+ # We are only ALWAYS interested in the pooled output of the final text encoder
583
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
584
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
585
+
586
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
587
+
588
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
589
+
590
+ num_edit_tokens = None
591
+ if enable_edit_guidance:
592
+ editing_prompt_2 = editing_prompt
593
+
594
+ editing_prompts = [editing_prompt, editing_prompt_2]
595
+ edit_prompt_embeds_list = []
596
+
597
+ for editing_prompt, tokenizer, text_encoder in zip(editing_prompts, tokenizers, text_encoders):
598
+ if isinstance(self, TextualInversionLoaderMixin):
599
+ editing_prompt = self.maybe_convert_prompt(editing_prompt, tokenizer)
600
+
601
+ max_length = prompt_embeds.shape[1]
602
+ edit_concepts_input = tokenizer(
603
+ #[x for item in editing_prompt for x in repeat(item, batch_size)],
604
+ editing_prompt,
605
+ padding="max_length",
606
+ max_length=max_length,
607
+ truncation=True,
608
+ return_tensors="pt",
609
+ return_length=True
610
+ )
611
+
612
+ num_edit_tokens = edit_concepts_input.length -2 # not counting startoftext and endoftext
613
+ edit_concepts_input_ids = edit_concepts_input.input_ids
614
+ edit_concepts_embeds = text_encoder(
615
+ edit_concepts_input.input_ids.to(device),
616
+ output_hidden_states=True,
617
+ )
618
+ # We are only ALWAYS interested in the pooled output of the final text encoder
619
+ edit_pooled_prompt_embeds = edit_concepts_embeds[0]
620
+ edit_concepts_embeds = edit_concepts_embeds.hidden_states[-2]
621
+
622
+ edit_prompt_embeds_list.append(edit_concepts_embeds)
623
+
624
+ edit_concepts_embeds = torch.concat(edit_prompt_embeds_list, dim=-1)
625
+ else:
626
+ edit_concepts_embeds = None
627
+ edit_pooled_prompt_embeds = None
628
+
629
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
630
+ bs_embed, seq_len, _ = prompt_embeds.shape
631
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
632
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
633
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
634
+
635
+ if do_classifier_free_guidance:
636
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
637
+ seq_len = negative_prompt_embeds.shape[1]
638
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
639
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
640
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
641
+
642
+ if enable_edit_guidance:
643
+ bs_embed_edit, seq_len, _ = edit_concepts_embeds.shape
644
+ edit_concepts_embeds = edit_concepts_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
645
+ edit_concepts_embeds = edit_concepts_embeds.repeat(1, num_images_per_prompt, 1)
646
+ edit_concepts_embeds = edit_concepts_embeds.view(bs_embed_edit * num_images_per_prompt, seq_len, -1)
647
+
648
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
649
+ bs_embed * num_images_per_prompt, -1
650
+ )
651
+ if do_classifier_free_guidance:
652
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
653
+ bs_embed * num_images_per_prompt, -1
654
+ )
655
+
656
+ if enable_edit_guidance:
657
+ edit_pooled_prompt_embeds = edit_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
658
+ bs_embed_edit * num_images_per_prompt, -1
659
+ )
660
+
661
+ return (prompt_embeds, negative_prompt_embeds, edit_concepts_embeds,
662
+ pooled_prompt_embeds, negative_pooled_prompt_embeds, edit_pooled_prompt_embeds,
663
+ num_edit_tokens)
664
+
665
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
666
+ def prepare_extra_step_kwargs(self, eta):
667
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
668
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
669
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
670
+ # and should be between [0, 1]
671
+
672
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
673
+ extra_step_kwargs = {}
674
+ if accepts_eta:
675
+ extra_step_kwargs["eta"] = eta
676
+
677
+ return extra_step_kwargs
678
+
679
+ def check_inputs(
680
+ self,
681
+ prompt,
682
+ prompt_2,
683
+ height,
684
+ width,
685
+ callback_steps,
686
+ negative_prompt=None,
687
+ negative_prompt_2=None,
688
+ prompt_embeds=None,
689
+ negative_prompt_embeds=None,
690
+ pooled_prompt_embeds=None,
691
+ negative_pooled_prompt_embeds=None,
692
+ ):
693
+ if height % 8 != 0 or width % 8 != 0:
694
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
695
+
696
+ if (callback_steps is None) or (
697
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
698
+ ):
699
+ raise ValueError(
700
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
701
+ f" {type(callback_steps)}."
702
+ )
703
+
704
+ if prompt is not None and prompt_embeds is not None:
705
+ raise ValueError(
706
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
707
+ " only forward one of the two."
708
+ )
709
+ elif prompt_2 is not None and prompt_embeds is not None:
710
+ raise ValueError(
711
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
712
+ " only forward one of the two."
713
+ )
714
+ elif prompt is None and prompt_embeds is None:
715
+ raise ValueError(
716
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
717
+ )
718
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
719
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
720
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
721
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
722
+
723
+ if negative_prompt is not None and negative_prompt_embeds is not None:
724
+ raise ValueError(
725
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
726
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
727
+ )
728
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
729
+ raise ValueError(
730
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
731
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
732
+ )
733
+
734
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
735
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
736
+ raise ValueError(
737
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
738
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
739
+ f" {negative_prompt_embeds.shape}."
740
+ )
741
+
742
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
743
+ raise ValueError(
744
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
745
+ )
746
+
747
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
748
+ raise ValueError(
749
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
750
+ )
751
+
752
+ # Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
753
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, latents):
754
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
755
+
756
+ if latents.shape != shape:
757
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
758
+
759
+ latents = latents.to(device)
760
+
761
+ # scale the initial noise by the standard deviation required by the scheduler
762
+ latents = latents * self.scheduler.init_noise_sigma
763
+ return latents
764
+
765
+ def prepare_unet(self, attention_store, enabled_editing_prompts):
766
+ attn_procs = {}
767
+ for name in self.unet.attn_processors.keys():
768
+ if name.startswith("mid_block"):
769
+ place_in_unet = "mid"
770
+ elif name.startswith("up_blocks"):
771
+ place_in_unet = "up"
772
+ elif name.startswith("down_blocks"):
773
+ place_in_unet = "down"
774
+ else:
775
+ continue
776
+
777
+ if "attn2" in name:
778
+ attn_procs[name] = CrossAttnProcessor(
779
+ attention_store=attention_store,
780
+ place_in_unet=place_in_unet,
781
+ editing_prompts=enabled_editing_prompts)
782
+ else:
783
+ attn_procs[name] = AttnProcessor()
784
+
785
+ self.unet.set_attn_processor(attn_procs)
786
+
787
+
788
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
789
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
790
+
791
+ passed_add_embed_dim = (
792
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
793
+ )
794
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
795
+
796
+ if expected_add_embed_dim != passed_add_embed_dim:
797
+ raise ValueError(
798
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
799
+ )
800
+
801
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
802
+ return add_time_ids
803
+
804
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
805
+ def upcast_vae(self):
806
+ dtype = self.vae.dtype
807
+ self.vae.to(dtype=torch.float32)
808
+ use_torch_2_0_or_xformers = isinstance(
809
+ self.vae.decoder.mid_block.attentions[0].processor,
810
+ (
811
+ AttnProcessor2_0,
812
+ XFormersAttnProcessor,
813
+ LoRAXFormersAttnProcessor,
814
+ LoRAAttnProcessor2_0,
815
+ ),
816
+ )
817
+ # if xformers or torch_2_0 is used attention block does not need
818
+ # to be in float32 which can save lots of memory
819
+ if use_torch_2_0_or_xformers:
820
+ self.vae.post_quant_conv.to(dtype)
821
+ self.vae.decoder.conv_in.to(dtype)
822
+ self.vae.decoder.mid_block.to(dtype)
823
+
824
+ @torch.no_grad()
825
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
826
+ def __call__(
827
+ self,
828
+ prompt: Union[str, List[str]] = None,
829
+ prompt_2: Optional[Union[str, List[str]]] = None,
830
+ height: Optional[int] = None,
831
+ width: Optional[int] = None,
832
+ #num_inference_steps: int = 50,
833
+ #denoising_end: Optional[float] = None,
834
+ guidance_scale: float = 5.0,
835
+ negative_prompt: Optional[Union[str, List[str]]] = None,
836
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
837
+ #num_images_per_prompt: Optional[int] = 1,
838
+ eta: float = 1.0,
839
+ #generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
840
+ latents: Optional[torch.FloatTensor] = None,
841
+ prompt_embeds: Optional[torch.FloatTensor] = None,
842
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
843
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
844
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
845
+ output_type: Optional[str] = "pil",
846
+ return_dict: bool = True,
847
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
848
+ callback_steps: int = 1,
849
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
850
+ guidance_rescale: float = 0.0,
851
+ original_size: Optional[Tuple[int, int]] = None,
852
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
853
+ target_size: Optional[Tuple[int, int]] = None,
854
+ editing_prompt: Optional[Union[str, List[str]]] = None,
855
+ editing_prompt_embeddings: Optional[torch.Tensor] = None,
856
+ reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
857
+ edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
858
+ edit_warmup_steps: Optional[Union[int, List[int]]] = 10,
859
+ edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
860
+ edit_threshold: Optional[Union[float, List[float]]] = 0.9,
861
+ edit_momentum_scale: Optional[float] = 0.1,
862
+ edit_mom_beta: Optional[float] = 0.4,
863
+ edit_weights: Optional[List[float]] = None,
864
+ sem_guidance: Optional[List[torch.Tensor]] = None,
865
+ user_mask: Optional[torch.FloatTensor] = None,
866
+ use_cross_attn_mask: bool = False,
867
+ # Attention store (just for visualization purposes)
868
+ attn_store_steps: Optional[List[int]] = [],
869
+ store_averaged_over_steps: bool = True,
870
+
871
+ zs: Optional[torch.FloatTensor] = None,
872
+ wts: Optional[torch.FloatTensor] = None,
873
+ ):
874
+ r"""
875
+ Function invoked when calling the pipeline for generation.
876
+
877
+ Args:
878
+ prompt (`str` or `List[str]`, *optional*):
879
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
880
+ instead.
881
+ prompt_2 (`str` or `List[str]`, *optional*):
882
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
883
+ used in both text-encoders
884
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
885
+ The height in pixels of the generated image.
886
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
887
+ The width in pixels of the generated image.
888
+ num_inference_steps (`int`, *optional*, defaults to 50):
889
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
890
+ expense of slower inference.
891
+ denoising_end (`float`, *optional*):
892
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
893
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
894
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
895
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
896
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
897
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
898
+ guidance_scale (`float`, *optional*, defaults to 5.0):
899
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
900
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
901
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
902
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
903
+ usually at the expense of lower image quality.
904
+ negative_prompt (`str` or `List[str]`, *optional*):
905
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
906
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
907
+ less than `1`).
908
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
909
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
910
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
911
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
912
+ The number of images to generate per prompt.
913
+ eta (`float`, *optional*, defaults to 0.0):
914
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
915
+ [`schedulers.DDIMScheduler`], will be ignored for others.
916
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
917
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
918
+ to make generation deterministic.
919
+ latents (`torch.FloatTensor`, *optional*):
920
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
921
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
922
+ tensor will ge generated by sampling using the supplied random `generator`.
923
+ prompt_embeds (`torch.FloatTensor`, *optional*):
924
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
925
+ provided, text embeddings will be generated from `prompt` input argument.
926
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
927
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
928
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
929
+ argument.
930
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
931
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
932
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
933
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
934
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
935
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
936
+ input argument.
937
+ output_type (`str`, *optional*, defaults to `"pil"`):
938
+ The output format of the generate image. Choose between
939
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
940
+ return_dict (`bool`, *optional*, defaults to `True`):
941
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
942
+ of a plain tuple.
943
+ callback (`Callable`, *optional*):
944
+ A function that will be called every `callback_steps` steps during inference. The function will be
945
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
946
+ callback_steps (`int`, *optional*, defaults to 1):
947
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
948
+ called at every step.
949
+ cross_attention_kwargs (`dict`, *optional*):
950
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
951
+ `self.processor` in
952
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
953
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
954
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
955
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
956
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
957
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
958
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
959
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
960
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
961
+ explained in section 2.2 of
962
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
963
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
964
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
965
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
966
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
967
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
968
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
969
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
970
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
971
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
972
+ editing_prompt (`str` or `List[str]`, *optional*):
973
+ The prompt or prompts to use for semantic guidance. Semantic guidance is disabled by setting
974
+ `editing_prompt = None`. Guidance direction of prompt should be specified via
975
+ `reverse_editing_direction`.
976
+ editing_prompt_embeddings (`torch.Tensor`, *optional*):
977
+ Pre-computed embeddings to use for semantic guidance. Guidance direction of embedding should be
978
+ specified via `reverse_editing_direction`.
979
+ reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
980
+ Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
981
+ edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
982
+ Guidance scale for semantic guidance. If provided as a list, values should correspond to
983
+ `editing_prompt`.
984
+ edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
985
+ Number of diffusion steps (for each prompt) for which semantic guidance is not applied. Momentum is
986
+ calculated for those steps and applied once all warmup periods are over.
987
+ edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
988
+ Number of diffusion steps (for each prompt) after which semantic guidance is longer applied.
989
+ edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
990
+ Threshold of semantic guidance.
991
+ edit_momentum_scale (`float`, *optional*, defaults to 0.1):
992
+ Scale of the momentum to be added to the semantic guidance at each diffusion step. If set to 0.0,
993
+ momentum is disabled. Momentum is already built up during warmup (for diffusion steps smaller than
994
+ `sld_warmup_steps`). Momentum is only added to latent guidance once all warmup periods are finished.
995
+ edit_mom_beta (`float`, *optional*, defaults to 0.4):
996
+ Defines how semantic guidance momentum builds up. `edit_mom_beta` indicates how much of the previous
997
+ momentum is kept. Momentum is already built up during warmup (for diffusion steps smaller than
998
+ `edit_warmup_steps`).
999
+ edit_weights (`List[float]`, *optional*, defaults to `None`):
1000
+ Indicates how much each individual concept should influence the overall guidance. If no weights are
1001
+ provided all concepts are applied equally.
1002
+ sem_guidance (`List[torch.Tensor]`, *optional*):
1003
+ List of pre-generated guidance vectors to be applied at generation. Length of the list has to
1004
+ correspond to `num_inference_steps`.
1005
+
1006
+ Examples:
1007
+
1008
+ Returns:
1009
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1010
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1011
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1012
+ """
1013
+ # eta = self.eta
1014
+ num_inference_steps = self.num_inversion_steps
1015
+ num_images_per_prompt = 1
1016
+ # latents = self.init_latents
1017
+
1018
+ use_ddpm = True
1019
+ # zs = self.zs
1020
+ # wts = self.wts
1021
+
1022
+ if use_cross_attn_mask:
1023
+ self.smoothing = GaussianSmoothing(self.device)
1024
+
1025
+ # 0. Default height and width to unet
1026
+ height = self.height
1027
+ width = self.width
1028
+ original_size = self.original_size
1029
+ target_size = self.target_size
1030
+
1031
+ # 1. Check inputs. Raise error if not correct
1032
+ self.check_inputs(
1033
+ prompt,
1034
+ prompt_2,
1035
+ height,
1036
+ width,
1037
+ callback_steps,
1038
+ negative_prompt,
1039
+ negative_prompt_2,
1040
+ prompt_embeds,
1041
+ negative_prompt_embeds,
1042
+ pooled_prompt_embeds,
1043
+ negative_pooled_prompt_embeds,
1044
+ )
1045
+
1046
+ # 2. Define call parameters
1047
+ if prompt is not None and isinstance(prompt, str):
1048
+ batch_size = 1
1049
+ elif prompt is not None and isinstance(prompt, list):
1050
+ batch_size = len(prompt)
1051
+ else:
1052
+ batch_size = prompt_embeds.shape[0]
1053
+
1054
+ device = self._execution_device
1055
+
1056
+ if editing_prompt:
1057
+ enable_edit_guidance = True
1058
+ if isinstance(editing_prompt, str):
1059
+ editing_prompt = [editing_prompt]
1060
+ enabled_editing_prompts = len(editing_prompt)
1061
+ elif editing_prompt_embeddings is not None:
1062
+ enable_edit_guidance = True
1063
+ enabled_editing_prompts = editing_prompt_embeddings.shape[0]
1064
+ else:
1065
+ enabled_editing_prompts = 0
1066
+ enable_edit_guidance = False
1067
+
1068
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1069
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1070
+ # corresponds to doing no classifier free guidance.
1071
+ do_classifier_free_guidance = guidance_scale > 1.0
1072
+
1073
+ if prompt == "" and (prompt_2 == "" or prompt_2 is None):
1074
+ # only use uncond noise pred
1075
+ guidance_scale = 0.0
1076
+ do_classifier_free_guidance = True
1077
+ else:
1078
+ do_classifier_free_guidance = guidance_scale > 1.0
1079
+
1080
+ # 3. Encode input prompt
1081
+ text_encoder_lora_scale = (
1082
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1083
+ )
1084
+ (
1085
+ prompt_embeds,
1086
+ negative_prompt_embeds,
1087
+ edit_prompt_embeds,
1088
+ pooled_prompt_embeds,
1089
+ negative_pooled_prompt_embeds,
1090
+ pooled_edit_embeds,
1091
+ num_edit_tokens
1092
+ ) = self.encode_prompt(
1093
+ prompt=prompt,
1094
+ prompt_2=prompt_2,
1095
+ device=device,
1096
+ num_images_per_prompt=num_images_per_prompt,
1097
+ do_classifier_free_guidance=do_classifier_free_guidance,
1098
+ negative_prompt=negative_prompt,
1099
+ negative_prompt_2=negative_prompt_2,
1100
+ prompt_embeds=prompt_embeds,
1101
+ negative_prompt_embeds=negative_prompt_embeds,
1102
+ pooled_prompt_embeds=pooled_prompt_embeds,
1103
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1104
+ lora_scale=text_encoder_lora_scale,
1105
+ enable_edit_guidance=enable_edit_guidance,
1106
+ editing_prompt=editing_prompt
1107
+ )
1108
+
1109
+ # 4. Prepare timesteps
1110
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1111
+
1112
+ timesteps = self.scheduler.timesteps
1113
+ if use_ddpm:
1114
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps[-zs.shape[0]:])}
1115
+ timesteps = timesteps[-zs.shape[0]:]
1116
+
1117
+ self.attention_store = AttentionStore(average=store_averaged_over_steps)
1118
+ # self.prepare_unet(self.attention_store, enabled_editing_prompts)
1119
+
1120
+ # 5. Prepare latent variables
1121
+ num_channels_latents = self.unet.config.in_channels
1122
+ latents = self.prepare_latents(
1123
+ batch_size * num_images_per_prompt,
1124
+ num_channels_latents,
1125
+ height,
1126
+ width,
1127
+ prompt_embeds.dtype,
1128
+ device,
1129
+ latents,
1130
+ )
1131
+
1132
+ if user_mask is not None:
1133
+ user_mask = user_mask.to(self.device)
1134
+ assert(latents.shape[-2:] == user_mask.shape)
1135
+
1136
+ # 6. Prepare extra step kwargs.
1137
+ extra_step_kwargs = self.prepare_extra_step_kwargs(eta)
1138
+
1139
+ # 7. Prepare added time ids & embeddings
1140
+ add_text_embeds = pooled_prompt_embeds
1141
+ add_time_ids = self._get_add_time_ids(
1142
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
1143
+ )
1144
+
1145
+ self.text_cross_attention_maps = [prompt] if isinstance(prompt, str) else prompt
1146
+ if enable_edit_guidance:
1147
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, edit_prompt_embeds], dim=0)
1148
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds, pooled_edit_embeds], dim=0)
1149
+ edit_concepts_time_ids = add_time_ids.repeat(edit_prompt_embeds.shape[0], 1)
1150
+ add_time_ids = torch.cat([add_time_ids, add_time_ids, edit_concepts_time_ids], dim=0)
1151
+
1152
+ self.text_cross_attention_maps += \
1153
+ ([editing_prompt] if isinstance(editing_prompt, str) else editing_prompt)
1154
+ elif do_classifier_free_guidance:
1155
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1156
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1157
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1158
+
1159
+ prompt_embeds = prompt_embeds.to(device)
1160
+ add_text_embeds = add_text_embeds.to(device)
1161
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1162
+
1163
+ # 8. Denoising loop
1164
+ edit_momentum = None
1165
+ self.uncond_estimates = None
1166
+ self.text_estimates = None
1167
+ self.edit_estimates = None
1168
+ self.sem_guidance = None
1169
+
1170
+ with self.progress_bar(total=len(timesteps)) as progress_bar:
1171
+ for i, t in enumerate(timesteps):
1172
+ # expand the latents if we are doing classifier free guidance
1173
+ latent_model_input = (
1174
+ torch.cat([latents] * (2 + enabled_editing_prompts)) if do_classifier_free_guidance else latents
1175
+ )
1176
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1177
+
1178
+ # predict the noise residual
1179
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1180
+ noise_pred = self.unet(
1181
+ latent_model_input,
1182
+ t,
1183
+ encoder_hidden_states=prompt_embeds,
1184
+ cross_attention_kwargs=cross_attention_kwargs,
1185
+ added_cond_kwargs=added_cond_kwargs,
1186
+ return_dict=False,
1187
+ )[0]
1188
+
1189
+ # perform guidance
1190
+ if do_classifier_free_guidance:
1191
+ noise_pred_out = noise_pred.chunk(2 + enabled_editing_prompts) # [b,4, 64, 64]
1192
+ noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
1193
+ noise_pred_edit_concepts = noise_pred_out[2:]
1194
+
1195
+ #noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1196
+ noise_guidance = guidance_scale * (noise_pred_text - noise_pred_uncond)
1197
+
1198
+ if self.uncond_estimates is None:
1199
+ self.uncond_estimates = torch.zeros((len(timesteps), *noise_pred_uncond.shape))
1200
+ self.uncond_estimates[i] = noise_pred_uncond.detach().cpu()
1201
+
1202
+ if self.text_estimates is None:
1203
+ self.text_estimates = torch.zeros((len(timesteps), *noise_pred_text.shape))
1204
+ self.text_estimates[i] = noise_pred_text.detach().cpu()
1205
+
1206
+ if self.edit_estimates is None and enable_edit_guidance:
1207
+ self.edit_estimates = torch.zeros(
1208
+ (len(timesteps), len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
1209
+ )
1210
+
1211
+ if self.sem_guidance is None:
1212
+ self.sem_guidance = torch.zeros((len(timesteps), *noise_pred_text.shape))
1213
+
1214
+ if edit_momentum is None:
1215
+ edit_momentum = torch.zeros_like(noise_guidance)
1216
+
1217
+ if enable_edit_guidance:
1218
+ concept_weights = torch.zeros(
1219
+ (len(noise_pred_edit_concepts), noise_guidance.shape[0]),
1220
+ device=self.device,
1221
+ dtype=noise_guidance.dtype,
1222
+ )
1223
+ noise_guidance_edit = torch.zeros(
1224
+ (len(noise_pred_edit_concepts), *noise_guidance.shape),
1225
+ device=self.device,
1226
+ dtype=noise_guidance.dtype,
1227
+ )
1228
+ # noise_guidance_edit = torch.zeros_like(noise_guidance)
1229
+ warmup_inds = []
1230
+ for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
1231
+ self.edit_estimates[i, c] = noise_pred_edit_concept
1232
+ if isinstance(edit_guidance_scale, list):
1233
+ edit_guidance_scale_c = edit_guidance_scale[c]
1234
+ else:
1235
+ edit_guidance_scale_c = edit_guidance_scale
1236
+
1237
+ if isinstance(edit_threshold, list):
1238
+ edit_threshold_c = edit_threshold[c]
1239
+ else:
1240
+ edit_threshold_c = edit_threshold
1241
+ if isinstance(reverse_editing_direction, list):
1242
+ reverse_editing_direction_c = reverse_editing_direction[c]
1243
+ else:
1244
+ reverse_editing_direction_c = reverse_editing_direction
1245
+ if edit_weights:
1246
+ edit_weight_c = edit_weights[c]
1247
+ else:
1248
+ edit_weight_c = 1.0
1249
+ if isinstance(edit_warmup_steps, list):
1250
+ edit_warmup_steps_c = edit_warmup_steps[c]
1251
+ else:
1252
+ edit_warmup_steps_c = edit_warmup_steps
1253
+
1254
+ if isinstance(edit_cooldown_steps, list):
1255
+ edit_cooldown_steps_c = edit_cooldown_steps[c]
1256
+ elif edit_cooldown_steps is None:
1257
+ edit_cooldown_steps_c = i + 1
1258
+ else:
1259
+ edit_cooldown_steps_c = edit_cooldown_steps
1260
+ if i >= edit_warmup_steps_c:
1261
+ warmup_inds.append(c)
1262
+ if i >= edit_cooldown_steps_c:
1263
+ noise_guidance_edit[c, :, :, :, :] = torch.zeros_like(noise_pred_edit_concept)
1264
+ continue
1265
+
1266
+ noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
1267
+ # tmp_weights = (noise_pred_text - noise_pred_edit_concept).sum(dim=(1, 2, 3))
1268
+ tmp_weights = (noise_guidance - noise_pred_edit_concept).sum(dim=(1, 2, 3))
1269
+
1270
+ tmp_weights = torch.full_like(tmp_weights, edit_weight_c) # * (1 / enabled_editing_prompts)
1271
+ if reverse_editing_direction_c:
1272
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
1273
+ concept_weights[c, :] = tmp_weights
1274
+
1275
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
1276
+
1277
+ if user_mask is not None:
1278
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * user_mask
1279
+
1280
+ if use_cross_attn_mask:
1281
+ out = self.attention_store.aggregate_attention(
1282
+ attention_maps=self.attention_store.step_store,
1283
+ prompts=self.text_cross_attention_maps,
1284
+ res=32,
1285
+ from_where=["up","down"],
1286
+ is_cross=True,
1287
+ select=self.text_cross_attention_maps.index(editing_prompt[c]),
1288
+ )
1289
+
1290
+ attn_map = out[:, :, 1:1+num_edit_tokens[c]] # 0 -> startoftext
1291
+
1292
+ # average over all tokens
1293
+ assert(attn_map.shape[2]==num_edit_tokens[c])
1294
+ attn_map = torch.sum(attn_map, dim=2)
1295
+
1296
+ # gaussian_smoothing
1297
+ attn_map = F.pad(attn_map.unsqueeze(0).unsqueeze(0), (1, 1, 1, 1), mode="reflect")
1298
+ attn_map = self.smoothing(attn_map).squeeze(0).squeeze(0)
1299
+
1300
+ # create binary mask
1301
+ # torch.quantile function expects float32
1302
+ if attn_map.dtype == torch.float32:
1303
+ tmp = torch.quantile(
1304
+ attn_map.flatten(),
1305
+ edit_threshold_c
1306
+ )
1307
+ else:
1308
+ tmp = torch.quantile(
1309
+ attn_map.flatten().to(torch.float32),
1310
+ edit_threshold_c
1311
+ ).to(attn_map.dtype)
1312
+
1313
+ attn_mask = torch.where(attn_map >= tmp, 1.0, 0.0)
1314
+
1315
+ # resolution must match latent space dimension
1316
+ attn_mask = F.interpolate(
1317
+ attn_mask.unsqueeze(0).unsqueeze(0),
1318
+ noise_guidance_edit_tmp.shape[-2:]
1319
+ )[0,0,:,:]
1320
+
1321
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
1322
+ else:
1323
+ # calculate quantile
1324
+ noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
1325
+ noise_guidance_edit_tmp_quantile = torch.sum(noise_guidance_edit_tmp_quantile, dim=1, keepdim=True)
1326
+ noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1,4,1,1)
1327
+
1328
+ # torch.quantile function expects float32
1329
+ if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
1330
+ tmp = torch.quantile(
1331
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
1332
+ edit_threshold_c,
1333
+ dim=2,
1334
+ keepdim=False,
1335
+ )
1336
+ else:
1337
+ tmp = torch.quantile(
1338
+ noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
1339
+ edit_threshold_c,
1340
+ dim=2,
1341
+ keepdim=False,
1342
+ ).to(noise_guidance_edit_tmp_quantile.dtype)
1343
+
1344
+ noise_guidance_edit_tmp = torch.where(
1345
+ noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
1346
+ noise_guidance_edit_tmp,
1347
+ torch.zeros_like(noise_guidance_edit_tmp),
1348
+ )
1349
+
1350
+ noise_guidance_edit[c, :, :, :, :] = noise_guidance_edit_tmp
1351
+
1352
+ warmup_inds = torch.tensor(warmup_inds).to(self.device)
1353
+ if len(noise_pred_edit_concepts) > warmup_inds.shape[0] > 0:
1354
+ concept_weights = concept_weights.to("cpu") # Offload to cpu
1355
+ noise_guidance_edit = noise_guidance_edit.to("cpu")
1356
+
1357
+ concept_weights_tmp = torch.index_select(concept_weights.to(self.device), 0, warmup_inds)
1358
+ concept_weights_tmp = torch.where(
1359
+ concept_weights_tmp < 0, torch.zeros_like(concept_weights_tmp), concept_weights_tmp
1360
+ )
1361
+ concept_weights_tmp = concept_weights_tmp / concept_weights_tmp.sum(dim=0)
1362
+ # concept_weights_tmp = torch.nan_to_num(concept_weights_tmp)
1363
+
1364
+ noise_guidance_edit_tmp = torch.index_select(
1365
+ noise_guidance_edit.to(self.device), 0, warmup_inds
1366
+ )
1367
+ noise_guidance_edit_tmp = torch.einsum(
1368
+ "cb,cbijk->bijk", concept_weights_tmp, noise_guidance_edit_tmp
1369
+ )
1370
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp
1371
+ noise_guidance = noise_guidance + noise_guidance_edit_tmp
1372
+
1373
+ self.sem_guidance[i] = noise_guidance_edit_tmp.detach().cpu()
1374
+
1375
+ del noise_guidance_edit_tmp
1376
+ del concept_weights_tmp
1377
+ concept_weights = concept_weights.to(self.device)
1378
+ noise_guidance_edit = noise_guidance_edit.to(self.device)
1379
+
1380
+ concept_weights = torch.where(
1381
+ concept_weights < 0, torch.zeros_like(concept_weights), concept_weights
1382
+ )
1383
+
1384
+ concept_weights = torch.nan_to_num(concept_weights)
1385
+
1386
+ noise_guidance_edit = torch.einsum("cb,cbijk->bijk", concept_weights, noise_guidance_edit)
1387
+
1388
+ noise_guidance_edit = noise_guidance_edit + edit_momentum_scale * edit_momentum
1389
+
1390
+ edit_momentum = edit_mom_beta * edit_momentum + (1 - edit_mom_beta) * noise_guidance_edit
1391
+
1392
+ if warmup_inds.shape[0] == len(noise_pred_edit_concepts):
1393
+ noise_guidance = noise_guidance + noise_guidance_edit
1394
+ self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
1395
+
1396
+ if sem_guidance is not None:
1397
+ edit_guidance = sem_guidance[i].to(self.device)
1398
+ noise_guidance = noise_guidance + edit_guidance
1399
+
1400
+ noise_pred = noise_pred_uncond + noise_guidance
1401
+
1402
+ # TODO: compatible with SEGA?
1403
+ #if do_classifier_free_guidance and guidance_rescale > 0.0:
1404
+ # # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1405
+ # noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1406
+
1407
+ # compute the previous noisy sample x_t -> x_t-1
1408
+ if use_ddpm:
1409
+ idx = t_to_idx[int(t)]
1410
+ latents = self.scheduler.step(noise_pred, t, latents, variance_noise=zs[idx], **extra_step_kwargs).prev_sample
1411
+
1412
+ else: #if not use_ddpm:
1413
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1414
+
1415
+ # step callback
1416
+ store_step = i in attn_store_steps
1417
+ if store_step:
1418
+ print(f"storing attention for step {i}")
1419
+ self.attention_store.between_steps(store_step)
1420
+
1421
+ # call the callback, if provided
1422
+ progress_bar.update()
1423
+ if callback is not None and i % callback_steps == 0:
1424
+ callback(i, t, latents)
1425
+
1426
+ # make sure the VAE is in float32 mode, as it overflows in float16
1427
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1428
+ self.upcast_vae()
1429
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1430
+ elif self.vae.config.force_upcast:
1431
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1432
+
1433
+ if not output_type == "latent":
1434
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1435
+ else:
1436
+ image = latents
1437
+ return StableDiffusionXLPipelineOutput(images=image)
1438
+
1439
+ # apply watermark if available
1440
+ if self.watermark is not None:
1441
+ image = self.watermark.apply_watermark(image)
1442
+
1443
+ image = self.image_processor.postprocess(image, output_type=output_type)
1444
+
1445
+ # Offload last model to CPU
1446
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1447
+ self.final_offload_hook.offload()
1448
+
1449
+ if not return_dict:
1450
+ return (image,)
1451
+
1452
+ return StableDiffusionXLPipelineOutput(images=image)
1453
+
1454
+ # Overrride to properly handle the loading and unloading of the additional text encoder.
1455
+ def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
1456
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1457
+ # it here explicitly to be able to tell that it's coming from an SDXL
1458
+ # pipeline.
1459
+ state_dict, network_alphas = self.lora_state_dict(
1460
+ pretrained_model_name_or_path_or_dict,
1461
+ unet_config=self.unet.config,
1462
+ **kwargs,
1463
+ )
1464
+ self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
1465
+
1466
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1467
+ if len(text_encoder_state_dict) > 0:
1468
+ self.load_lora_into_text_encoder(
1469
+ text_encoder_state_dict,
1470
+ network_alphas=network_alphas,
1471
+ text_encoder=self.text_encoder,
1472
+ prefix="text_encoder",
1473
+ lora_scale=self.lora_scale,
1474
+ )
1475
+
1476
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1477
+ if len(text_encoder_2_state_dict) > 0:
1478
+ self.load_lora_into_text_encoder(
1479
+ text_encoder_2_state_dict,
1480
+ network_alphas=network_alphas,
1481
+ text_encoder=self.text_encoder_2,
1482
+ prefix="text_encoder_2",
1483
+ lora_scale=self.lora_scale,
1484
+ )
1485
+
1486
+ @classmethod
1487
+ def save_lora_weights(
1488
+ self,
1489
+ save_directory: Union[str, os.PathLike],
1490
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1491
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1492
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1493
+ is_main_process: bool = True,
1494
+ weight_name: str = None,
1495
+ save_function: Callable = None,
1496
+ safe_serialization: bool = True,
1497
+ ):
1498
+ state_dict = {}
1499
+
1500
+ def pack_weights(layers, prefix):
1501
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1502
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1503
+ return layers_state_dict
1504
+
1505
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1506
+
1507
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1508
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1509
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1510
+
1511
+ self.write_lora_layers(
1512
+ state_dict=state_dict,
1513
+ save_directory=save_directory,
1514
+ is_main_process=is_main_process,
1515
+ weight_name=weight_name,
1516
+ save_function=save_function,
1517
+ safe_serialization=safe_serialization,
1518
+ )
1519
+
1520
+ def _remove_text_encoder_monkey_patch(self):
1521
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1522
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
1523
+
1524
+
1525
+ @torch.no_grad()
1526
+ def invert(self,
1527
+ # image_path: str,
1528
+ x0,
1529
+ source_prompt: str = "",
1530
+ source_prompt_2: str = None,
1531
+ source_guidance_scale = 3.5,
1532
+ negative_prompt: str = None,
1533
+ negative_prompt_2: str = None,
1534
+ num_inversion_steps: int = 100,
1535
+ skip_steps: int = 35,
1536
+ eta: float = 1.0,
1537
+ generator: Optional[torch.Generator] = None,
1538
+ height: Optional[int] = None,
1539
+ width: Optional[int] = None,
1540
+ original_size: Optional[Tuple[int, int]] = None,
1541
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1542
+ target_size: Optional[Tuple[int, int]] = None,
1543
+ ):
1544
+ """
1545
+ Inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
1546
+ based on the code in https://github.com/inbarhub/DDPM_inversion
1547
+
1548
+ returns:
1549
+ zs - noise maps
1550
+ xts - intermediate inverted latents
1551
+ """
1552
+
1553
+ # self.eta = eta
1554
+ # assert(self.eta > 0)
1555
+
1556
+ self.num_inversion_steps = num_inversion_steps
1557
+ self.scheduler.set_timesteps(self.num_inversion_steps)
1558
+ timesteps = self.scheduler.timesteps.to(self.device)
1559
+
1560
+ cross_attention_kwargs = None # TODO
1561
+ batch_size = 1
1562
+ num_images_per_prompt = 1
1563
+
1564
+ device = self._execution_device
1565
+
1566
+ # Reset attn processor, we do not want to store attn maps during inversion
1567
+ # self.unet.set_default_attn_processor()
1568
+
1569
+ # 0. Ensure that only uncond embedding is used if prompt = ""
1570
+ if source_prompt == "" and \
1571
+ (source_prompt_2 == "" or source_prompt_2 is None):
1572
+ # noise pred should only be noise_pred_uncond
1573
+ source_guidance_scale = 0.0
1574
+ do_classifier_free_guidance = True
1575
+ else:
1576
+ do_classifier_free_guidance = source_guidance_scale > 1.0
1577
+
1578
+ # 1. Default height and width to unet
1579
+ height = height or self.default_sample_size * self.vae_scale_factor
1580
+ width = width or self.default_sample_size * self.vae_scale_factor
1581
+ original_size = original_size or (height, width)
1582
+ target_size = target_size or (height, width)
1583
+
1584
+ self.height = height
1585
+ self.width = width
1586
+ self.original_size = original_size
1587
+ self.target_size = target_size
1588
+
1589
+ # 2. get embeddings
1590
+ text_encoder_lora_scale = (
1591
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1592
+ )
1593
+
1594
+ (
1595
+ prompt_embeds,
1596
+ negative_prompt_embeds,
1597
+ _,
1598
+ pooled_prompt_embeds,
1599
+ negative_pooled_prompt_embeds,
1600
+ _,
1601
+ _
1602
+ ) = self.encode_prompt(
1603
+ prompt=source_prompt,
1604
+ prompt_2=source_prompt_2,
1605
+ device=device,
1606
+ num_images_per_prompt=num_images_per_prompt,
1607
+ do_classifier_free_guidance=do_classifier_free_guidance,
1608
+ negative_prompt=negative_prompt,
1609
+ negative_prompt_2=negative_prompt_2,
1610
+ lora_scale=text_encoder_lora_scale,
1611
+ enable_edit_guidance=False,
1612
+ )
1613
+
1614
+ # 3. Prepare added time ids & embeddings
1615
+ add_text_embeds = pooled_prompt_embeds
1616
+ add_time_ids = self._get_add_time_ids(
1617
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
1618
+ )
1619
+
1620
+ if do_classifier_free_guidance:
1621
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1622
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1623
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1624
+
1625
+ prompt_embeds = prompt_embeds.to(device)
1626
+ add_text_embeds = add_text_embeds.to(device)
1627
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1628
+
1629
+ # # 4. prepare image
1630
+ # image = Image.open(image_path)
1631
+ # size = self.unet.sample_size * self.vae_scale_factor
1632
+ # image = image.convert("RGB").resize((size,size))
1633
+ # image = self.image_processor.preprocess(image)
1634
+ # image = image.to(device=device, dtype=negative_prompt_embeds.dtype)
1635
+
1636
+ # if image.shape[1] == 4:
1637
+ # x0 = image
1638
+ # else:
1639
+ # if self.vae.config.force_upcast:
1640
+ # image = image.float()
1641
+ # self.vae.to(dtype=torch.float32)
1642
+
1643
+ # x0 = self.vae.encode(image).latent_dist.sample(generator)
1644
+ # x0 = x0.to(negative_prompt_embeds.dtype)
1645
+ # x0 = self.vae.config.scaling_factor * x0
1646
+
1647
+ # autoencoder reconstruction
1648
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1649
+ self.upcast_vae()
1650
+ x0_tmp = x0.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1651
+ image_rec = self.vae.decode(x0_tmp / self.vae.config.scaling_factor, return_dict=False)[0]
1652
+ elif self.vae.config.force_upcast:
1653
+ x0_tmp = x0.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1654
+ image_rec = self.vae.decode(x0_tmp / self.vae.config.scaling_factor, return_dict=False)[0]
1655
+ else:
1656
+ image_rec = self.vae.decode(x0 / self.vae.config.scaling_factor, return_dict=False)[0]
1657
+
1658
+ image_rec = self.image_processor.postprocess(image_rec, output_type="pil")
1659
+
1660
+ # 5. find zs and xts
1661
+ variance_noise_shape = (
1662
+ self.num_inversion_steps,
1663
+ self.unet.config.in_channels,
1664
+ self.unet.sample_size,
1665
+ self.unet.sample_size)
1666
+
1667
+ # intermediate latents
1668
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps)}
1669
+ xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=negative_prompt_embeds.dtype)
1670
+
1671
+ for t in reversed(timesteps):
1672
+ idx = t_to_idx[int(t)]
1673
+ noise = randn_tensor(shape=x0.shape, generator=generator, device=self.device, dtype=x0.dtype)
1674
+ xts[idx] = self.scheduler.add_noise(x0, noise, t)
1675
+ xts = torch.cat([xts, x0 ],dim = 0)
1676
+
1677
+ # noise maps
1678
+ zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=negative_prompt_embeds.dtype)
1679
+
1680
+ for t in tqdm(timesteps):
1681
+ idx = t_to_idx[int(t)]
1682
+ # 1. predict noise residual
1683
+ xt = xts[idx][None]
1684
+
1685
+ latent_model_input = (
1686
+ torch.cat([xt] * 2) if do_classifier_free_guidance else xt
1687
+ )
1688
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1689
+
1690
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1691
+ noise_pred = self.unet(
1692
+ latent_model_input,
1693
+ t,
1694
+ encoder_hidden_states=prompt_embeds,
1695
+ cross_attention_kwargs=cross_attention_kwargs,
1696
+ added_cond_kwargs=added_cond_kwargs,
1697
+ return_dict=False,
1698
+ )[0]
1699
+
1700
+ # 2. perform guidance
1701
+ if do_classifier_free_guidance:
1702
+ noise_pred_out = noise_pred.chunk(2)
1703
+ noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
1704
+ noise_pred = noise_pred_uncond + source_guidance_scale * (noise_pred_text - noise_pred_uncond)
1705
+
1706
+ xtm1 = xts[idx+1][None]
1707
+ z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, eta)
1708
+ zs[idx] = z
1709
+
1710
+ # correction to avoid error accumulation
1711
+ xts[idx+1] = xtm1_corrected
1712
+
1713
+ # TODO: I don't think that the noise map for the last step should be discarded ?!
1714
+ # if not zs is None:
1715
+ # zs[-1] = torch.zeros_like(zs[-1])
1716
+
1717
+ # self.init_latents = xts[skip_steps].expand(1, -1, -1, -1)
1718
+ # self.zs = zs[skip_steps:]
1719
+ # self.wts = xts
1720
+ # self.latents_path = xts[skip_steps:]
1721
+ # return zs, xts, image_rec
1722
+ return zs, xts
1723
+
1724
+
1725
+ # Copied from pipelines.StableDiffusion.CycleDiffusionPipeline.compute_noise
1726
+ def compute_noise(scheduler, prev_latents, latents, timestep, noise_pred, eta):
1727
+ # 1. get previous step value (=t-1)
1728
+ prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
1729
+
1730
+ # 2. compute alphas, betas
1731
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
1732
+ alpha_prod_t_prev = (
1733
+ scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
1734
+ )
1735
+
1736
+ beta_prod_t = 1 - alpha_prod_t
1737
+
1738
+ # 3. compute predicted original sample from predicted noise also called
1739
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1740
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
1741
+
1742
+ # 4. Clip "predicted x_0"
1743
+ if scheduler.config.clip_sample:
1744
+ pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
1745
+
1746
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
1747
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
1748
+ variance = scheduler._get_variance(timestep, prev_timestep)
1749
+ std_dev_t = eta * variance ** (0.5)
1750
+
1751
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
1752
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * noise_pred
1753
+
1754
+ # modifed so that updated xtm1 is returned as well (to avoid error accumulation)
1755
+ mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
1756
+ noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
1757
+
1758
+ return noise, mu_xt + ( eta * variance ** 0.5 )*noise