pipeline_brushnet_sd_xl.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. # https://github.com/TencentARC/BrushNet
  2. import inspect
  3. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  4. import numpy as np
  5. import PIL.Image
  6. import torch
  7. import torch.nn.functional as F
  8. from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
  9. from diffusers.loaders import (
  10. FromSingleFileMixin,
  11. IPAdapterMixin,
  12. StableDiffusionXLLoraLoaderMixin,
  13. TextualInversionLoaderMixin,
  14. )
  15. from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
  16. from diffusers.models.attention_processor import (
  17. AttnProcessor2_0,
  18. LoRAAttnProcessor2_0,
  19. LoRAXFormersAttnProcessor,
  20. XFormersAttnProcessor,
  21. )
  22. from diffusers.models.lora import adjust_lora_scale_text_encoder
  23. from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
  24. from diffusers.pipelines.stable_diffusion_xl.pipeline_output import (
  25. StableDiffusionXLPipelineOutput,
  26. )
  27. from diffusers.schedulers import KarrasDiffusionSchedulers
  28. from diffusers.utils import (
  29. USE_PEFT_BACKEND,
  30. deprecate,
  31. logging,
  32. replace_example_docstring,
  33. scale_lora_layers,
  34. unscale_lora_layers,
  35. )
  36. from diffusers.utils.import_utils import is_invisible_watermark_available
  37. from diffusers.utils.torch_utils import (
  38. is_compiled_module,
  39. is_torch_version,
  40. randn_tensor,
  41. )
  42. from transformers import (
  43. CLIPImageProcessor,
  44. CLIPTextModel,
  45. CLIPTextModelWithProjection,
  46. CLIPTokenizer,
  47. CLIPVisionModelWithProjection,
  48. )
  49. from .brushnet import BrushNetModel
  50. if is_invisible_watermark_available():
  51. from diffusers.pipelines.stable_diffusion_xl.watermark import (
  52. StableDiffusionXLWatermarker,
  53. )
  54. # from .multibrushnet import MultiBrushNetModel
  55. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  56. EXAMPLE_DOC_STRING = """
  57. Examples:
  58. ```py
  59. >>> # !pip install opencv-python transformers accelerate
  60. >>> from diffusers import StableDiffusionXLBrushNetPipeline, BrushNetModel, AutoencoderKL
  61. >>> from diffusers.utils import load_image
  62. >>> import numpy as np
  63. >>> import torch
  64. >>> import cv2
  65. >>> from PIL import Image
  66. >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
  67. >>> negative_prompt = "low quality, bad quality, sketches"
  68. >>> # download an image
  69. >>> image = load_image(
  70. ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_brushnet/hf-logo.png"
  71. ... )
  72. >>> # initialize the models and pipeline
  73. >>> brushnet_conditioning_scale = 0.5 # recommended for good generalization
  74. >>> brushnet = BrushNetModel.from_pretrained(
  75. ... "diffusers/brushnet-canny-sdxl-1.0", torch_dtype=torch.float16
  76. ... )
  77. >>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
  78. >>> pipe = StableDiffusionXLBrushNetPipeline.from_pretrained(
  79. ... "stabilityai/stable-diffusion-xl-base-1.0", brushnet=brushnet, vae=vae, torch_dtype=torch.float16
  80. ... )
  81. >>> pipe.enable_model_cpu_offload()
  82. >>> # get canny image
  83. >>> image = np.array(image)
  84. >>> image = cv2.Canny(image, 100, 200)
  85. >>> image = image[:, :, None]
  86. >>> image = np.concatenate([image, image, image], axis=2)
  87. >>> canny_image = Image.fromarray(image)
  88. >>> # generate image
  89. >>> image = pipe(
  90. ... prompt, brushnet_conditioning_scale=brushnet_conditioning_scale, image=canny_image
  91. ... ).images[0]
  92. ```
  93. """
  94. class StableDiffusionXLBrushNetPipeline(
  95. DiffusionPipeline,
  96. StableDiffusionMixin,
  97. TextualInversionLoaderMixin,
  98. StableDiffusionXLLoraLoaderMixin,
  99. IPAdapterMixin,
  100. FromSingleFileMixin,
  101. ):
  102. r"""
  103. Pipeline for text-to-image generation using Stable Diffusion XL with BrushNet guidance.
  104. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
  105. implemented for all pipelines (downloading, saving, running on a particular device, etc.).
  106. The pipeline also inherits the following loading methods:
  107. - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
  108. - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
  109. - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
  110. - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
  111. - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
  112. Args:
  113. vae ([`AutoencoderKL`]):
  114. Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
  115. text_encoder ([`~transformers.CLIPTextModel`]):
  116. Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
  117. text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
  118. Second frozen text-encoder
  119. ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
  120. tokenizer ([`~transformers.CLIPTokenizer`]):
  121. A `CLIPTokenizer` to tokenize text.
  122. tokenizer_2 ([`~transformers.CLIPTokenizer`]):
  123. A `CLIPTokenizer` to tokenize text.
  124. unet ([`UNet2DConditionModel`]):
  125. A `UNet2DConditionModel` to denoise the encoded image latents.
  126. brushnet ([`BrushNetModel`] or `List[BrushNetModel]`):
  127. Provides additional conditioning to the `unet` during the denoising process. If you set multiple
  128. BrushNets as a list, the outputs from each BrushNet are added together to create one combined
  129. additional conditioning.
  130. scheduler ([`SchedulerMixin`]):
  131. A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
  132. [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
  133. force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
  134. Whether the negative prompt embeddings should always be set to 0. Also see the config of
  135. `stabilityai/stable-diffusion-xl-base-1-0`.
  136. add_watermarker (`bool`, *optional*):
  137. Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
  138. watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
  139. watermarker is used.
  140. """
  141. # leave brushnet out on purpose because it iterates with unet
  142. model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
  143. _optional_components = [
  144. "tokenizer",
  145. "tokenizer_2",
  146. "text_encoder",
  147. "text_encoder_2",
  148. "feature_extractor",
  149. "image_encoder",
  150. ]
  151. _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
  152. def __init__(
  153. self,
  154. vae: AutoencoderKL,
  155. text_encoder: CLIPTextModel,
  156. text_encoder_2: CLIPTextModelWithProjection,
  157. tokenizer: CLIPTokenizer,
  158. tokenizer_2: CLIPTokenizer,
  159. unet: UNet2DConditionModel,
  160. brushnet: Union[
  161. BrushNetModel, List[BrushNetModel], Tuple[BrushNetModel]
  162. ], # MultiBrushNetModel],
  163. scheduler: KarrasDiffusionSchedulers,
  164. force_zeros_for_empty_prompt: bool = True,
  165. add_watermarker: Optional[bool] = None,
  166. feature_extractor: CLIPImageProcessor = None,
  167. image_encoder: CLIPVisionModelWithProjection = None,
  168. ):
  169. super().__init__()
  170. # if isinstance(brushnet, (list, tuple)):
  171. # brushnet = MultiBrushNetModel(brushnet)
  172. self.register_modules(
  173. vae=vae,
  174. text_encoder=text_encoder,
  175. text_encoder_2=text_encoder_2,
  176. tokenizer=tokenizer,
  177. tokenizer_2=tokenizer_2,
  178. unet=unet,
  179. brushnet=brushnet,
  180. scheduler=scheduler,
  181. feature_extractor=feature_extractor,
  182. image_encoder=image_encoder,
  183. )
  184. self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
  185. self.image_processor = VaeImageProcessor(
  186. vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True
  187. )
  188. # self.control_image_processor = VaeImageProcessor(
  189. # vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
  190. # )
  191. add_watermarker = (
  192. add_watermarker
  193. if add_watermarker is not None
  194. else is_invisible_watermark_available()
  195. )
  196. if add_watermarker:
  197. self.watermark = StableDiffusionXLWatermarker()
  198. else:
  199. self.watermark = None
  200. self.register_to_config(
  201. force_zeros_for_empty_prompt=force_zeros_for_empty_prompt
  202. )
  203. # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
  204. def encode_prompt(
  205. self,
  206. prompt: str,
  207. prompt_2: Optional[str] = None,
  208. device: Optional[torch.device] = None,
  209. num_images_per_prompt: int = 1,
  210. do_classifier_free_guidance: bool = True,
  211. negative_prompt: Optional[str] = None,
  212. negative_prompt_2: Optional[str] = None,
  213. prompt_embeds: Optional[torch.FloatTensor] = None,
  214. negative_prompt_embeds: Optional[torch.FloatTensor] = None,
  215. pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
  216. negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
  217. lora_scale: Optional[float] = None,
  218. clip_skip: Optional[int] = None,
  219. ):
  220. r"""
  221. Encodes the prompt into text encoder hidden states.
  222. Args:
  223. prompt (`str` or `List[str]`, *optional*):
  224. prompt to be encoded
  225. prompt_2 (`str` or `List[str]`, *optional*):
  226. The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
  227. used in both text-encoders
  228. device: (`torch.device`):
  229. torch device
  230. num_images_per_prompt (`int`):
  231. number of images that should be generated per prompt
  232. do_classifier_free_guidance (`bool`):
  233. whether to use classifier free guidance or not
  234. negative_prompt (`str` or `List[str]`, *optional*):
  235. The prompt or prompts not to guide the image generation. If not defined, one has to pass
  236. `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
  237. less than `1`).
  238. negative_prompt_2 (`str` or `List[str]`, *optional*):
  239. The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
  240. `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
  241. prompt_embeds (`torch.FloatTensor`, *optional*):
  242. Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
  243. provided, text embeddings will be generated from `prompt` input argument.
  244. negative_prompt_embeds (`torch.FloatTensor`, *optional*):
  245. Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
  246. weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
  247. argument.
  248. pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
  249. Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
  250. If not provided, pooled text embeddings will be generated from `prompt` input argument.
  251. negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
  252. Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
  253. weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
  254. input argument.
  255. lora_scale (`float`, *optional*):
  256. A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
  257. clip_skip (`int`, *optional*):
  258. Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
  259. the output of the pre-final layer will be used for computing the prompt embeddings.
  260. """
  261. device = device or self._execution_device
  262. # set lora scale so that monkey patched LoRA
  263. # function of text encoder can correctly access it
  264. if lora_scale is not None and isinstance(
  265. self, StableDiffusionXLLoraLoaderMixin
  266. ):
  267. self._lora_scale = lora_scale
  268. # dynamically adjust the LoRA scale
  269. if self.text_encoder is not None:
  270. if not USE_PEFT_BACKEND:
  271. adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
  272. else:
  273. scale_lora_layers(self.text_encoder, lora_scale)
  274. if self.text_encoder_2 is not None:
  275. if not USE_PEFT_BACKEND:
  276. adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
  277. else:
  278. scale_lora_layers(self.text_encoder_2, lora_scale)
  279. prompt = [prompt] if isinstance(prompt, str) else prompt
  280. if prompt is not None:
  281. batch_size = len(prompt)
  282. else:
  283. batch_size = prompt_embeds.shape[0]
  284. # Define tokenizers and text encoders
  285. tokenizers = (
  286. [self.tokenizer, self.tokenizer_2]
  287. if self.tokenizer is not None
  288. else [self.tokenizer_2]
  289. )
  290. text_encoders = (
  291. [self.text_encoder, self.text_encoder_2]
  292. if self.text_encoder is not None
  293. else [self.text_encoder_2]
  294. )
  295. if prompt_embeds is None:
  296. prompt_2 = prompt_2 or prompt
  297. prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
  298. # textual inversion: process multi-vector tokens if necessary
  299. prompt_embeds_list = []
  300. prompts = [prompt, prompt_2]
  301. for prompt, tokenizer, text_encoder in zip(
  302. prompts, tokenizers, text_encoders
  303. ):
  304. if isinstance(self, TextualInversionLoaderMixin):
  305. prompt = self.maybe_convert_prompt(prompt, tokenizer)
  306. text_inputs = tokenizer(
  307. prompt,
  308. padding="max_length",
  309. max_length=tokenizer.model_max_length,
  310. truncation=True,
  311. return_tensors="pt",
  312. )
  313. text_input_ids = text_inputs.input_ids
  314. untruncated_ids = tokenizer(
  315. prompt, padding="longest", return_tensors="pt"
  316. ).input_ids
  317. if untruncated_ids.shape[-1] >= text_input_ids.shape[
  318. -1
  319. ] and not torch.equal(text_input_ids, untruncated_ids):
  320. removed_text = tokenizer.batch_decode(
  321. untruncated_ids[:, tokenizer.model_max_length - 1 : -1]
  322. )
  323. logger.warning(
  324. "The following part of your input was truncated because CLIP can only handle sequences up to"
  325. f" {tokenizer.model_max_length} tokens: {removed_text}"
  326. )
  327. prompt_embeds = text_encoder(
  328. text_input_ids.to(device), output_hidden_states=True
  329. )
  330. # We are only ALWAYS interested in the pooled output of the final text encoder
  331. pooled_prompt_embeds = prompt_embeds[0]
  332. if clip_skip is None:
  333. prompt_embeds = prompt_embeds.hidden_states[-2]
  334. else:
  335. # "2" because SDXL always indexes from the penultimate layer.
  336. prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
  337. prompt_embeds_list.append(prompt_embeds)
  338. prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
  339. # get unconditional embeddings for classifier free guidance
  340. zero_out_negative_prompt = (
  341. negative_prompt is None and self.config.force_zeros_for_empty_prompt
  342. )
  343. if (
  344. do_classifier_free_guidance
  345. and negative_prompt_embeds is None
  346. and zero_out_negative_prompt
  347. ):
  348. negative_prompt_embeds = torch.zeros_like(prompt_embeds)
  349. negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
  350. elif do_classifier_free_guidance and negative_prompt_embeds is None:
  351. negative_prompt = negative_prompt or ""
  352. negative_prompt_2 = negative_prompt_2 or negative_prompt
  353. # normalize str to list
  354. negative_prompt = (
  355. batch_size * [negative_prompt]
  356. if isinstance(negative_prompt, str)
  357. else negative_prompt
  358. )
  359. negative_prompt_2 = (
  360. batch_size * [negative_prompt_2]
  361. if isinstance(negative_prompt_2, str)
  362. else negative_prompt_2
  363. )
  364. uncond_tokens: List[str]
  365. if prompt is not None and type(prompt) is not type(negative_prompt):
  366. raise TypeError(
  367. f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
  368. f" {type(prompt)}."
  369. )
  370. elif batch_size != len(negative_prompt):
  371. raise ValueError(
  372. f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
  373. f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
  374. " the batch size of `prompt`."
  375. )
  376. else:
  377. uncond_tokens = [negative_prompt, negative_prompt_2]
  378. negative_prompt_embeds_list = []
  379. for negative_prompt, tokenizer, text_encoder in zip(
  380. uncond_tokens, tokenizers, text_encoders
  381. ):
  382. if isinstance(self, TextualInversionLoaderMixin):
  383. negative_prompt = self.maybe_convert_prompt(
  384. negative_prompt, tokenizer
  385. )
  386. max_length = prompt_embeds.shape[1]
  387. uncond_input = tokenizer(
  388. negative_prompt,
  389. padding="max_length",
  390. max_length=max_length,
  391. truncation=True,
  392. return_tensors="pt",
  393. )
  394. negative_prompt_embeds = text_encoder(
  395. uncond_input.input_ids.to(device),
  396. output_hidden_states=True,
  397. )
  398. # We are only ALWAYS interested in the pooled output of the final text encoder
  399. negative_pooled_prompt_embeds = negative_prompt_embeds[0]
  400. negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
  401. negative_prompt_embeds_list.append(negative_prompt_embeds)
  402. negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
  403. if self.text_encoder_2 is not None:
  404. prompt_embeds = prompt_embeds.to(
  405. dtype=self.text_encoder_2.dtype, device=device
  406. )
  407. else:
  408. prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
  409. bs_embed, seq_len, _ = prompt_embeds.shape
  410. # duplicate text embeddings for each generation per prompt, using mps friendly method
  411. prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
  412. prompt_embeds = prompt_embeds.view(
  413. bs_embed * num_images_per_prompt, seq_len, -1
  414. )
  415. if do_classifier_free_guidance:
  416. # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
  417. seq_len = negative_prompt_embeds.shape[1]
  418. if self.text_encoder_2 is not None:
  419. negative_prompt_embeds = negative_prompt_embeds.to(
  420. dtype=self.text_encoder_2.dtype, device=device
  421. )
  422. else:
  423. negative_prompt_embeds = negative_prompt_embeds.to(
  424. dtype=self.unet.dtype, device=device
  425. )
  426. negative_prompt_embeds = negative_prompt_embeds.repeat(
  427. 1, num_images_per_prompt, 1
  428. )
  429. negative_prompt_embeds = negative_prompt_embeds.view(
  430. batch_size * num_images_per_prompt, seq_len, -1
  431. )
  432. pooled_prompt_embeds = pooled_prompt_embeds.repeat(
  433. 1, num_images_per_prompt
  434. ).view(bs_embed * num_images_per_prompt, -1)
  435. if do_classifier_free_guidance:
  436. negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(
  437. 1, num_images_per_prompt
  438. ).view(bs_embed * num_images_per_prompt, -1)
  439. if self.text_encoder is not None:
  440. if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
  441. # Retrieve the original scale by scaling back the LoRA layers
  442. unscale_lora_layers(self.text_encoder, lora_scale)
  443. if self.text_encoder_2 is not None:
  444. if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
  445. # Retrieve the original scale by scaling back the LoRA layers
  446. unscale_lora_layers(self.text_encoder_2, lora_scale)
  447. return (
  448. prompt_embeds,
  449. negative_prompt_embeds,
  450. pooled_prompt_embeds,
  451. negative_pooled_prompt_embeds,
  452. )
  453. # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
  454. def encode_image(
  455. self, image, device, num_images_per_prompt, output_hidden_states=None
  456. ):
  457. dtype = next(self.image_encoder.parameters()).dtype
  458. if not isinstance(image, torch.Tensor):
  459. image = self.feature_extractor(image, return_tensors="pt").pixel_values
  460. image = image.to(device=device, dtype=dtype)
  461. if output_hidden_states:
  462. image_enc_hidden_states = self.image_encoder(
  463. image, output_hidden_states=True
  464. ).hidden_states[-2]
  465. image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(
  466. num_images_per_prompt, dim=0
  467. )
  468. uncond_image_enc_hidden_states = self.image_encoder(
  469. torch.zeros_like(image), output_hidden_states=True
  470. ).hidden_states[-2]
  471. uncond_image_enc_hidden_states = (
  472. uncond_image_enc_hidden_states.repeat_interleave(
  473. num_images_per_prompt, dim=0
  474. )
  475. )
  476. return image_enc_hidden_states, uncond_image_enc_hidden_states
  477. else:
  478. image_embeds = self.image_encoder(image).image_embeds
  479. image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
  480. uncond_image_embeds = torch.zeros_like(image_embeds)
  481. return image_embeds, uncond_image_embeds
  482. # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
  483. def prepare_ip_adapter_image_embeds(
  484. self,
  485. ip_adapter_image,
  486. ip_adapter_image_embeds,
  487. device,
  488. num_images_per_prompt,
  489. do_classifier_free_guidance,
  490. ):
  491. if ip_adapter_image_embeds is None:
  492. if not isinstance(ip_adapter_image, list):
  493. ip_adapter_image = [ip_adapter_image]
  494. if len(ip_adapter_image) != len(
  495. self.unet.encoder_hid_proj.image_projection_layers
  496. ):
  497. raise ValueError(
  498. f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
  499. )
  500. image_embeds = []
  501. for single_ip_adapter_image, image_proj_layer in zip(
  502. ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
  503. ):
  504. output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
  505. single_image_embeds, single_negative_image_embeds = self.encode_image(
  506. single_ip_adapter_image, device, 1, output_hidden_state
  507. )
  508. single_image_embeds = torch.stack(
  509. [single_image_embeds] * num_images_per_prompt, dim=0
  510. )
  511. single_negative_image_embeds = torch.stack(
  512. [single_negative_image_embeds] * num_images_per_prompt, dim=0
  513. )
  514. if do_classifier_free_guidance:
  515. single_image_embeds = torch.cat(
  516. [single_negative_image_embeds, single_image_embeds]
  517. )
  518. single_image_embeds = single_image_embeds.to(device)
  519. image_embeds.append(single_image_embeds)
  520. else:
  521. repeat_dims = [1]
  522. image_embeds = []
  523. for single_image_embeds in ip_adapter_image_embeds:
  524. if do_classifier_free_guidance:
  525. (
  526. single_negative_image_embeds,
  527. single_image_embeds,
  528. ) = single_image_embeds.chunk(2)
  529. single_image_embeds = single_image_embeds.repeat(
  530. num_images_per_prompt,
  531. *(repeat_dims * len(single_image_embeds.shape[1:])),
  532. )
  533. single_negative_image_embeds = single_negative_image_embeds.repeat(
  534. num_images_per_prompt,
  535. *(repeat_dims * len(single_negative_image_embeds.shape[1:])),
  536. )
  537. single_image_embeds = torch.cat(
  538. [single_negative_image_embeds, single_image_embeds]
  539. )
  540. else:
  541. single_image_embeds = single_image_embeds.repeat(
  542. num_images_per_prompt,
  543. *(repeat_dims * len(single_image_embeds.shape[1:])),
  544. )
  545. image_embeds.append(single_image_embeds)
  546. return image_embeds
  547. # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
  548. def prepare_extra_step_kwargs(self, generator, eta):
  549. # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
  550. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
  551. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
  552. # and should be between [0, 1]
  553. accepts_eta = "eta" in set(
  554. inspect.signature(self.scheduler.step).parameters.keys()
  555. )
  556. extra_step_kwargs = {}
  557. if accepts_eta:
  558. extra_step_kwargs["eta"] = eta
  559. # check if the scheduler accepts generator
  560. accepts_generator = "generator" in set(
  561. inspect.signature(self.scheduler.step).parameters.keys()
  562. )
  563. if accepts_generator:
  564. extra_step_kwargs["generator"] = generator
  565. return extra_step_kwargs
  566. def check_inputs(
  567. self,
  568. prompt,
  569. prompt_2,
  570. image,
  571. mask,
  572. callback_steps,
  573. negative_prompt=None,
  574. negative_prompt_2=None,
  575. prompt_embeds=None,
  576. negative_prompt_embeds=None,
  577. pooled_prompt_embeds=None,
  578. ip_adapter_image=None,
  579. ip_adapter_image_embeds=None,
  580. negative_pooled_prompt_embeds=None,
  581. brushnet_conditioning_scale=1.0,
  582. control_guidance_start=0.0,
  583. control_guidance_end=1.0,
  584. callback_on_step_end_tensor_inputs=None,
  585. ):
  586. if callback_steps is not None and (
  587. not isinstance(callback_steps, int) or callback_steps <= 0
  588. ):
  589. raise ValueError(
  590. f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
  591. f" {type(callback_steps)}."
  592. )
  593. if callback_on_step_end_tensor_inputs is not None and not all(
  594. k in self._callback_tensor_inputs
  595. for k in callback_on_step_end_tensor_inputs
  596. ):
  597. raise ValueError(
  598. f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
  599. )
  600. if prompt is not None and prompt_embeds is not None:
  601. raise ValueError(
  602. f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
  603. " only forward one of the two."
  604. )
  605. elif prompt_2 is not None and prompt_embeds is not None:
  606. raise ValueError(
  607. f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
  608. " only forward one of the two."
  609. )
  610. elif prompt is None and prompt_embeds is None:
  611. raise ValueError(
  612. "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
  613. )
  614. elif prompt is not None and (
  615. not isinstance(prompt, str) and not isinstance(prompt, list)
  616. ):
  617. raise ValueError(
  618. f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
  619. )
  620. elif prompt_2 is not None and (
  621. not isinstance(prompt_2, str) and not isinstance(prompt_2, list)
  622. ):
  623. raise ValueError(
  624. f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}"
  625. )
  626. if negative_prompt is not None and negative_prompt_embeds is not None:
  627. raise ValueError(
  628. f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
  629. f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
  630. )
  631. elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
  632. raise ValueError(
  633. f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
  634. f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
  635. )
  636. if prompt_embeds is not None and negative_prompt_embeds is not None:
  637. if prompt_embeds.shape != negative_prompt_embeds.shape:
  638. raise ValueError(
  639. "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
  640. f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
  641. f" {negative_prompt_embeds.shape}."
  642. )
  643. if prompt_embeds is not None and pooled_prompt_embeds is None:
  644. raise ValueError(
  645. "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`."
  646. )
  647. if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
  648. raise ValueError(
  649. "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`."
  650. )
  651. # `prompt` needs more sophisticated handling when there are multiple
  652. # conditionings.
  653. # if isinstance(self.brushnet, MultiBrushNetModel):
  654. # if isinstance(prompt, list):
  655. # logger.warning(
  656. # f"You have {len(self.brushnet.nets)} BrushNets and you have passed {len(prompt)}"
  657. # " prompts. The conditionings will be fixed across the prompts."
  658. # )
  659. # Check `image`
  660. is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
  661. self.brushnet, torch._dynamo.eval_frame.OptimizedModule
  662. )
  663. if (
  664. isinstance(self.brushnet, BrushNetModel)
  665. or is_compiled
  666. and isinstance(self.brushnet._orig_mod, BrushNetModel)
  667. ):
  668. self.check_image(image, mask, prompt, prompt_embeds)
  669. # elif (
  670. # isinstance(self.brushnet, MultiBrushNetModel)
  671. # or is_compiled
  672. # and isinstance(self.brushnet._orig_mod, MultiBrushNetModel)
  673. # ):
  674. # if not isinstance(image, list):
  675. # raise TypeError("For multiple brushnets: `image` must be type `list`")
  676. # # When `image` is a nested list:
  677. # # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
  678. # elif any(isinstance(i, list) for i in image):
  679. # raise ValueError("A single batch of multiple conditionings are supported at the moment.")
  680. # elif len(image) != len(self.brushnet.nets):
  681. # raise ValueError(
  682. # f"For multiple brushnets: `image` must have the same length as the number of brushnets, but got {len(image)} images and {len(self.brushnet.nets)} BrushNets."
  683. # )
  684. # for image_ in image:
  685. # self.check_image(image_, prompt, prompt_embeds)
  686. else:
  687. assert False
  688. # Check `brushnet_conditioning_scale`
  689. if (
  690. isinstance(self.brushnet, BrushNetModel)
  691. or is_compiled
  692. and isinstance(self.brushnet._orig_mod, BrushNetModel)
  693. ):
  694. if not isinstance(brushnet_conditioning_scale, float):
  695. raise TypeError(
  696. "For single brushnet: `brushnet_conditioning_scale` must be type `float`."
  697. )
  698. # elif (
  699. # isinstance(self.brushnet, MultiBrushNetModel)
  700. # or is_compiled
  701. # and isinstance(self.brushnet._orig_mod, MultiBrushNetModel)
  702. # ):
  703. # if isinstance(brushnet_conditioning_scale, list):
  704. # if any(isinstance(i, list) for i in brushnet_conditioning_scale):
  705. # raise ValueError("A single batch of multiple conditionings are supported at the moment.")
  706. # elif isinstance(brushnet_conditioning_scale, list) and len(brushnet_conditioning_scale) != len(
  707. # self.brushnet.nets
  708. # ):
  709. # raise ValueError(
  710. # "For multiple brushnets: When `brushnet_conditioning_scale` is specified as `list`, it must have"
  711. # " the same length as the number of brushnets"
  712. # )
  713. else:
  714. assert False
  715. if not isinstance(control_guidance_start, (tuple, list)):
  716. control_guidance_start = [control_guidance_start]
  717. if not isinstance(control_guidance_end, (tuple, list)):
  718. control_guidance_end = [control_guidance_end]
  719. if len(control_guidance_start) != len(control_guidance_end):
  720. raise ValueError(
  721. f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
  722. )
  723. # if isinstance(self.brushnet, MultiBrushNetModel):
  724. # if len(control_guidance_start) != len(self.brushnet.nets):
  725. # raise ValueError(
  726. # f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.brushnet.nets)} brushnets available. Make sure to provide {len(self.brushnet.nets)}."
  727. # )
  728. for start, end in zip(control_guidance_start, control_guidance_end):
  729. if start >= end:
  730. raise ValueError(
  731. f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
  732. )
  733. if start < 0.0:
  734. raise ValueError(
  735. f"control guidance start: {start} can't be smaller than 0."
  736. )
  737. if end > 1.0:
  738. raise ValueError(
  739. f"control guidance end: {end} can't be larger than 1.0."
  740. )
  741. if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
  742. raise ValueError(
  743. "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
  744. )
  745. if ip_adapter_image_embeds is not None:
  746. if not isinstance(ip_adapter_image_embeds, list):
  747. raise ValueError(
  748. f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
  749. )
  750. elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
  751. raise ValueError(
  752. f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
  753. )
  754. # Copied from diffusers.pipelines.brushnet.pipeline_brushnet.StableDiffusionBrushNetPipeline.check_image
  755. def check_image(self, image, mask, prompt, prompt_embeds):
  756. image_is_pil = isinstance(image, PIL.Image.Image)
  757. image_is_tensor = isinstance(image, torch.Tensor)
  758. image_is_np = isinstance(image, np.ndarray)
  759. image_is_pil_list = isinstance(image, list) and isinstance(
  760. image[0], PIL.Image.Image
  761. )
  762. image_is_tensor_list = isinstance(image, list) and isinstance(
  763. image[0], torch.Tensor
  764. )
  765. image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
  766. if (
  767. not image_is_pil
  768. and not image_is_tensor
  769. and not image_is_np
  770. and not image_is_pil_list
  771. and not image_is_tensor_list
  772. and not image_is_np_list
  773. ):
  774. raise TypeError(
  775. f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
  776. )
  777. mask_is_pil = isinstance(mask, PIL.Image.Image)
  778. mask_is_tensor = isinstance(mask, torch.Tensor)
  779. mask_is_np = isinstance(mask, np.ndarray)
  780. mask_is_pil_list = isinstance(mask, list) and isinstance(
  781. mask[0], PIL.Image.Image
  782. )
  783. mask_is_tensor_list = isinstance(mask, list) and isinstance(
  784. mask[0], torch.Tensor
  785. )
  786. mask_is_np_list = isinstance(mask, list) and isinstance(mask[0], np.ndarray)
  787. if (
  788. not mask_is_pil
  789. and not mask_is_tensor
  790. and not mask_is_np
  791. and not mask_is_pil_list
  792. and not mask_is_tensor_list
  793. and not mask_is_np_list
  794. ):
  795. raise TypeError(
  796. f"mask must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(mask)}"
  797. )
  798. if image_is_pil:
  799. image_batch_size = 1
  800. else:
  801. image_batch_size = len(image)
  802. if prompt is not None and isinstance(prompt, str):
  803. prompt_batch_size = 1
  804. elif prompt is not None and isinstance(prompt, list):
  805. prompt_batch_size = len(prompt)
  806. elif prompt_embeds is not None:
  807. prompt_batch_size = prompt_embeds.shape[0]
  808. if image_batch_size != 1 and image_batch_size != prompt_batch_size:
  809. raise ValueError(
  810. f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
  811. )
  812. # Copied from diffusers.pipelines.brushnet.pipeline_brushnet.StableDiffusionBrushNetPipeline.prepare_image
  813. def prepare_image(
  814. self,
  815. image,
  816. width,
  817. height,
  818. batch_size,
  819. num_images_per_prompt,
  820. device,
  821. dtype,
  822. do_classifier_free_guidance=False,
  823. guess_mode=False,
  824. ):
  825. image = self.image_processor.preprocess(image, height=height, width=width).to(
  826. dtype=torch.float32
  827. )
  828. image_batch_size = image.shape[0]
  829. if image_batch_size == 1:
  830. repeat_by = batch_size
  831. else:
  832. # image batch size is the same as prompt batch size
  833. repeat_by = num_images_per_prompt
  834. image = image.repeat_interleave(repeat_by, dim=0)
  835. image = image.to(device=device, dtype=dtype)
  836. if do_classifier_free_guidance and not guess_mode:
  837. image = torch.cat([image] * 2)
  838. return image
  839. # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
  840. def prepare_latents(
  841. self,
  842. batch_size,
  843. num_channels_latents,
  844. height,
  845. width,
  846. dtype,
  847. device,
  848. generator,
  849. latents=None,
  850. ):
  851. shape = (
  852. batch_size,
  853. num_channels_latents,
  854. height // self.vae_scale_factor,
  855. width // self.vae_scale_factor,
  856. )
  857. if isinstance(generator, list) and len(generator) != batch_size:
  858. raise ValueError(
  859. f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
  860. f" size of {batch_size}. Make sure the batch size matches the length of the generators."
  861. )
  862. if latents is None:
  863. noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
  864. else:
  865. noise = latents.to(device)
  866. # scale the initial noise by the standard deviation required by the scheduler
  867. latents = noise * self.scheduler.init_noise_sigma
  868. return latents, noise
  869. # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
  870. def _get_add_time_ids(
  871. self,
  872. original_size,
  873. crops_coords_top_left,
  874. target_size,
  875. dtype,
  876. text_encoder_projection_dim=None,
  877. ):
  878. add_time_ids = list(original_size + crops_coords_top_left + target_size)
  879. passed_add_embed_dim = (
  880. self.unet.config.addition_time_embed_dim * len(add_time_ids)
  881. + text_encoder_projection_dim
  882. )
  883. expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
  884. if expected_add_embed_dim != passed_add_embed_dim:
  885. raise ValueError(
  886. 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`."
  887. )
  888. add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
  889. return add_time_ids
  890. # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
  891. def upcast_vae(self):
  892. dtype = self.vae.dtype
  893. self.vae.to(dtype=torch.float32)
  894. use_torch_2_0_or_xformers = isinstance(
  895. self.vae.decoder.mid_block.attentions[0].processor,
  896. (
  897. AttnProcessor2_0,
  898. XFormersAttnProcessor,
  899. LoRAXFormersAttnProcessor,
  900. LoRAAttnProcessor2_0,
  901. ),
  902. )
  903. # if xformers or torch_2_0 is used attention block does not need
  904. # to be in float32 which can save lots of memory
  905. if use_torch_2_0_or_xformers:
  906. self.vae.post_quant_conv.to(dtype)
  907. self.vae.decoder.conv_in.to(dtype)
  908. self.vae.decoder.mid_block.to(dtype)
  909. # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
  910. def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
  911. """
  912. See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
  913. Args:
  914. timesteps (`torch.Tensor`):
  915. generate embedding vectors at these timesteps
  916. embedding_dim (`int`, *optional*, defaults to 512):
  917. dimension of the embeddings to generate
  918. dtype:
  919. data type of the generated embeddings
  920. Returns:
  921. `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
  922. """
  923. assert len(w.shape) == 1
  924. w = w * 1000.0
  925. half_dim = embedding_dim // 2
  926. emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
  927. emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
  928. emb = w.to(dtype)[:, None] * emb[None, :]
  929. emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
  930. if embedding_dim % 2 == 1: # zero pad
  931. emb = torch.nn.functional.pad(emb, (0, 1))
  932. assert emb.shape == (w.shape[0], embedding_dim)
  933. return emb
  934. @property
  935. def guidance_scale(self):
  936. return self._guidance_scale
  937. @property
  938. def clip_skip(self):
  939. return self._clip_skip
  940. # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
  941. # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
  942. # corresponds to doing no classifier free guidance.
  943. @property
  944. def do_classifier_free_guidance(self):
  945. return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
  946. @property
  947. def cross_attention_kwargs(self):
  948. return self._cross_attention_kwargs
  949. @property
  950. def denoising_end(self):
  951. return self._denoising_end
  952. @property
  953. def num_timesteps(self):
  954. return self._num_timesteps
  955. @torch.no_grad()
  956. @replace_example_docstring(EXAMPLE_DOC_STRING)
  957. def __call__(
  958. self,
  959. prompt: Union[str, List[str]] = None,
  960. prompt_2: Optional[Union[str, List[str]]] = None,
  961. image: PipelineImageInput = None,
  962. mask: PipelineImageInput = None,
  963. height: Optional[int] = None,
  964. width: Optional[int] = None,
  965. num_inference_steps: int = 50,
  966. denoising_end: Optional[float] = None,
  967. guidance_scale: float = 5.0,
  968. negative_prompt: Optional[Union[str, List[str]]] = None,
  969. negative_prompt_2: Optional[Union[str, List[str]]] = None,
  970. num_images_per_prompt: Optional[int] = 1,
  971. eta: float = 0.0,
  972. generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
  973. latents: Optional[torch.FloatTensor] = None,
  974. prompt_embeds: Optional[torch.FloatTensor] = None,
  975. negative_prompt_embeds: Optional[torch.FloatTensor] = None,
  976. pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
  977. negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
  978. ip_adapter_image: Optional[PipelineImageInput] = None,
  979. ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
  980. output_type: Optional[str] = "pil",
  981. return_dict: bool = True,
  982. cross_attention_kwargs: Optional[Dict[str, Any]] = None,
  983. brushnet_conditioning_scale: Union[float, List[float]] = 1.0,
  984. guess_mode: bool = False,
  985. control_guidance_start: Union[float, List[float]] = 0.0,
  986. control_guidance_end: Union[float, List[float]] = 1.0,
  987. original_size: Tuple[int, int] = None,
  988. crops_coords_top_left: Tuple[int, int] = (0, 0),
  989. target_size: Tuple[int, int] = None,
  990. negative_original_size: Optional[Tuple[int, int]] = None,
  991. negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
  992. negative_target_size: Optional[Tuple[int, int]] = None,
  993. clip_skip: Optional[int] = None,
  994. callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
  995. callback_on_step_end_tensor_inputs: List[str] = ["latents"],
  996. **kwargs,
  997. ):
  998. r"""
  999. The call function to the pipeline for generation.
  1000. Args:
  1001. prompt (`str` or `List[str]`, *optional*):
  1002. The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
  1003. prompt_2 (`str` or `List[str]`, *optional*):
  1004. The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
  1005. used in both text-encoders.
  1006. image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
  1007. `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
  1008. The BrushNet input condition to provide guidance to the `unet` for generation. If the type is
  1009. specified as `torch.FloatTensor`, it is passed to BrushNet as is. `PIL.Image.Image` can also be
  1010. accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
  1011. and/or width are passed, `image` is resized accordingly. If multiple BrushNets are specified in
  1012. `init`, images must be passed as a list such that each element of the list can be correctly batched for
  1013. input to a single BrushNet.
  1014. height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
  1015. The height in pixels of the generated image. Anything below 512 pixels won't work well for
  1016. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
  1017. and checkpoints that are not specifically fine-tuned on low resolutions.
  1018. width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
  1019. The width in pixels of the generated image. Anything below 512 pixels won't work well for
  1020. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
  1021. and checkpoints that are not specifically fine-tuned on low resolutions.
  1022. num_inference_steps (`int`, *optional*, defaults to 50):
  1023. The number of denoising steps. More denoising steps usually lead to a higher quality image at the
  1024. expense of slower inference.
  1025. denoising_end (`float`, *optional*):
  1026. When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
  1027. completed before it is intentionally prematurely terminated. As a result, the returned sample will
  1028. still retain a substantial amount of noise as determined by the discrete timesteps selected by the
  1029. scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
  1030. "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
  1031. Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
  1032. guidance_scale (`float`, *optional*, defaults to 5.0):
  1033. A higher guidance scale value encourages the model to generate images closely linked to the text
  1034. `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
  1035. negative_prompt (`str` or `List[str]`, *optional*):
  1036. The prompt or prompts to guide what to not include in image generation. If not defined, you need to
  1037. pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
  1038. negative_prompt_2 (`str` or `List[str]`, *optional*):
  1039. The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
  1040. and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
  1041. num_images_per_prompt (`int`, *optional*, defaults to 1):
  1042. The number of images to generate per prompt.
  1043. eta (`float`, *optional*, defaults to 0.0):
  1044. Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
  1045. to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
  1046. generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
  1047. A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
  1048. generation deterministic.
  1049. latents (`torch.FloatTensor`, *optional*):
  1050. Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
  1051. generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
  1052. tensor is generated by sampling using the supplied random `generator`.
  1053. prompt_embeds (`torch.FloatTensor`, *optional*):
  1054. Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
  1055. provided, text embeddings are generated from the `prompt` input argument.
  1056. negative_prompt_embeds (`torch.FloatTensor`, *optional*):
  1057. Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
  1058. not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
  1059. pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
  1060. Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
  1061. not provided, pooled text embeddings are generated from `prompt` input argument.
  1062. negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
  1063. Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
  1064. weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
  1065. argument.
  1066. ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
  1067. ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
  1068. Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
  1069. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
  1070. if `do_classifier_free_guidance` is set to `True`.
  1071. If not provided, embeddings are computed from the `ip_adapter_image` input argument.
  1072. output_type (`str`, *optional*, defaults to `"pil"`):
  1073. The output format of the generated image. Choose between `PIL.Image` or `np.array`.
  1074. return_dict (`bool`, *optional*, defaults to `True`):
  1075. Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
  1076. plain tuple.
  1077. cross_attention_kwargs (`dict`, *optional*):
  1078. A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
  1079. [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
  1080. brushnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
  1081. The outputs of the BrushNet are multiplied by `brushnet_conditioning_scale` before they are added
  1082. to the residual in the original `unet`. If multiple BrushNets are specified in `init`, you can set
  1083. the corresponding scale as a list.
  1084. guess_mode (`bool`, *optional*, defaults to `False`):
  1085. The BrushNet encoder tries to recognize the content of the input image even if you remove all
  1086. prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
  1087. control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
  1088. The percentage of total steps at which the BrushNet starts applying.
  1089. control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
  1090. The percentage of total steps at which the BrushNet stops applying.
  1091. original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
  1092. If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
  1093. `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
  1094. explained in section 2.2 of
  1095. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
  1096. crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
  1097. `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
  1098. `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
  1099. `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
  1100. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
  1101. target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
  1102. For most cases, `target_size` should be set to the desired height and width of the generated image. If
  1103. not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
  1104. section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
  1105. negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
  1106. To negatively condition the generation process based on a specific image resolution. Part of SDXL's
  1107. micro-conditioning as explained in section 2.2 of
  1108. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
  1109. information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
  1110. negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
  1111. To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
  1112. micro-conditioning as explained in section 2.2 of
  1113. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
  1114. information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
  1115. negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
  1116. To negatively condition the generation process based on a target image resolution. It should be as same
  1117. as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
  1118. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
  1119. information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
  1120. clip_skip (`int`, *optional*):
  1121. Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
  1122. the output of the pre-final layer will be used for computing the prompt embeddings.
  1123. callback_on_step_end (`Callable`, *optional*):
  1124. A function that calls at the end of each denoising steps during the inference. The function is called
  1125. with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
  1126. callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
  1127. `callback_on_step_end_tensor_inputs`.
  1128. callback_on_step_end_tensor_inputs (`List`, *optional*):
  1129. The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
  1130. will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
  1131. `._callback_tensor_inputs` attribute of your pipeine class.
  1132. Examples:
  1133. Returns:
  1134. [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
  1135. If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
  1136. otherwise a `tuple` is returned containing the output images.
  1137. """
  1138. callback = kwargs.pop("callback", None)
  1139. callback_steps = kwargs.pop("callback_steps", None)
  1140. if callback is not None:
  1141. deprecate(
  1142. "callback",
  1143. "1.0.0",
  1144. "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
  1145. )
  1146. if callback_steps is not None:
  1147. deprecate(
  1148. "callback_steps",
  1149. "1.0.0",
  1150. "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
  1151. )
  1152. brushnet = (
  1153. self.brushnet._orig_mod
  1154. if is_compiled_module(self.brushnet)
  1155. else self.brushnet
  1156. )
  1157. # align format for control guidance
  1158. if not isinstance(control_guidance_start, list) and isinstance(
  1159. control_guidance_end, list
  1160. ):
  1161. control_guidance_start = len(control_guidance_end) * [
  1162. control_guidance_start
  1163. ]
  1164. elif not isinstance(control_guidance_end, list) and isinstance(
  1165. control_guidance_start, list
  1166. ):
  1167. control_guidance_end = len(control_guidance_start) * [control_guidance_end]
  1168. elif not isinstance(control_guidance_start, list) and not isinstance(
  1169. control_guidance_end, list
  1170. ):
  1171. # mult = len(brushnet.nets) if isinstance(brushnet, MultiBrushNetModel) else 1
  1172. mult = 1
  1173. control_guidance_start, control_guidance_end = (
  1174. mult * [control_guidance_start],
  1175. mult * [control_guidance_end],
  1176. )
  1177. # 1. Check inputs. Raise error if not correct
  1178. self.check_inputs(
  1179. prompt,
  1180. prompt_2,
  1181. image,
  1182. mask,
  1183. callback_steps,
  1184. negative_prompt,
  1185. negative_prompt_2,
  1186. prompt_embeds,
  1187. negative_prompt_embeds,
  1188. pooled_prompt_embeds,
  1189. ip_adapter_image,
  1190. ip_adapter_image_embeds,
  1191. negative_pooled_prompt_embeds,
  1192. brushnet_conditioning_scale,
  1193. control_guidance_start,
  1194. control_guidance_end,
  1195. callback_on_step_end_tensor_inputs,
  1196. )
  1197. self._guidance_scale = guidance_scale
  1198. self._clip_skip = clip_skip
  1199. self._cross_attention_kwargs = cross_attention_kwargs
  1200. self._denoising_end = denoising_end
  1201. # 2. Define call parameters
  1202. if prompt is not None and isinstance(prompt, str):
  1203. batch_size = 1
  1204. elif prompt is not None and isinstance(prompt, list):
  1205. batch_size = len(prompt)
  1206. else:
  1207. batch_size = prompt_embeds.shape[0]
  1208. device = self._execution_device
  1209. # if isinstance(brushnet, MultiBrushNetModel) and isinstance(brushnet_conditioning_scale, float):
  1210. # brushnet_conditioning_scale = [brushnet_conditioning_scale] * len(brushnet.nets)
  1211. global_pool_conditions = (
  1212. brushnet.config.global_pool_conditions
  1213. if isinstance(brushnet, BrushNetModel)
  1214. else brushnet.nets[0].config.global_pool_conditions
  1215. )
  1216. guess_mode = guess_mode or global_pool_conditions
  1217. # 3.1 Encode input prompt
  1218. text_encoder_lora_scale = (
  1219. self.cross_attention_kwargs.get("scale", None)
  1220. if self.cross_attention_kwargs is not None
  1221. else None
  1222. )
  1223. (
  1224. prompt_embeds,
  1225. negative_prompt_embeds,
  1226. pooled_prompt_embeds,
  1227. negative_pooled_prompt_embeds,
  1228. ) = self.encode_prompt(
  1229. prompt,
  1230. prompt_2,
  1231. device,
  1232. num_images_per_prompt,
  1233. self.do_classifier_free_guidance,
  1234. negative_prompt,
  1235. negative_prompt_2,
  1236. prompt_embeds=prompt_embeds,
  1237. negative_prompt_embeds=negative_prompt_embeds,
  1238. pooled_prompt_embeds=pooled_prompt_embeds,
  1239. negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
  1240. lora_scale=text_encoder_lora_scale,
  1241. clip_skip=self.clip_skip,
  1242. )
  1243. # 3.2 Encode ip_adapter_image
  1244. if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
  1245. image_embeds = self.prepare_ip_adapter_image_embeds(
  1246. ip_adapter_image,
  1247. ip_adapter_image_embeds,
  1248. device,
  1249. batch_size * num_images_per_prompt,
  1250. self.do_classifier_free_guidance,
  1251. )
  1252. # 4. Prepare image
  1253. if isinstance(brushnet, BrushNetModel):
  1254. image = self.prepare_image(
  1255. image=image,
  1256. width=width,
  1257. height=height,
  1258. batch_size=batch_size * num_images_per_prompt,
  1259. num_images_per_prompt=num_images_per_prompt,
  1260. device=device,
  1261. dtype=brushnet.dtype,
  1262. do_classifier_free_guidance=self.do_classifier_free_guidance,
  1263. guess_mode=guess_mode,
  1264. )
  1265. original_mask = self.prepare_image(
  1266. image=mask,
  1267. width=width,
  1268. height=height,
  1269. batch_size=batch_size * num_images_per_prompt,
  1270. num_images_per_prompt=num_images_per_prompt,
  1271. device=device,
  1272. dtype=brushnet.dtype,
  1273. do_classifier_free_guidance=self.do_classifier_free_guidance,
  1274. guess_mode=guess_mode,
  1275. )
  1276. original_mask = (original_mask.sum(1)[:, None, :, :] < 0).to(image.dtype)
  1277. height, width = image.shape[-2:]
  1278. # elif isinstance(brushnet, MultiBrushNetModel):
  1279. # images = []
  1280. # for image_ in image:
  1281. # image_ = self.prepare_image(
  1282. # image=image_,
  1283. # width=width,
  1284. # height=height,
  1285. # batch_size=batch_size * num_images_per_prompt,
  1286. # num_images_per_prompt=num_images_per_prompt,
  1287. # device=device,
  1288. # dtype=brushnet.dtype,
  1289. # do_classifier_free_guidance=self.do_classifier_free_guidance,
  1290. # guess_mode=guess_mode,
  1291. # )
  1292. # images.append(image_)
  1293. # image = images
  1294. # height, width = image[0].shape[-2:]
  1295. else:
  1296. assert False
  1297. # 5. Prepare timesteps
  1298. self.scheduler.set_timesteps(num_inference_steps, device=device)
  1299. timesteps = self.scheduler.timesteps
  1300. self._num_timesteps = len(timesteps)
  1301. # 6. Prepare latent variables
  1302. num_channels_latents = self.unet.config.in_channels
  1303. latents, noise = self.prepare_latents(
  1304. batch_size * num_images_per_prompt,
  1305. num_channels_latents,
  1306. height,
  1307. width,
  1308. prompt_embeds.dtype,
  1309. device,
  1310. generator,
  1311. latents,
  1312. )
  1313. # 6.1 prepare condition latents
  1314. conditioning_latents = (
  1315. self.vae.encode(image).latent_dist.sample() * self.vae.config.scaling_factor
  1316. )
  1317. mask = torch.nn.functional.interpolate(
  1318. original_mask,
  1319. size=(conditioning_latents.shape[-2], conditioning_latents.shape[-1]),
  1320. )
  1321. conditioning_latents = torch.concat([conditioning_latents, mask], 1)
  1322. # 6.5 Optionally get Guidance Scale Embedding
  1323. timestep_cond = None
  1324. if self.unet.config.time_cond_proj_dim is not None:
  1325. guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(
  1326. batch_size * num_images_per_prompt
  1327. )
  1328. timestep_cond = self.get_guidance_scale_embedding(
  1329. guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
  1330. ).to(device=device, dtype=latents.dtype)
  1331. # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
  1332. extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
  1333. # 7.1 Create tensor stating which brushnets to keep
  1334. brushnet_keep = []
  1335. for i in range(len(timesteps)):
  1336. keeps = [
  1337. 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
  1338. for s, e in zip(control_guidance_start, control_guidance_end)
  1339. ]
  1340. brushnet_keep.append(
  1341. keeps[0] if isinstance(brushnet, BrushNetModel) else keeps
  1342. )
  1343. # 7.2 Prepare added time ids & embeddings
  1344. if isinstance(image, list):
  1345. original_size = original_size or image[0].shape[-2:]
  1346. else:
  1347. original_size = original_size or image.shape[-2:]
  1348. target_size = target_size or (height, width)
  1349. add_text_embeds = pooled_prompt_embeds
  1350. if self.text_encoder_2 is None:
  1351. text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
  1352. else:
  1353. text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
  1354. add_time_ids = self._get_add_time_ids(
  1355. original_size,
  1356. crops_coords_top_left,
  1357. target_size,
  1358. dtype=prompt_embeds.dtype,
  1359. text_encoder_projection_dim=text_encoder_projection_dim,
  1360. )
  1361. if negative_original_size is not None and negative_target_size is not None:
  1362. negative_add_time_ids = self._get_add_time_ids(
  1363. negative_original_size,
  1364. negative_crops_coords_top_left,
  1365. negative_target_size,
  1366. dtype=prompt_embeds.dtype,
  1367. text_encoder_projection_dim=text_encoder_projection_dim,
  1368. )
  1369. else:
  1370. negative_add_time_ids = add_time_ids
  1371. if self.do_classifier_free_guidance:
  1372. prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
  1373. add_text_embeds = torch.cat(
  1374. [negative_pooled_prompt_embeds, add_text_embeds], dim=0
  1375. )
  1376. add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
  1377. prompt_embeds = prompt_embeds.to(device)
  1378. add_text_embeds = add_text_embeds.to(device)
  1379. add_time_ids = add_time_ids.to(device).repeat(
  1380. batch_size * num_images_per_prompt, 1
  1381. )
  1382. # 8. Denoising loop
  1383. num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
  1384. # 8.1 Apply denoising_end
  1385. if (
  1386. self.denoising_end is not None
  1387. and isinstance(self.denoising_end, float)
  1388. and self.denoising_end > 0
  1389. and self.denoising_end < 1
  1390. ):
  1391. discrete_timestep_cutoff = int(
  1392. round(
  1393. self.scheduler.config.num_train_timesteps
  1394. - (self.denoising_end * self.scheduler.config.num_train_timesteps)
  1395. )
  1396. )
  1397. num_inference_steps = len(
  1398. list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps))
  1399. )
  1400. timesteps = timesteps[:num_inference_steps]
  1401. is_unet_compiled = is_compiled_module(self.unet)
  1402. is_brushnet_compiled = is_compiled_module(self.brushnet)
  1403. is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
  1404. with self.progress_bar(total=num_inference_steps) as progress_bar:
  1405. for i, t in enumerate(timesteps):
  1406. # Relevant thread:
  1407. # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
  1408. if (
  1409. is_unet_compiled and is_brushnet_compiled
  1410. ) and is_torch_higher_equal_2_1:
  1411. torch._inductor.cudagraph_mark_step_begin()
  1412. # expand the latents if we are doing classifier free guidance
  1413. latent_model_input = (
  1414. torch.cat([latents] * 2)
  1415. if self.do_classifier_free_guidance
  1416. else latents
  1417. )
  1418. latent_model_input = self.scheduler.scale_model_input(
  1419. latent_model_input, t
  1420. )
  1421. added_cond_kwargs = {
  1422. "text_embeds": add_text_embeds,
  1423. "time_ids": add_time_ids,
  1424. }
  1425. # brushnet(s) inference
  1426. if guess_mode and self.do_classifier_free_guidance:
  1427. # Infer BrushNet only for the conditional batch.
  1428. control_model_input = latents
  1429. control_model_input = self.scheduler.scale_model_input(
  1430. control_model_input, t
  1431. )
  1432. brushnet_prompt_embeds = prompt_embeds.chunk(2)[1]
  1433. brushnet_added_cond_kwargs = {
  1434. "text_embeds": add_text_embeds.chunk(2)[1],
  1435. "time_ids": add_time_ids.chunk(2)[1],
  1436. }
  1437. else:
  1438. control_model_input = latent_model_input
  1439. brushnet_prompt_embeds = prompt_embeds
  1440. brushnet_added_cond_kwargs = added_cond_kwargs
  1441. if isinstance(brushnet_keep[i], list):
  1442. cond_scale = [
  1443. c * s
  1444. for c, s in zip(brushnet_conditioning_scale, brushnet_keep[i])
  1445. ]
  1446. else:
  1447. brushnet_cond_scale = brushnet_conditioning_scale
  1448. if isinstance(brushnet_cond_scale, list):
  1449. brushnet_cond_scale = brushnet_cond_scale[0]
  1450. cond_scale = brushnet_cond_scale * brushnet_keep[i]
  1451. (
  1452. down_block_res_samples,
  1453. mid_block_res_sample,
  1454. up_block_res_samples,
  1455. ) = self.brushnet(
  1456. control_model_input,
  1457. t,
  1458. encoder_hidden_states=brushnet_prompt_embeds,
  1459. brushnet_cond=conditioning_latents,
  1460. conditioning_scale=cond_scale,
  1461. guess_mode=guess_mode,
  1462. added_cond_kwargs=brushnet_added_cond_kwargs,
  1463. return_dict=False,
  1464. )
  1465. if guess_mode and self.do_classifier_free_guidance:
  1466. # Infered BrushNet only for the conditional batch.
  1467. # To apply the output of BrushNet to both the unconditional and conditional batches,
  1468. # add 0 to the unconditional batch to keep it unchanged.
  1469. down_block_res_samples = [
  1470. torch.cat([torch.zeros_like(d), d])
  1471. for d in down_block_res_samples
  1472. ]
  1473. mid_block_res_sample = torch.cat(
  1474. [torch.zeros_like(mid_block_res_sample), mid_block_res_sample]
  1475. )
  1476. up_block_res_samples = [
  1477. torch.cat([torch.zeros_like(d), d])
  1478. for d in up_block_res_samples
  1479. ]
  1480. if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
  1481. added_cond_kwargs["image_embeds"] = image_embeds
  1482. # predict the noise residual
  1483. noise_pred = self.unet(
  1484. latent_model_input,
  1485. t,
  1486. encoder_hidden_states=prompt_embeds,
  1487. timestep_cond=timestep_cond,
  1488. cross_attention_kwargs=self.cross_attention_kwargs,
  1489. down_block_add_samples=down_block_res_samples,
  1490. mid_block_add_sample=mid_block_res_sample,
  1491. up_block_add_samples=up_block_res_samples,
  1492. added_cond_kwargs=added_cond_kwargs,
  1493. return_dict=False,
  1494. )[0]
  1495. # perform guidance
  1496. if self.do_classifier_free_guidance:
  1497. noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
  1498. noise_pred = noise_pred_uncond + guidance_scale * (
  1499. noise_pred_text - noise_pred_uncond
  1500. )
  1501. # compute the previous noisy sample x_t -> x_t-1
  1502. latents = self.scheduler.step(
  1503. noise_pred, t, latents, **extra_step_kwargs, return_dict=False
  1504. )[0]
  1505. if callback_on_step_end is not None:
  1506. callback_kwargs = {}
  1507. for k in callback_on_step_end_tensor_inputs:
  1508. callback_kwargs[k] = locals()[k]
  1509. callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
  1510. latents = callback_outputs.pop("latents", latents)
  1511. prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
  1512. negative_prompt_embeds = callback_outputs.pop(
  1513. "negative_prompt_embeds", negative_prompt_embeds
  1514. )
  1515. # call the callback, if provided
  1516. if i == len(timesteps) - 1 or (
  1517. (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
  1518. ):
  1519. progress_bar.update()
  1520. if callback is not None and i % callback_steps == 0:
  1521. step_idx = i // getattr(self.scheduler, "order", 1)
  1522. callback(step_idx, t, latents)
  1523. if not output_type == "latent":
  1524. # make sure the VAE is in float32 mode, as it overflows in float16
  1525. needs_upcasting = (
  1526. self.vae.dtype == torch.float16 and self.vae.config.force_upcast
  1527. )
  1528. if needs_upcasting:
  1529. self.upcast_vae()
  1530. latents = latents.to(
  1531. next(iter(self.vae.post_quant_conv.parameters())).dtype
  1532. )
  1533. # unscale/denormalize the latents
  1534. # denormalize with the mean and std if available and not None
  1535. has_latents_mean = (
  1536. hasattr(self.vae.config, "latents_mean")
  1537. and self.vae.config.latents_mean is not None
  1538. )
  1539. has_latents_std = (
  1540. hasattr(self.vae.config, "latents_std")
  1541. and self.vae.config.latents_std is not None
  1542. )
  1543. if has_latents_mean and has_latents_std:
  1544. latents_mean = (
  1545. torch.tensor(self.vae.config.latents_mean)
  1546. .view(1, 4, 1, 1)
  1547. .to(latents.device, latents.dtype)
  1548. )
  1549. latents_std = (
  1550. torch.tensor(self.vae.config.latents_std)
  1551. .view(1, 4, 1, 1)
  1552. .to(latents.device, latents.dtype)
  1553. )
  1554. latents = (
  1555. latents * latents_std / self.vae.config.scaling_factor
  1556. + latents_mean
  1557. )
  1558. else:
  1559. latents = latents / self.vae.config.scaling_factor
  1560. image = self.vae.decode(latents, return_dict=False)[0]
  1561. # cast back to fp16 if needed
  1562. if needs_upcasting:
  1563. self.vae.to(dtype=torch.float16)
  1564. else:
  1565. image = latents
  1566. if not output_type == "latent":
  1567. # apply watermark if available
  1568. if self.watermark is not None:
  1569. image = self.watermark.apply_watermark(image)
  1570. image = self.image_processor.postprocess(image, output_type=output_type)
  1571. # Offload all models
  1572. self.maybe_free_model_hooks()
  1573. if not return_dict:
  1574. return (image,)
  1575. return StableDiffusionXLPipelineOutput(images=image)