rodrigomasini commited on
Commit
96f7484
1 Parent(s): 093740e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +573 -1
app.py CHANGED
@@ -1001,7 +1001,579 @@ use_safetensors= False
1001
  # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
1002
  # pipe1.scheduler.set_timesteps(50)
1003
  ###
1004
- pipe2 = StableDiffusionXLPipeline.from_pretrained(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1005
  models_dict["Unstable"], torch_dtype=torch.float16, use_safetensors=use_safetensors)
1006
  pipe2 = pipe2.to("cpu")
1007
  pipe2.load_photomaker_adapter(
 
1001
  # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
1002
  # pipe1.scheduler.set_timesteps(50)
1003
  ###
1004
+
1005
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
1006
+ from collections import OrderedDict
1007
+ import os
1008
+ import PIL
1009
+ import numpy as np
1010
+
1011
+ import torch
1012
+ from torchvision import transforms as T
1013
+
1014
+ from safetensors import safe_open
1015
+ from huggingface_hub.utils import validate_hf_hub_args
1016
+ from transformers import CLIPImageProcessor, CLIPTokenizer
1017
+ from diffusers import StableDiffusionXLPipeline
1018
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
1019
+ from diffusers.utils import (
1020
+ _get_model_file,
1021
+ is_transformers_available,
1022
+ logging,
1023
+ )
1024
+
1025
+ from . import PhotoMakerIDEncoder
1026
+
1027
+ PipelineImageInput = Union[
1028
+ PIL.Image.Image,
1029
+ torch.FloatTensor,
1030
+ List[PIL.Image.Image],
1031
+ List[torch.FloatTensor],
1032
+ ]
1033
+
1034
+
1035
+ class PhotoMakerStableDiffusionXLPipeline(StableDiffusionXLPipeline):
1036
+ @validate_hf_hub_args
1037
+ def load_photomaker_adapter(
1038
+ self,
1039
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1040
+ weight_name: str,
1041
+ subfolder: str = '',
1042
+ trigger_word: str = 'img',
1043
+ **kwargs,
1044
+ ):
1045
+ """
1046
+ Parameters:
1047
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1048
+ Can be either:
1049
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
1050
+ the Hub.
1051
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
1052
+ with [`ModelMixin.save_pretrained`].
1053
+ - A [torch state
1054
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
1055
+ weight_name (`str`):
1056
+ The weight name NOT the path to the weight.
1057
+ subfolder (`str`, defaults to `""`):
1058
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
1059
+ trigger_word (`str`, *optional*, defaults to `"img"`):
1060
+ The trigger word is used to identify the position of class word in the text prompt,
1061
+ and it is recommended not to set it as a common word.
1062
+ This trigger word must be placed after the class word when used, otherwise, it will affect the performance of the personalized generation.
1063
+ """
1064
+
1065
+ # Load the main state dict first.
1066
+ cache_dir = kwargs.pop("cache_dir", None)
1067
+ force_download = kwargs.pop("force_download", False)
1068
+ resume_download = kwargs.pop("resume_download", False)
1069
+ proxies = kwargs.pop("proxies", None)
1070
+ local_files_only = kwargs.pop("local_files_only", None)
1071
+ token = kwargs.pop("token", None)
1072
+ revision = kwargs.pop("revision", None)
1073
+
1074
+ user_agent = {
1075
+ "file_type": "attn_procs_weights",
1076
+ "framework": "pytorch",
1077
+ }
1078
+
1079
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
1080
+ model_file = _get_model_file(
1081
+ pretrained_model_name_or_path_or_dict,
1082
+ weights_name=weight_name,
1083
+ cache_dir=cache_dir,
1084
+ force_download=force_download,
1085
+ resume_download=resume_download,
1086
+ proxies=proxies,
1087
+ local_files_only=local_files_only,
1088
+ token=token,
1089
+ revision=revision,
1090
+ subfolder=subfolder,
1091
+ user_agent=user_agent,
1092
+ )
1093
+ if weight_name.endswith(".safetensors"):
1094
+ state_dict = {"id_encoder": {}, "lora_weights": {}}
1095
+ with safe_open(model_file, framework="pt", device="cpu") as f:
1096
+ for key in f.keys():
1097
+ if key.startswith("id_encoder."):
1098
+ state_dict["id_encoder"][key.replace("id_encoder.", "")] = f.get_tensor(key)
1099
+ elif key.startswith("lora_weights."):
1100
+ state_dict["lora_weights"][key.replace("lora_weights.", "")] = f.get_tensor(key)
1101
+ else:
1102
+ state_dict = torch.load(model_file, map_location="cpu")
1103
+ else:
1104
+ state_dict = pretrained_model_name_or_path_or_dict
1105
+
1106
+ keys = list(state_dict.keys())
1107
+ if keys != ["id_encoder", "lora_weights"]:
1108
+ raise ValueError("Required keys are (`id_encoder` and `lora_weights`) missing from the state dict.")
1109
+
1110
+ self.trigger_word = trigger_word
1111
+ # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet
1112
+ print(f"Loading PhotoMaker components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...")
1113
+ id_encoder = PhotoMakerIDEncoder()
1114
+ id_encoder.load_state_dict(state_dict["id_encoder"], strict=True)
1115
+ id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype)
1116
+ self.id_encoder = id_encoder
1117
+ self.id_image_processor = CLIPImageProcessor()
1118
+
1119
+ # load lora into models
1120
+ print(f"Loading PhotoMaker components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]")
1121
+ self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
1122
+
1123
+ # Add trigger word token
1124
+ if self.tokenizer is not None:
1125
+ self.tokenizer.add_tokens([self.trigger_word], special_tokens=True)
1126
+
1127
+ self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
1128
+
1129
+
1130
+ def encode_prompt_with_trigger_word(
1131
+ self,
1132
+ prompt: str,
1133
+ prompt_2: Optional[str] = None,
1134
+ num_id_images: int = 1,
1135
+ device: Optional[torch.device] = None,
1136
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1137
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1138
+ class_tokens_mask: Optional[torch.LongTensor] = None,
1139
+ ):
1140
+ device = device or self._execution_device
1141
+
1142
+ if prompt is not None and isinstance(prompt, str):
1143
+ batch_size = 1
1144
+ elif prompt is not None and isinstance(prompt, list):
1145
+ batch_size = len(prompt)
1146
+ else:
1147
+ batch_size = prompt_embeds.shape[0]
1148
+
1149
+ # Find the token id of the trigger word
1150
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
1151
+
1152
+ # Define tokenizers and text encoders
1153
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
1154
+ text_encoders = (
1155
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
1156
+ )
1157
+
1158
+ if prompt_embeds is None:
1159
+ prompt_2 = prompt_2 or prompt
1160
+ prompt_embeds_list = []
1161
+ prompts = [prompt, prompt_2]
1162
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
1163
+ input_ids = tokenizer.encode(prompt) # TODO: batch encode
1164
+ clean_index = 0
1165
+ clean_input_ids = []
1166
+ class_token_index = []
1167
+ # Find out the corresponding class word token based on the newly added trigger word token
1168
+ for i, token_id in enumerate(input_ids):
1169
+ if token_id == image_token_id:
1170
+ class_token_index.append(clean_index - 1)
1171
+ else:
1172
+ clean_input_ids.append(token_id)
1173
+ clean_index += 1
1174
+
1175
+ if len(class_token_index) != 1:
1176
+ raise ValueError(
1177
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
1178
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
1179
+ )
1180
+ class_token_index = class_token_index[0]
1181
+
1182
+ # Expand the class word token and corresponding mask
1183
+ class_token = clean_input_ids[class_token_index]
1184
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images + \
1185
+ clean_input_ids[class_token_index+1:]
1186
+
1187
+ # Truncation or padding
1188
+ max_len = tokenizer.model_max_length
1189
+ if len(clean_input_ids) > max_len:
1190
+ clean_input_ids = clean_input_ids[:max_len]
1191
+ else:
1192
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
1193
+ max_len - len(clean_input_ids)
1194
+ )
1195
+
1196
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+num_id_images else False \
1197
+ for i in range(len(clean_input_ids))]
1198
+
1199
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
1200
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
1201
+
1202
+ prompt_embeds = text_encoder(
1203
+ clean_input_ids.to(device),
1204
+ output_hidden_states=True,
1205
+ )
1206
+
1207
+ # We are only ALWAYS interested in the pooled output of the final text encoder
1208
+ pooled_prompt_embeds = prompt_embeds[0]
1209
+ prompt_embeds = prompt_embeds.hidden_states[-2]
1210
+ prompt_embeds_list.append(prompt_embeds)
1211
+
1212
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
1213
+
1214
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
1215
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
1216
+
1217
+ return prompt_embeds, pooled_prompt_embeds, class_tokens_mask
1218
+
1219
+ @property
1220
+ def interrupt(self):
1221
+ return self._interrupt
1222
+
1223
+ @torch.no_grad()
1224
+ def __call__(
1225
+ self,
1226
+ prompt: Union[str, List[str]] = None,
1227
+ prompt_2: Optional[Union[str, List[str]]] = None,
1228
+ height: Optional[int] = None,
1229
+ width: Optional[int] = None,
1230
+ num_inference_steps: int = 50,
1231
+ denoising_end: Optional[float] = None,
1232
+ guidance_scale: float = 5.0,
1233
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1234
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1235
+ num_images_per_prompt: Optional[int] = 1,
1236
+ eta: float = 0.0,
1237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1238
+ latents: Optional[torch.FloatTensor] = None,
1239
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1240
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1241
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1242
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1243
+ output_type: Optional[str] = "pil",
1244
+ return_dict: bool = True,
1245
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1246
+ guidance_rescale: float = 0.0,
1247
+ original_size: Optional[Tuple[int, int]] = None,
1248
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1249
+ target_size: Optional[Tuple[int, int]] = None,
1250
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1251
+ callback_steps: int = 1,
1252
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1253
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1254
+ # Added parameters (for PhotoMaker)
1255
+ input_id_images: PipelineImageInput = None,
1256
+ start_merge_step: int = 0, # TODO: change to `style_strength_ratio` in the future
1257
+ class_tokens_mask: Optional[torch.LongTensor] = None,
1258
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
1259
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
1260
+ ):
1261
+ r"""
1262
+ Function invoked when calling the pipeline for generation.
1263
+ Only the parameters introduced by PhotoMaker are discussed here.
1264
+ For explanations of the previous parameters in StableDiffusionXLPipeline, please refer to https://github.com/huggingface/diffusers/blob/v0.25.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py
1265
+ Args:
1266
+ input_id_images (`PipelineImageInput`, *optional*):
1267
+ Input ID Image to work with PhotoMaker.
1268
+ class_tokens_mask (`torch.LongTensor`, *optional*):
1269
+ Pre-generated class token. When the `prompt_embeds` parameter is provided in advance, it is necessary to prepare the `class_tokens_mask` beforehand for marking out the position of class word.
1270
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
1271
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1272
+ provided, text embeddings will be generated from `prompt` input argument.
1273
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
1274
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1275
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1276
+ Returns:
1277
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1278
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1279
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1280
+ """
1281
+ # 0. Default height and width to unet
1282
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1283
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1284
+
1285
+ original_size = original_size or (height, width)
1286
+ target_size = target_size or (height, width)
1287
+
1288
+ # 1. Check inputs. Raise error if not correct
1289
+ self.check_inputs(
1290
+ prompt,
1291
+ prompt_2,
1292
+ height,
1293
+ width,
1294
+ callback_steps,
1295
+ negative_prompt,
1296
+ negative_prompt_2,
1297
+ prompt_embeds,
1298
+ negative_prompt_embeds,
1299
+ pooled_prompt_embeds,
1300
+ negative_pooled_prompt_embeds,
1301
+ callback_on_step_end_tensor_inputs,
1302
+ )
1303
+
1304
+ self._interrupt = False
1305
+
1306
+ #
1307
+ if prompt_embeds is not None and class_tokens_mask is None:
1308
+ raise ValueError(
1309
+ "If `prompt_embeds` are provided, `class_tokens_mask` also have to be passed. Make sure to generate `class_tokens_mask` from the same tokenizer that was used to generate `prompt_embeds`."
1310
+ )
1311
+ # check the input id images
1312
+ if input_id_images is None:
1313
+ raise ValueError(
1314
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
1315
+ )
1316
+ if not isinstance(input_id_images, list):
1317
+ input_id_images = [input_id_images]
1318
+
1319
+ # 2. Define call parameters
1320
+ if prompt is not None and isinstance(prompt, str):
1321
+ batch_size = 1
1322
+ prompt = [prompt]
1323
+ elif prompt is not None and isinstance(prompt, list):
1324
+ batch_size = len(prompt)
1325
+ else:
1326
+ batch_size = prompt_embeds.shape[0]
1327
+
1328
+ device = self._execution_device
1329
+
1330
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1331
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1332
+ # corresponds to doing no classifier free guidance.
1333
+ do_classifier_free_guidance = guidance_scale >= 1.0
1334
+
1335
+ assert do_classifier_free_guidance
1336
+
1337
+ # 3. Encode input prompt
1338
+ num_id_images = len(input_id_images)
1339
+ if isinstance(prompt, list):
1340
+ prompt_arr = prompt
1341
+ negative_prompt_embeds_arr = []
1342
+ prompt_embeds_text_only_arr = []
1343
+ prompt_embeds_arr = []
1344
+ latents_arr = []
1345
+ add_time_ids_arr = []
1346
+ negative_pooled_prompt_embeds_arr = []
1347
+ pooled_prompt_embeds_text_only_arr = []
1348
+ pooled_prompt_embeds_arr = []
1349
+ for prompt in prompt_arr:
1350
+ (
1351
+ prompt_embeds,
1352
+ pooled_prompt_embeds,
1353
+ class_tokens_mask,
1354
+ ) = self.encode_prompt_with_trigger_word(
1355
+ prompt=prompt,
1356
+ prompt_2=prompt_2,
1357
+ device=device,
1358
+ num_id_images=num_id_images,
1359
+ prompt_embeds=prompt_embeds,
1360
+ pooled_prompt_embeds=pooled_prompt_embeds,
1361
+ class_tokens_mask=class_tokens_mask,
1362
+ )
1363
+
1364
+ # 4. Encode input prompt without the trigger word for delayed conditioning
1365
+ # encode, remove trigger word token, then decode
1366
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
1367
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
1368
+ tokens_text_only.remove(trigger_word_token)
1369
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
1370
+ print(prompt_text_only)
1371
+ (
1372
+ prompt_embeds_text_only,
1373
+ negative_prompt_embeds,
1374
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
1375
+ negative_pooled_prompt_embeds,
1376
+ ) = self.encode_prompt(
1377
+ prompt=prompt_text_only,
1378
+ prompt_2=prompt_2,
1379
+ device=device,
1380
+ num_images_per_prompt=num_images_per_prompt,
1381
+ do_classifier_free_guidance=True,
1382
+ negative_prompt=negative_prompt,
1383
+ negative_prompt_2=negative_prompt_2,
1384
+ prompt_embeds=prompt_embeds_text_only,
1385
+ negative_prompt_embeds=negative_prompt_embeds,
1386
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
1387
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1388
+ )
1389
+
1390
+ # 5. Prepare the input ID images
1391
+ dtype = next(self.id_encoder.parameters()).dtype
1392
+ if not isinstance(input_id_images[0], torch.Tensor):
1393
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
1394
+
1395
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
1396
+
1397
+ # 6. Get the update text embedding with the stacked ID embedding
1398
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
1399
+
1400
+ bs_embed, seq_len, _ = prompt_embeds.shape
1401
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
1402
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
1403
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
1404
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
1405
+ bs_embed * num_images_per_prompt, -1
1406
+ )
1407
+
1408
+
1409
+ negative_prompt_embeds_arr.append(negative_prompt_embeds)
1410
+ negative_prompt_embeds = None
1411
+ negative_pooled_prompt_embeds_arr.append(negative_pooled_prompt_embeds)
1412
+ negative_pooled_prompt_embeds = None
1413
+ prompt_embeds_text_only_arr.append(prompt_embeds_text_only)
1414
+ prompt_embeds_text_only = None
1415
+ prompt_embeds_arr.append(prompt_embeds)
1416
+ prompt_embeds = None
1417
+ pooled_prompt_embeds_arr.append(pooled_prompt_embeds)
1418
+ pooled_prompt_embeds = None
1419
+ pooled_prompt_embeds_text_only_arr.append(pooled_prompt_embeds_text_only)
1420
+ pooled_prompt_embeds_text_only = None
1421
+ # 7. Prepare timesteps
1422
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1423
+ timesteps = self.scheduler.timesteps
1424
+
1425
+ negative_prompt_embeds = torch.cat(negative_prompt_embeds_arr ,dim =0)
1426
+ print(negative_prompt_embeds.shape)
1427
+ prompt_embeds = torch.cat(prompt_embeds_arr ,dim = 0)
1428
+ print(prompt_embeds.shape)
1429
+
1430
+ prompt_embeds_text_only = torch.cat(prompt_embeds_text_only_arr ,dim = 0)
1431
+ print(prompt_embeds_text_only.shape)
1432
+ pooled_prompt_embeds_text_only = torch.cat(pooled_prompt_embeds_text_only_arr ,dim = 0)
1433
+ print(pooled_prompt_embeds_text_only.shape)
1434
+
1435
+ negative_pooled_prompt_embeds = torch.cat(negative_pooled_prompt_embeds_arr ,dim = 0)
1436
+ print(negative_pooled_prompt_embeds.shape)
1437
+ pooled_prompt_embeds = torch.cat(pooled_prompt_embeds_arr,dim = 0)
1438
+ print(pooled_prompt_embeds.shape)
1439
+ # 8. Prepare latent variables
1440
+ num_channels_latents = self.unet.config.in_channels
1441
+ latents = self.prepare_latents(
1442
+ batch_size * num_images_per_prompt,
1443
+ num_channels_latents,
1444
+ height,
1445
+ width,
1446
+ prompt_embeds.dtype,
1447
+ device,
1448
+ generator,
1449
+ latents,
1450
+ )
1451
+
1452
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1453
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1454
+
1455
+ # 10. Prepare added time ids & embeddings
1456
+ if self.text_encoder_2 is None:
1457
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1458
+ else:
1459
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1460
+
1461
+ add_time_ids = self._get_add_time_ids(
1462
+ original_size,
1463
+ crops_coords_top_left,
1464
+ target_size,
1465
+ dtype=prompt_embeds.dtype,
1466
+ text_encoder_projection_dim=text_encoder_projection_dim,
1467
+ )
1468
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1469
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1470
+
1471
+
1472
+ print(latents.shape)
1473
+ print(add_time_ids.shape)
1474
+
1475
+ # 11. Denoising loop
1476
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1477
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1478
+ for i, t in enumerate(timesteps):
1479
+ if self.interrupt:
1480
+ continue
1481
+
1482
+ latent_model_input = (
1483
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1484
+ )
1485
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1486
+
1487
+ if i <= start_merge_step:
1488
+ current_prompt_embeds = torch.cat(
1489
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
1490
+ )
1491
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0)
1492
+ else:
1493
+ current_prompt_embeds = torch.cat(
1494
+ [negative_prompt_embeds, prompt_embeds], dim=0
1495
+ )
1496
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
1497
+ # predict the noise residual
1498
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1499
+ # print(latent_model_input.shape)
1500
+ # print(t)
1501
+ # print(current_prompt_embeds.shape)
1502
+ # print(add_text_embeds.shape)
1503
+ # print(add_time_ids.shape)
1504
+ #zeros_matrix =
1505
+ #global_mask1024 = torch.cat([torch.randn(1, 1024, 1, 1, device=device) for random_number])
1506
+ #global_mask4096 =
1507
+ noise_pred = self.unet(
1508
+ latent_model_input,
1509
+ t,
1510
+ encoder_hidden_states=current_prompt_embeds,
1511
+ cross_attention_kwargs=cross_attention_kwargs,
1512
+ added_cond_kwargs=added_cond_kwargs,
1513
+ return_dict=False,
1514
+ )[0]
1515
+ # print(noise_pred.shape)
1516
+ # perform guidance
1517
+ if do_classifier_free_guidance:
1518
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1519
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1520
+
1521
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1522
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1523
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1524
+
1525
+ # compute the previous noisy sample x_t -> x_t-1
1526
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1527
+
1528
+ if callback_on_step_end is not None:
1529
+ callback_kwargs = {}
1530
+ for k in callback_on_step_end_tensor_inputs:
1531
+ callback_kwargs[k] = locals()[k]
1532
+
1533
+ ck_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1534
+
1535
+ latents = callback_outputs.pop("latents", latents)
1536
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1537
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1538
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1539
+ # negative_pooled_prompt_embeds = callback_outputs.pop(
1540
+ # "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1541
+ # )
1542
+ # add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1543
+ # negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1544
+
1545
+ # call the callback, if provided
1546
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1547
+ progress_bar.update()
1548
+ if callback is not None and i % callback_steps == 0:
1549
+ step_idx = i // getattr(self.scheduler, "order", 1)
1550
+ callback(step_idx, t, latents)
1551
+
1552
+ # make sure the VAE is in float32 mode, as it overflows in float16
1553
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1554
+ self.upcast_vae()
1555
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1556
+
1557
+ if not output_type == "latent":
1558
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1559
+ else:
1560
+ image = latents
1561
+ return StableDiffusionXLPipelineOutput(images=image)
1562
+
1563
+ # apply watermark if available
1564
+ # if self.watermark is not None:
1565
+ # image = self.watermark.apply_watermark(image)
1566
+
1567
+ image = self.image_processor.postprocess(image, output_type=output_type)
1568
+
1569
+ # Offload all models
1570
+ self.maybe_free_model_hooks()
1571
+
1572
+ if not return_dict:
1573
+ return (image,)
1574
+
1575
+ return StableDiffusionXLPipelineOutput(images=image)
1576
+ pipe2 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
1577
  models_dict["Unstable"], torch_dtype=torch.float16, use_safetensors=use_safetensors)
1578
  pipe2 = pipe2.to("cpu")
1579
  pipe2.load_photomaker_adapter(