diffusers 0.27.0__py3-none-any.whl → 0.32.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (445) hide show
  1. diffusers/__init__.py +233 -6
  2. diffusers/callbacks.py +209 -0
  3. diffusers/commands/env.py +102 -6
  4. diffusers/configuration_utils.py +45 -16
  5. diffusers/dependency_versions_table.py +4 -3
  6. diffusers/image_processor.py +434 -110
  7. diffusers/loaders/__init__.py +42 -9
  8. diffusers/loaders/ip_adapter.py +626 -36
  9. diffusers/loaders/lora_base.py +900 -0
  10. diffusers/loaders/lora_conversion_utils.py +991 -125
  11. diffusers/loaders/lora_pipeline.py +3812 -0
  12. diffusers/loaders/peft.py +571 -7
  13. diffusers/loaders/single_file.py +405 -173
  14. diffusers/loaders/single_file_model.py +385 -0
  15. diffusers/loaders/single_file_utils.py +1783 -713
  16. diffusers/loaders/textual_inversion.py +41 -23
  17. diffusers/loaders/transformer_flux.py +181 -0
  18. diffusers/loaders/transformer_sd3.py +89 -0
  19. diffusers/loaders/unet.py +464 -540
  20. diffusers/loaders/unet_loader_utils.py +163 -0
  21. diffusers/models/__init__.py +76 -7
  22. diffusers/models/activations.py +65 -10
  23. diffusers/models/adapter.py +53 -53
  24. diffusers/models/attention.py +605 -18
  25. diffusers/models/attention_flax.py +1 -1
  26. diffusers/models/attention_processor.py +4304 -687
  27. diffusers/models/autoencoders/__init__.py +8 -0
  28. diffusers/models/autoencoders/autoencoder_asym_kl.py +15 -17
  29. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  30. diffusers/models/autoencoders/autoencoder_kl.py +110 -28
  31. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  32. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1482 -0
  33. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  34. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  35. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  36. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +19 -24
  37. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  38. diffusers/models/autoencoders/autoencoder_tiny.py +21 -18
  39. diffusers/models/autoencoders/consistency_decoder_vae.py +45 -20
  40. diffusers/models/autoencoders/vae.py +41 -29
  41. diffusers/models/autoencoders/vq_model.py +182 -0
  42. diffusers/models/controlnet.py +47 -800
  43. diffusers/models/controlnet_flux.py +70 -0
  44. diffusers/models/controlnet_sd3.py +68 -0
  45. diffusers/models/controlnet_sparsectrl.py +116 -0
  46. diffusers/models/controlnets/__init__.py +23 -0
  47. diffusers/models/controlnets/controlnet.py +872 -0
  48. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +9 -9
  49. diffusers/models/controlnets/controlnet_flux.py +536 -0
  50. diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
  51. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  52. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  53. diffusers/models/controlnets/controlnet_union.py +832 -0
  54. diffusers/models/controlnets/controlnet_xs.py +1946 -0
  55. diffusers/models/controlnets/multicontrolnet.py +183 -0
  56. diffusers/models/downsampling.py +85 -18
  57. diffusers/models/embeddings.py +1856 -158
  58. diffusers/models/embeddings_flax.py +23 -9
  59. diffusers/models/model_loading_utils.py +480 -0
  60. diffusers/models/modeling_flax_pytorch_utils.py +2 -1
  61. diffusers/models/modeling_flax_utils.py +2 -7
  62. diffusers/models/modeling_outputs.py +14 -0
  63. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  64. diffusers/models/modeling_utils.py +611 -146
  65. diffusers/models/normalization.py +361 -20
  66. diffusers/models/resnet.py +18 -23
  67. diffusers/models/transformers/__init__.py +16 -0
  68. diffusers/models/transformers/auraflow_transformer_2d.py +544 -0
  69. diffusers/models/transformers/cogvideox_transformer_3d.py +542 -0
  70. diffusers/models/transformers/dit_transformer_2d.py +240 -0
  71. diffusers/models/transformers/dual_transformer_2d.py +9 -8
  72. diffusers/models/transformers/hunyuan_transformer_2d.py +578 -0
  73. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  74. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  75. diffusers/models/transformers/pixart_transformer_2d.py +445 -0
  76. diffusers/models/transformers/prior_transformer.py +13 -13
  77. diffusers/models/transformers/sana_transformer.py +488 -0
  78. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  79. diffusers/models/transformers/t5_film_transformer.py +17 -19
  80. diffusers/models/transformers/transformer_2d.py +297 -187
  81. diffusers/models/transformers/transformer_allegro.py +422 -0
  82. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  83. diffusers/models/transformers/transformer_flux.py +593 -0
  84. diffusers/models/transformers/transformer_hunyuan_video.py +791 -0
  85. diffusers/models/transformers/transformer_ltx.py +469 -0
  86. diffusers/models/transformers/transformer_mochi.py +499 -0
  87. diffusers/models/transformers/transformer_sd3.py +461 -0
  88. diffusers/models/transformers/transformer_temporal.py +21 -19
  89. diffusers/models/unets/unet_1d.py +8 -8
  90. diffusers/models/unets/unet_1d_blocks.py +31 -31
  91. diffusers/models/unets/unet_2d.py +17 -10
  92. diffusers/models/unets/unet_2d_blocks.py +225 -149
  93. diffusers/models/unets/unet_2d_condition.py +50 -53
  94. diffusers/models/unets/unet_2d_condition_flax.py +6 -5
  95. diffusers/models/unets/unet_3d_blocks.py +192 -1057
  96. diffusers/models/unets/unet_3d_condition.py +22 -27
  97. diffusers/models/unets/unet_i2vgen_xl.py +22 -18
  98. diffusers/models/unets/unet_kandinsky3.py +2 -2
  99. diffusers/models/unets/unet_motion_model.py +1413 -89
  100. diffusers/models/unets/unet_spatio_temporal_condition.py +40 -16
  101. diffusers/models/unets/unet_stable_cascade.py +19 -18
  102. diffusers/models/unets/uvit_2d.py +2 -2
  103. diffusers/models/upsampling.py +95 -26
  104. diffusers/models/vq_model.py +12 -164
  105. diffusers/optimization.py +1 -1
  106. diffusers/pipelines/__init__.py +202 -3
  107. diffusers/pipelines/allegro/__init__.py +48 -0
  108. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  109. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  110. diffusers/pipelines/amused/pipeline_amused.py +12 -12
  111. diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
  112. diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
  113. diffusers/pipelines/animatediff/__init__.py +8 -0
  114. diffusers/pipelines/animatediff/pipeline_animatediff.py +122 -109
  115. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1106 -0
  116. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1288 -0
  117. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1010 -0
  118. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +236 -180
  119. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  120. diffusers/pipelines/animatediff/pipeline_output.py +3 -2
  121. diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
  122. diffusers/pipelines/audioldm2/modeling_audioldm2.py +58 -39
  123. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +121 -36
  124. diffusers/pipelines/aura_flow/__init__.py +48 -0
  125. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +584 -0
  126. diffusers/pipelines/auto_pipeline.py +196 -28
  127. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  128. diffusers/pipelines/blip_diffusion/modeling_blip2.py +6 -6
  129. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
  130. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  131. diffusers/pipelines/cogvideo/__init__.py +54 -0
  132. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +772 -0
  133. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
  134. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +885 -0
  135. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +851 -0
  136. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  137. diffusers/pipelines/cogview3/__init__.py +47 -0
  138. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  139. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  140. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +6 -6
  141. diffusers/pipelines/controlnet/__init__.py +86 -80
  142. diffusers/pipelines/controlnet/multicontrolnet.py +7 -182
  143. diffusers/pipelines/controlnet/pipeline_controlnet.py +134 -87
  144. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  145. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +93 -77
  146. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +88 -197
  147. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +136 -90
  148. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +176 -80
  149. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +125 -89
  150. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  151. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  152. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  153. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  154. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  155. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1060 -0
  156. diffusers/pipelines/controlnet_sd3/__init__.py +57 -0
  157. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1133 -0
  158. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  159. diffusers/pipelines/controlnet_xs/__init__.py +68 -0
  160. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +916 -0
  161. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1111 -0
  162. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  163. diffusers/pipelines/deepfloyd_if/pipeline_if.py +16 -30
  164. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +20 -35
  165. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +23 -41
  166. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +22 -38
  167. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +25 -41
  168. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +19 -34
  169. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  170. diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
  171. diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
  172. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +70 -30
  173. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +48 -25
  174. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
  175. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
  176. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +21 -20
  177. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +27 -29
  178. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +33 -27
  179. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +33 -23
  180. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +36 -30
  181. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +102 -69
  182. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
  183. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
  184. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
  185. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
  186. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
  187. diffusers/pipelines/dit/pipeline_dit.py +7 -4
  188. diffusers/pipelines/flux/__init__.py +69 -0
  189. diffusers/pipelines/flux/modeling_flux.py +47 -0
  190. diffusers/pipelines/flux/pipeline_flux.py +957 -0
  191. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  192. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  193. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  194. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
  195. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
  196. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
  197. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  198. diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
  199. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
  200. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  201. diffusers/pipelines/flux/pipeline_output.py +37 -0
  202. diffusers/pipelines/free_init_utils.py +41 -38
  203. diffusers/pipelines/free_noise_utils.py +596 -0
  204. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  205. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  206. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  207. diffusers/pipelines/hunyuandit/__init__.py +48 -0
  208. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +916 -0
  209. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
  210. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
  211. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +32 -29
  212. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
  213. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
  214. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
  215. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  216. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +34 -31
  217. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
  218. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
  219. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
  220. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
  221. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
  222. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
  223. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
  224. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +22 -35
  225. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +26 -37
  226. diffusers/pipelines/kolors/__init__.py +54 -0
  227. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  228. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1250 -0
  229. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  230. diffusers/pipelines/kolors/text_encoder.py +889 -0
  231. diffusers/pipelines/kolors/tokenizer.py +338 -0
  232. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +82 -62
  233. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +77 -60
  234. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +12 -12
  235. diffusers/pipelines/latte/__init__.py +48 -0
  236. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  237. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +80 -74
  238. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +85 -76
  239. diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
  240. diffusers/pipelines/ltx/__init__.py +50 -0
  241. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  242. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  243. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  244. diffusers/pipelines/lumina/__init__.py +48 -0
  245. diffusers/pipelines/lumina/pipeline_lumina.py +890 -0
  246. diffusers/pipelines/marigold/__init__.py +50 -0
  247. diffusers/pipelines/marigold/marigold_image_processing.py +576 -0
  248. diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
  249. diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
  250. diffusers/pipelines/mochi/__init__.py +48 -0
  251. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  252. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  253. diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
  254. diffusers/pipelines/pag/__init__.py +80 -0
  255. diffusers/pipelines/pag/pag_utils.py +243 -0
  256. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1328 -0
  257. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
  258. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1610 -0
  259. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
  260. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +969 -0
  261. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  262. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +865 -0
  263. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  264. diffusers/pipelines/pag/pipeline_pag_sd.py +1062 -0
  265. diffusers/pipelines/pag/pipeline_pag_sd_3.py +994 -0
  266. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  267. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +866 -0
  268. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
  269. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  270. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1345 -0
  271. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1544 -0
  272. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1776 -0
  273. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
  274. diffusers/pipelines/pia/pipeline_pia.py +74 -164
  275. diffusers/pipelines/pipeline_flax_utils.py +5 -10
  276. diffusers/pipelines/pipeline_loading_utils.py +515 -53
  277. diffusers/pipelines/pipeline_utils.py +411 -222
  278. diffusers/pipelines/pixart_alpha/__init__.py +8 -1
  279. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +76 -93
  280. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +873 -0
  281. diffusers/pipelines/sana/__init__.py +47 -0
  282. diffusers/pipelines/sana/pipeline_output.py +21 -0
  283. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  284. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +27 -23
  285. diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
  286. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
  287. diffusers/pipelines/shap_e/renderer.py +1 -1
  288. diffusers/pipelines/stable_audio/__init__.py +50 -0
  289. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  290. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +756 -0
  291. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +71 -25
  292. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
  293. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +35 -34
  294. diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  295. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +20 -11
  296. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  297. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  298. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
  299. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +145 -79
  300. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +43 -28
  301. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
  302. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +100 -68
  303. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +109 -201
  304. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +131 -32
  305. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +247 -87
  306. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +30 -29
  307. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +35 -27
  308. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +49 -42
  309. diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
  310. diffusers/pipelines/stable_diffusion_3/__init__.py +54 -0
  311. diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
  312. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1140 -0
  313. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1036 -0
  314. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1250 -0
  315. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +29 -20
  316. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +59 -58
  317. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +31 -25
  318. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +38 -22
  319. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -24
  320. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -23
  321. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +107 -67
  322. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +316 -69
  323. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
  324. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  325. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +98 -30
  326. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +121 -83
  327. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +161 -105
  328. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +142 -218
  329. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -29
  330. diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
  331. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
  332. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +69 -39
  333. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +105 -74
  334. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
  335. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +29 -49
  336. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +32 -93
  337. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +37 -25
  338. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +54 -40
  339. diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
  340. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
  341. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
  342. diffusers/pipelines/unidiffuser/modeling_uvit.py +12 -12
  343. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +29 -28
  344. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
  345. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
  346. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +6 -8
  347. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
  348. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
  349. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +15 -14
  350. diffusers/{models/dual_transformer_2d.py → quantizers/__init__.py} +2 -6
  351. diffusers/quantizers/auto.py +139 -0
  352. diffusers/quantizers/base.py +233 -0
  353. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  354. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
  355. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  356. diffusers/quantizers/gguf/__init__.py +1 -0
  357. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  358. diffusers/quantizers/gguf/utils.py +456 -0
  359. diffusers/quantizers/quantization_config.py +669 -0
  360. diffusers/quantizers/torchao/__init__.py +15 -0
  361. diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
  362. diffusers/schedulers/__init__.py +12 -2
  363. diffusers/schedulers/deprecated/__init__.py +1 -1
  364. diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
  365. diffusers/schedulers/scheduling_amused.py +5 -5
  366. diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
  367. diffusers/schedulers/scheduling_consistency_models.py +23 -25
  368. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  369. diffusers/schedulers/scheduling_ddim.py +27 -26
  370. diffusers/schedulers/scheduling_ddim_cogvideox.py +452 -0
  371. diffusers/schedulers/scheduling_ddim_flax.py +2 -1
  372. diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
  373. diffusers/schedulers/scheduling_ddim_parallel.py +32 -31
  374. diffusers/schedulers/scheduling_ddpm.py +27 -30
  375. diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
  376. diffusers/schedulers/scheduling_ddpm_parallel.py +33 -36
  377. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
  378. diffusers/schedulers/scheduling_deis_multistep.py +150 -50
  379. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  380. diffusers/schedulers/scheduling_dpmsolver_multistep.py +221 -84
  381. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
  382. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +158 -52
  383. diffusers/schedulers/scheduling_dpmsolver_sde.py +153 -34
  384. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +275 -86
  385. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +81 -57
  386. diffusers/schedulers/scheduling_edm_euler.py +62 -39
  387. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +30 -29
  388. diffusers/schedulers/scheduling_euler_discrete.py +255 -74
  389. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +458 -0
  390. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +320 -0
  391. diffusers/schedulers/scheduling_heun_discrete.py +174 -46
  392. diffusers/schedulers/scheduling_ipndm.py +9 -9
  393. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +138 -29
  394. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +132 -26
  395. diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
  396. diffusers/schedulers/scheduling_lcm.py +23 -29
  397. diffusers/schedulers/scheduling_lms_discrete.py +105 -28
  398. diffusers/schedulers/scheduling_pndm.py +20 -20
  399. diffusers/schedulers/scheduling_repaint.py +21 -21
  400. diffusers/schedulers/scheduling_sasolver.py +157 -60
  401. diffusers/schedulers/scheduling_sde_ve.py +19 -19
  402. diffusers/schedulers/scheduling_tcd.py +41 -36
  403. diffusers/schedulers/scheduling_unclip.py +19 -16
  404. diffusers/schedulers/scheduling_unipc_multistep.py +243 -47
  405. diffusers/schedulers/scheduling_utils.py +12 -5
  406. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  407. diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
  408. diffusers/training_utils.py +214 -30
  409. diffusers/utils/__init__.py +17 -1
  410. diffusers/utils/constants.py +3 -0
  411. diffusers/utils/doc_utils.py +1 -0
  412. diffusers/utils/dummy_pt_objects.py +592 -7
  413. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  414. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  415. diffusers/utils/dummy_torch_and_transformers_objects.py +1001 -71
  416. diffusers/utils/dynamic_modules_utils.py +34 -29
  417. diffusers/utils/export_utils.py +50 -6
  418. diffusers/utils/hub_utils.py +131 -17
  419. diffusers/utils/import_utils.py +210 -8
  420. diffusers/utils/loading_utils.py +118 -5
  421. diffusers/utils/logging.py +4 -2
  422. diffusers/utils/peft_utils.py +37 -7
  423. diffusers/utils/state_dict_utils.py +13 -2
  424. diffusers/utils/testing_utils.py +193 -11
  425. diffusers/utils/torch_utils.py +4 -0
  426. diffusers/video_processor.py +113 -0
  427. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
  428. diffusers-0.32.2.dist-info/RECORD +550 -0
  429. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/WHEEL +1 -1
  430. diffusers/loaders/autoencoder.py +0 -146
  431. diffusers/loaders/controlnet.py +0 -136
  432. diffusers/loaders/lora.py +0 -1349
  433. diffusers/models/prior_transformer.py +0 -12
  434. diffusers/models/t5_film_transformer.py +0 -70
  435. diffusers/models/transformer_2d.py +0 -25
  436. diffusers/models/transformer_temporal.py +0 -34
  437. diffusers/models/unet_1d.py +0 -26
  438. diffusers/models/unet_1d_blocks.py +0 -203
  439. diffusers/models/unet_2d.py +0 -27
  440. diffusers/models/unet_2d_blocks.py +0 -375
  441. diffusers/models/unet_2d_condition.py +0 -25
  442. diffusers-0.27.0.dist-info/RECORD +0 -399
  443. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
  444. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
  445. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1776 @@
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import PIL.Image
19
+ import torch
20
+ from transformers import (
21
+ CLIPImageProcessor,
22
+ CLIPTextModel,
23
+ CLIPTextModelWithProjection,
24
+ CLIPTokenizer,
25
+ CLIPVisionModelWithProjection,
26
+ )
27
+
28
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
29
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
30
+ from ...loaders import (
31
+ FromSingleFileMixin,
32
+ IPAdapterMixin,
33
+ StableDiffusionXLLoraLoaderMixin,
34
+ TextualInversionLoaderMixin,
35
+ )
36
+ from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
37
+ from ...models.attention_processor import (
38
+ AttnProcessor2_0,
39
+ XFormersAttnProcessor,
40
+ )
41
+ from ...models.lora import adjust_lora_scale_text_encoder
42
+ from ...schedulers import KarrasDiffusionSchedulers
43
+ from ...utils import (
44
+ USE_PEFT_BACKEND,
45
+ is_invisible_watermark_available,
46
+ is_torch_xla_available,
47
+ logging,
48
+ replace_example_docstring,
49
+ scale_lora_layers,
50
+ unscale_lora_layers,
51
+ )
52
+ from ...utils.torch_utils import randn_tensor
53
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
54
+ from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
55
+ from .pag_utils import PAGMixin
56
+
57
+
58
+ if is_invisible_watermark_available():
59
+ from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
60
+
61
+ if is_torch_xla_available():
62
+ import torch_xla.core.xla_model as xm
63
+
64
+ XLA_AVAILABLE = True
65
+ else:
66
+ XLA_AVAILABLE = False
67
+
68
+
69
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
70
+
71
+
72
+ EXAMPLE_DOC_STRING = """
73
+ Examples:
74
+ ```py
75
+ >>> import torch
76
+ >>> from diffusers import AutoPipelineForInpainting
77
+ >>> from diffusers.utils import load_image
78
+
79
+ >>> pipe = AutoPipelineForInpainting.from_pretrained(
80
+ ... "stabilityai/stable-diffusion-xl-base-1.0",
81
+ ... torch_dtype=torch.float16,
82
+ ... variant="fp16",
83
+ ... enable_pag=True,
84
+ ... )
85
+ >>> pipe.to("cuda")
86
+
87
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
88
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
89
+
90
+ >>> init_image = load_image(img_url).convert("RGB")
91
+ >>> mask_image = load_image(mask_url).convert("RGB")
92
+
93
+ >>> prompt = "A majestic tiger sitting on a bench"
94
+ >>> image = pipe(
95
+ ... prompt=prompt,
96
+ ... image=init_image,
97
+ ... mask_image=mask_image,
98
+ ... num_inference_steps=50,
99
+ ... strength=0.80,
100
+ ... pag_scale=0.3,
101
+ ... ).images[0]
102
+ ```
103
+ """
104
+
105
+
106
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
107
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
108
+ r"""
109
+ Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
110
+ Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
111
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf).
112
+
113
+ Args:
114
+ noise_cfg (`torch.Tensor`):
115
+ The predicted noise tensor for the guided diffusion process.
116
+ noise_pred_text (`torch.Tensor`):
117
+ The predicted noise tensor for the text-guided diffusion process.
118
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
119
+ A rescale factor applied to the noise predictions.
120
+
121
+ Returns:
122
+ noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
123
+ """
124
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
125
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
126
+ # rescale the results from guidance (fixes overexposure)
127
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
128
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
129
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
130
+ return noise_cfg
131
+
132
+
133
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
134
+ def retrieve_latents(
135
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
136
+ ):
137
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
138
+ return encoder_output.latent_dist.sample(generator)
139
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
140
+ return encoder_output.latent_dist.mode()
141
+ elif hasattr(encoder_output, "latents"):
142
+ return encoder_output.latents
143
+ else:
144
+ raise AttributeError("Could not access latents of provided encoder_output")
145
+
146
+
147
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
148
+ def retrieve_timesteps(
149
+ scheduler,
150
+ num_inference_steps: Optional[int] = None,
151
+ device: Optional[Union[str, torch.device]] = None,
152
+ timesteps: Optional[List[int]] = None,
153
+ sigmas: Optional[List[float]] = None,
154
+ **kwargs,
155
+ ):
156
+ r"""
157
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
158
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
159
+
160
+ Args:
161
+ scheduler (`SchedulerMixin`):
162
+ The scheduler to get timesteps from.
163
+ num_inference_steps (`int`):
164
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
165
+ must be `None`.
166
+ device (`str` or `torch.device`, *optional*):
167
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
168
+ timesteps (`List[int]`, *optional*):
169
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
170
+ `num_inference_steps` and `sigmas` must be `None`.
171
+ sigmas (`List[float]`, *optional*):
172
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
173
+ `num_inference_steps` and `timesteps` must be `None`.
174
+
175
+ Returns:
176
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
177
+ second element is the number of inference steps.
178
+ """
179
+ if timesteps is not None and sigmas is not None:
180
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
181
+ if timesteps is not None:
182
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
183
+ if not accepts_timesteps:
184
+ raise ValueError(
185
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
186
+ f" timestep schedules. Please check whether you are using the correct scheduler."
187
+ )
188
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
189
+ timesteps = scheduler.timesteps
190
+ num_inference_steps = len(timesteps)
191
+ elif sigmas is not None:
192
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
193
+ if not accept_sigmas:
194
+ raise ValueError(
195
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
196
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
197
+ )
198
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
199
+ timesteps = scheduler.timesteps
200
+ num_inference_steps = len(timesteps)
201
+ else:
202
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
203
+ timesteps = scheduler.timesteps
204
+ return timesteps, num_inference_steps
205
+
206
+
207
+ class StableDiffusionXLPAGInpaintPipeline(
208
+ DiffusionPipeline,
209
+ StableDiffusionMixin,
210
+ TextualInversionLoaderMixin,
211
+ StableDiffusionXLLoraLoaderMixin,
212
+ FromSingleFileMixin,
213
+ IPAdapterMixin,
214
+ PAGMixin,
215
+ ):
216
+ r"""
217
+ Pipeline for text-to-image generation using Stable Diffusion XL.
218
+
219
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
220
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
221
+
222
+ The pipeline also inherits the following loading methods:
223
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
224
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
225
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
226
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
227
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
228
+
229
+ Args:
230
+ vae ([`AutoencoderKL`]):
231
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
232
+ text_encoder ([`CLIPTextModel`]):
233
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
234
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
235
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
236
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
237
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
238
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
239
+ specifically the
240
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
241
+ variant.
242
+ tokenizer (`CLIPTokenizer`):
243
+ Tokenizer of class
244
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
245
+ tokenizer_2 (`CLIPTokenizer`):
246
+ Second Tokenizer of class
247
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
248
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
249
+ scheduler ([`SchedulerMixin`]):
250
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
251
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
252
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
253
+ Whether the `unet` requires a aesthetic_score condition to be passed during inference. Also see the config
254
+ of `stabilityai/stable-diffusion-xl-refiner-1-0`.
255
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
256
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
257
+ `stabilityai/stable-diffusion-xl-base-1-0`.
258
+ add_watermarker (`bool`, *optional*):
259
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
260
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
261
+ watermarker will be used.
262
+ """
263
+
264
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
265
+
266
+ _optional_components = [
267
+ "tokenizer",
268
+ "tokenizer_2",
269
+ "text_encoder",
270
+ "text_encoder_2",
271
+ "image_encoder",
272
+ "feature_extractor",
273
+ ]
274
+ _callback_tensor_inputs = [
275
+ "latents",
276
+ "prompt_embeds",
277
+ "negative_prompt_embeds",
278
+ "add_text_embeds",
279
+ "add_time_ids",
280
+ "negative_pooled_prompt_embeds",
281
+ "add_neg_time_ids",
282
+ "mask",
283
+ "masked_image_latents",
284
+ ]
285
+
286
+ def __init__(
287
+ self,
288
+ vae: AutoencoderKL,
289
+ text_encoder: CLIPTextModel,
290
+ text_encoder_2: CLIPTextModelWithProjection,
291
+ tokenizer: CLIPTokenizer,
292
+ tokenizer_2: CLIPTokenizer,
293
+ unet: UNet2DConditionModel,
294
+ scheduler: KarrasDiffusionSchedulers,
295
+ image_encoder: CLIPVisionModelWithProjection = None,
296
+ feature_extractor: CLIPImageProcessor = None,
297
+ requires_aesthetics_score: bool = False,
298
+ force_zeros_for_empty_prompt: bool = True,
299
+ add_watermarker: Optional[bool] = None,
300
+ pag_applied_layers: Union[str, List[str]] = "mid", # ["mid"], ["down.block_1", "up.block_0.attentions_0"]
301
+ ):
302
+ super().__init__()
303
+
304
+ self.register_modules(
305
+ vae=vae,
306
+ text_encoder=text_encoder,
307
+ text_encoder_2=text_encoder_2,
308
+ tokenizer=tokenizer,
309
+ tokenizer_2=tokenizer_2,
310
+ unet=unet,
311
+ image_encoder=image_encoder,
312
+ feature_extractor=feature_extractor,
313
+ scheduler=scheduler,
314
+ )
315
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
316
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
317
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
318
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
319
+ self.mask_processor = VaeImageProcessor(
320
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
321
+ )
322
+
323
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
324
+
325
+ if add_watermarker:
326
+ self.watermark = StableDiffusionXLWatermarker()
327
+ else:
328
+ self.watermark = None
329
+
330
+ self.set_pag_applied_layers(pag_applied_layers)
331
+
332
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
333
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
334
+ dtype = next(self.image_encoder.parameters()).dtype
335
+
336
+ if not isinstance(image, torch.Tensor):
337
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
338
+
339
+ image = image.to(device=device, dtype=dtype)
340
+ if output_hidden_states:
341
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
342
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
343
+ uncond_image_enc_hidden_states = self.image_encoder(
344
+ torch.zeros_like(image), output_hidden_states=True
345
+ ).hidden_states[-2]
346
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
347
+ num_images_per_prompt, dim=0
348
+ )
349
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
350
+ else:
351
+ image_embeds = self.image_encoder(image).image_embeds
352
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
353
+ uncond_image_embeds = torch.zeros_like(image_embeds)
354
+
355
+ return image_embeds, uncond_image_embeds
356
+
357
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
358
+ def prepare_ip_adapter_image_embeds(
359
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
360
+ ):
361
+ image_embeds = []
362
+ if do_classifier_free_guidance:
363
+ negative_image_embeds = []
364
+ if ip_adapter_image_embeds is None:
365
+ if not isinstance(ip_adapter_image, list):
366
+ ip_adapter_image = [ip_adapter_image]
367
+
368
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
369
+ raise ValueError(
370
+ 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."
371
+ )
372
+
373
+ for single_ip_adapter_image, image_proj_layer in zip(
374
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
375
+ ):
376
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
377
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
378
+ single_ip_adapter_image, device, 1, output_hidden_state
379
+ )
380
+
381
+ image_embeds.append(single_image_embeds[None, :])
382
+ if do_classifier_free_guidance:
383
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
384
+ else:
385
+ for single_image_embeds in ip_adapter_image_embeds:
386
+ if do_classifier_free_guidance:
387
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
388
+ negative_image_embeds.append(single_negative_image_embeds)
389
+ image_embeds.append(single_image_embeds)
390
+
391
+ ip_adapter_image_embeds = []
392
+ for i, single_image_embeds in enumerate(image_embeds):
393
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
394
+ if do_classifier_free_guidance:
395
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
396
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
397
+
398
+ single_image_embeds = single_image_embeds.to(device=device)
399
+ ip_adapter_image_embeds.append(single_image_embeds)
400
+
401
+ return ip_adapter_image_embeds
402
+
403
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
404
+ def encode_prompt(
405
+ self,
406
+ prompt: str,
407
+ prompt_2: Optional[str] = None,
408
+ device: Optional[torch.device] = None,
409
+ num_images_per_prompt: int = 1,
410
+ do_classifier_free_guidance: bool = True,
411
+ negative_prompt: Optional[str] = None,
412
+ negative_prompt_2: Optional[str] = None,
413
+ prompt_embeds: Optional[torch.Tensor] = None,
414
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
415
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
416
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
417
+ lora_scale: Optional[float] = None,
418
+ clip_skip: Optional[int] = None,
419
+ ):
420
+ r"""
421
+ Encodes the prompt into text encoder hidden states.
422
+
423
+ Args:
424
+ prompt (`str` or `List[str]`, *optional*):
425
+ prompt to be encoded
426
+ prompt_2 (`str` or `List[str]`, *optional*):
427
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
428
+ used in both text-encoders
429
+ device: (`torch.device`):
430
+ torch device
431
+ num_images_per_prompt (`int`):
432
+ number of images that should be generated per prompt
433
+ do_classifier_free_guidance (`bool`):
434
+ whether to use classifier free guidance or not
435
+ negative_prompt (`str` or `List[str]`, *optional*):
436
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
437
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
438
+ less than `1`).
439
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
440
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
441
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
442
+ prompt_embeds (`torch.Tensor`, *optional*):
443
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
444
+ provided, text embeddings will be generated from `prompt` input argument.
445
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
446
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
447
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
448
+ argument.
449
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
450
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
451
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
452
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
453
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
454
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
455
+ input argument.
456
+ lora_scale (`float`, *optional*):
457
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
458
+ clip_skip (`int`, *optional*):
459
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
460
+ the output of the pre-final layer will be used for computing the prompt embeddings.
461
+ """
462
+ device = device or self._execution_device
463
+
464
+ # set lora scale so that monkey patched LoRA
465
+ # function of text encoder can correctly access it
466
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
467
+ self._lora_scale = lora_scale
468
+
469
+ # dynamically adjust the LoRA scale
470
+ if self.text_encoder is not None:
471
+ if not USE_PEFT_BACKEND:
472
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
473
+ else:
474
+ scale_lora_layers(self.text_encoder, lora_scale)
475
+
476
+ if self.text_encoder_2 is not None:
477
+ if not USE_PEFT_BACKEND:
478
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
479
+ else:
480
+ scale_lora_layers(self.text_encoder_2, lora_scale)
481
+
482
+ prompt = [prompt] if isinstance(prompt, str) else prompt
483
+
484
+ if prompt is not None:
485
+ batch_size = len(prompt)
486
+ else:
487
+ batch_size = prompt_embeds.shape[0]
488
+
489
+ # Define tokenizers and text encoders
490
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
491
+ text_encoders = (
492
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
493
+ )
494
+
495
+ if prompt_embeds is None:
496
+ prompt_2 = prompt_2 or prompt
497
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
498
+
499
+ # textual inversion: process multi-vector tokens if necessary
500
+ prompt_embeds_list = []
501
+ prompts = [prompt, prompt_2]
502
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
503
+ if isinstance(self, TextualInversionLoaderMixin):
504
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
505
+
506
+ text_inputs = tokenizer(
507
+ prompt,
508
+ padding="max_length",
509
+ max_length=tokenizer.model_max_length,
510
+ truncation=True,
511
+ return_tensors="pt",
512
+ )
513
+
514
+ text_input_ids = text_inputs.input_ids
515
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
516
+
517
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
518
+ text_input_ids, untruncated_ids
519
+ ):
520
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
521
+ logger.warning(
522
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
523
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
524
+ )
525
+
526
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
527
+
528
+ # We are only ALWAYS interested in the pooled output of the final text encoder
529
+ pooled_prompt_embeds = prompt_embeds[0]
530
+ if clip_skip is None:
531
+ prompt_embeds = prompt_embeds.hidden_states[-2]
532
+ else:
533
+ # "2" because SDXL always indexes from the penultimate layer.
534
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
535
+
536
+ prompt_embeds_list.append(prompt_embeds)
537
+
538
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
539
+
540
+ # get unconditional embeddings for classifier free guidance
541
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
542
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
543
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
544
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
545
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
546
+ negative_prompt = negative_prompt or ""
547
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
548
+
549
+ # normalize str to list
550
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
551
+ negative_prompt_2 = (
552
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
553
+ )
554
+
555
+ uncond_tokens: List[str]
556
+ if prompt is not None and type(prompt) is not type(negative_prompt):
557
+ raise TypeError(
558
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
559
+ f" {type(prompt)}."
560
+ )
561
+ elif batch_size != len(negative_prompt):
562
+ raise ValueError(
563
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
564
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
565
+ " the batch size of `prompt`."
566
+ )
567
+ else:
568
+ uncond_tokens = [negative_prompt, negative_prompt_2]
569
+
570
+ negative_prompt_embeds_list = []
571
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
572
+ if isinstance(self, TextualInversionLoaderMixin):
573
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
574
+
575
+ max_length = prompt_embeds.shape[1]
576
+ uncond_input = tokenizer(
577
+ negative_prompt,
578
+ padding="max_length",
579
+ max_length=max_length,
580
+ truncation=True,
581
+ return_tensors="pt",
582
+ )
583
+
584
+ negative_prompt_embeds = text_encoder(
585
+ uncond_input.input_ids.to(device),
586
+ output_hidden_states=True,
587
+ )
588
+ # We are only ALWAYS interested in the pooled output of the final text encoder
589
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
590
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
591
+
592
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
593
+
594
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
595
+
596
+ if self.text_encoder_2 is not None:
597
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
598
+ else:
599
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
600
+
601
+ bs_embed, seq_len, _ = prompt_embeds.shape
602
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
603
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
604
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
605
+
606
+ if do_classifier_free_guidance:
607
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
608
+ seq_len = negative_prompt_embeds.shape[1]
609
+
610
+ if self.text_encoder_2 is not None:
611
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
612
+ else:
613
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
614
+
615
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
616
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
617
+
618
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
619
+ bs_embed * num_images_per_prompt, -1
620
+ )
621
+ if do_classifier_free_guidance:
622
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
623
+ bs_embed * num_images_per_prompt, -1
624
+ )
625
+
626
+ if self.text_encoder is not None:
627
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
628
+ # Retrieve the original scale by scaling back the LoRA layers
629
+ unscale_lora_layers(self.text_encoder, lora_scale)
630
+
631
+ if self.text_encoder_2 is not None:
632
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
633
+ # Retrieve the original scale by scaling back the LoRA layers
634
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
635
+
636
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
637
+
638
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
639
+ def prepare_extra_step_kwargs(self, generator, eta):
640
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
641
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
642
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
643
+ # and should be between [0, 1]
644
+
645
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
646
+ extra_step_kwargs = {}
647
+ if accepts_eta:
648
+ extra_step_kwargs["eta"] = eta
649
+
650
+ # check if the scheduler accepts generator
651
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
652
+ if accepts_generator:
653
+ extra_step_kwargs["generator"] = generator
654
+ return extra_step_kwargs
655
+
656
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_inpaint.StableDiffusionXLInpaintPipeline.check_inputs
657
+ def check_inputs(
658
+ self,
659
+ prompt,
660
+ prompt_2,
661
+ image,
662
+ mask_image,
663
+ height,
664
+ width,
665
+ strength,
666
+ callback_steps,
667
+ output_type,
668
+ negative_prompt=None,
669
+ negative_prompt_2=None,
670
+ prompt_embeds=None,
671
+ negative_prompt_embeds=None,
672
+ ip_adapter_image=None,
673
+ ip_adapter_image_embeds=None,
674
+ callback_on_step_end_tensor_inputs=None,
675
+ padding_mask_crop=None,
676
+ ):
677
+ if strength < 0 or strength > 1:
678
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
679
+
680
+ if height % 8 != 0 or width % 8 != 0:
681
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
682
+
683
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
684
+ raise ValueError(
685
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
686
+ f" {type(callback_steps)}."
687
+ )
688
+
689
+ if callback_on_step_end_tensor_inputs is not None and not all(
690
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
691
+ ):
692
+ raise ValueError(
693
+ 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]}"
694
+ )
695
+
696
+ if prompt is not None and prompt_embeds is not None:
697
+ raise ValueError(
698
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
699
+ " only forward one of the two."
700
+ )
701
+ elif prompt_2 is not None and prompt_embeds is not None:
702
+ raise ValueError(
703
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
704
+ " only forward one of the two."
705
+ )
706
+ elif prompt is None and prompt_embeds is None:
707
+ raise ValueError(
708
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
709
+ )
710
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
711
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
712
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
713
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
714
+
715
+ if negative_prompt is not None and negative_prompt_embeds is not None:
716
+ raise ValueError(
717
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
718
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
719
+ )
720
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
721
+ raise ValueError(
722
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
723
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
724
+ )
725
+
726
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
727
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
728
+ raise ValueError(
729
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
730
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
731
+ f" {negative_prompt_embeds.shape}."
732
+ )
733
+ if padding_mask_crop is not None:
734
+ if not isinstance(image, PIL.Image.Image):
735
+ raise ValueError(
736
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
737
+ )
738
+ if not isinstance(mask_image, PIL.Image.Image):
739
+ raise ValueError(
740
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
741
+ f" {type(mask_image)}."
742
+ )
743
+ if output_type != "pil":
744
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
745
+
746
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
747
+ raise ValueError(
748
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
749
+ )
750
+
751
+ if ip_adapter_image_embeds is not None:
752
+ if not isinstance(ip_adapter_image_embeds, list):
753
+ raise ValueError(
754
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
755
+ )
756
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
757
+ raise ValueError(
758
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
759
+ )
760
+
761
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_inpaint.StableDiffusionXLInpaintPipeline.prepare_latents
762
+ def prepare_latents(
763
+ self,
764
+ batch_size,
765
+ num_channels_latents,
766
+ height,
767
+ width,
768
+ dtype,
769
+ device,
770
+ generator,
771
+ latents=None,
772
+ image=None,
773
+ timestep=None,
774
+ is_strength_max=True,
775
+ add_noise=True,
776
+ return_noise=False,
777
+ return_image_latents=False,
778
+ ):
779
+ shape = (
780
+ batch_size,
781
+ num_channels_latents,
782
+ int(height) // self.vae_scale_factor,
783
+ int(width) // self.vae_scale_factor,
784
+ )
785
+ if isinstance(generator, list) and len(generator) != batch_size:
786
+ raise ValueError(
787
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
788
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
789
+ )
790
+
791
+ if (image is None or timestep is None) and not is_strength_max:
792
+ raise ValueError(
793
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
794
+ "However, either the image or the noise timestep has not been provided."
795
+ )
796
+
797
+ if image.shape[1] == 4:
798
+ image_latents = image.to(device=device, dtype=dtype)
799
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
800
+ elif return_image_latents or (latents is None and not is_strength_max):
801
+ image = image.to(device=device, dtype=dtype)
802
+ image_latents = self._encode_vae_image(image=image, generator=generator)
803
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
804
+
805
+ if latents is None and add_noise:
806
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
807
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
808
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
809
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
810
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
811
+ elif add_noise:
812
+ noise = latents.to(device)
813
+ latents = noise * self.scheduler.init_noise_sigma
814
+ else:
815
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
816
+ latents = image_latents.to(device)
817
+
818
+ outputs = (latents,)
819
+
820
+ if return_noise:
821
+ outputs += (noise,)
822
+
823
+ if return_image_latents:
824
+ outputs += (image_latents,)
825
+
826
+ return outputs
827
+
828
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_inpaint.StableDiffusionXLInpaintPipeline._encode_vae_image
829
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
830
+ dtype = image.dtype
831
+ if self.vae.config.force_upcast:
832
+ image = image.float()
833
+ self.vae.to(dtype=torch.float32)
834
+
835
+ if isinstance(generator, list):
836
+ image_latents = [
837
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
838
+ for i in range(image.shape[0])
839
+ ]
840
+ image_latents = torch.cat(image_latents, dim=0)
841
+ else:
842
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
843
+
844
+ if self.vae.config.force_upcast:
845
+ self.vae.to(dtype)
846
+
847
+ image_latents = image_latents.to(dtype)
848
+ image_latents = self.vae.config.scaling_factor * image_latents
849
+
850
+ return image_latents
851
+
852
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_inpaint.StableDiffusionXLInpaintPipeline.prepare_mask_latents
853
+ def prepare_mask_latents(
854
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
855
+ ):
856
+ # resize the mask to latents shape as we concatenate the mask to the latents
857
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
858
+ # and half precision
859
+ mask = torch.nn.functional.interpolate(
860
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
861
+ )
862
+ mask = mask.to(device=device, dtype=dtype)
863
+
864
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
865
+ if mask.shape[0] < batch_size:
866
+ if not batch_size % mask.shape[0] == 0:
867
+ raise ValueError(
868
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
869
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
870
+ " of masks that you pass is divisible by the total requested batch size."
871
+ )
872
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
873
+
874
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
875
+
876
+ if masked_image is not None and masked_image.shape[1] == 4:
877
+ masked_image_latents = masked_image
878
+ else:
879
+ masked_image_latents = None
880
+
881
+ if masked_image is not None:
882
+ if masked_image_latents is None:
883
+ masked_image = masked_image.to(device=device, dtype=dtype)
884
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
885
+
886
+ if masked_image_latents.shape[0] < batch_size:
887
+ if not batch_size % masked_image_latents.shape[0] == 0:
888
+ raise ValueError(
889
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
890
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
891
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
892
+ )
893
+ masked_image_latents = masked_image_latents.repeat(
894
+ batch_size // masked_image_latents.shape[0], 1, 1, 1
895
+ )
896
+
897
+ masked_image_latents = (
898
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
899
+ )
900
+
901
+ # aligning device to prevent device errors when concating it with the latent model input
902
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
903
+
904
+ return mask, masked_image_latents
905
+
906
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
907
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
908
+ # get the original timestep using init_timestep
909
+ if denoising_start is None:
910
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
911
+ t_start = max(num_inference_steps - init_timestep, 0)
912
+
913
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
914
+ if hasattr(self.scheduler, "set_begin_index"):
915
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
916
+
917
+ return timesteps, num_inference_steps - t_start
918
+
919
+ else:
920
+ # Strength is irrelevant if we directly request a timestep to start at;
921
+ # that is, strength is determined by the denoising_start instead.
922
+ discrete_timestep_cutoff = int(
923
+ round(
924
+ self.scheduler.config.num_train_timesteps
925
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
926
+ )
927
+ )
928
+
929
+ num_inference_steps = (self.scheduler.timesteps < discrete_timestep_cutoff).sum().item()
930
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
931
+ # if the scheduler is a 2nd order scheduler we might have to do +1
932
+ # because `num_inference_steps` might be even given that every timestep
933
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
934
+ # mean that we cut the timesteps in the middle of the denoising step
935
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
936
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
937
+ num_inference_steps = num_inference_steps + 1
938
+
939
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
940
+ t_start = len(self.scheduler.timesteps) - num_inference_steps
941
+ timesteps = self.scheduler.timesteps[t_start:]
942
+ if hasattr(self.scheduler, "set_begin_index"):
943
+ self.scheduler.set_begin_index(t_start)
944
+ return timesteps, num_inference_steps
945
+
946
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids
947
+ def _get_add_time_ids(
948
+ self,
949
+ original_size,
950
+ crops_coords_top_left,
951
+ target_size,
952
+ aesthetic_score,
953
+ negative_aesthetic_score,
954
+ negative_original_size,
955
+ negative_crops_coords_top_left,
956
+ negative_target_size,
957
+ dtype,
958
+ text_encoder_projection_dim=None,
959
+ ):
960
+ if self.config.requires_aesthetics_score:
961
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
962
+ add_neg_time_ids = list(
963
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
964
+ )
965
+ else:
966
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
967
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
968
+
969
+ passed_add_embed_dim = (
970
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
971
+ )
972
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
973
+
974
+ if (
975
+ expected_add_embed_dim > passed_add_embed_dim
976
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
977
+ ):
978
+ raise ValueError(
979
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
980
+ )
981
+ elif (
982
+ expected_add_embed_dim < passed_add_embed_dim
983
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
984
+ ):
985
+ raise ValueError(
986
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
987
+ )
988
+ elif expected_add_embed_dim != passed_add_embed_dim:
989
+ raise ValueError(
990
+ 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`."
991
+ )
992
+
993
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
994
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
995
+
996
+ return add_time_ids, add_neg_time_ids
997
+
998
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
999
+ def upcast_vae(self):
1000
+ dtype = self.vae.dtype
1001
+ self.vae.to(dtype=torch.float32)
1002
+ use_torch_2_0_or_xformers = isinstance(
1003
+ self.vae.decoder.mid_block.attentions[0].processor,
1004
+ (
1005
+ AttnProcessor2_0,
1006
+ XFormersAttnProcessor,
1007
+ ),
1008
+ )
1009
+ # if xformers or torch_2_0 is used attention block does not need
1010
+ # to be in float32 which can save lots of memory
1011
+ if use_torch_2_0_or_xformers:
1012
+ self.vae.post_quant_conv.to(dtype)
1013
+ self.vae.decoder.conv_in.to(dtype)
1014
+ self.vae.decoder.mid_block.to(dtype)
1015
+
1016
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1017
+ def get_guidance_scale_embedding(
1018
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1019
+ ) -> torch.Tensor:
1020
+ """
1021
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1022
+
1023
+ Args:
1024
+ w (`torch.Tensor`):
1025
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1026
+ embedding_dim (`int`, *optional*, defaults to 512):
1027
+ Dimension of the embeddings to generate.
1028
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1029
+ Data type of the generated embeddings.
1030
+
1031
+ Returns:
1032
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1033
+ """
1034
+ assert len(w.shape) == 1
1035
+ w = w * 1000.0
1036
+
1037
+ half_dim = embedding_dim // 2
1038
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1039
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1040
+ emb = w.to(dtype)[:, None] * emb[None, :]
1041
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1042
+ if embedding_dim % 2 == 1: # zero pad
1043
+ emb = torch.nn.functional.pad(emb, (0, 1))
1044
+ assert emb.shape == (w.shape[0], embedding_dim)
1045
+ return emb
1046
+
1047
+ @property
1048
+ def guidance_scale(self):
1049
+ return self._guidance_scale
1050
+
1051
+ @property
1052
+ def guidance_rescale(self):
1053
+ return self._guidance_rescale
1054
+
1055
+ @property
1056
+ def clip_skip(self):
1057
+ return self._clip_skip
1058
+
1059
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1060
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1061
+ # corresponds to doing no classifier free guidance.
1062
+ @property
1063
+ def do_classifier_free_guidance(self):
1064
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1065
+
1066
+ @property
1067
+ def cross_attention_kwargs(self):
1068
+ return self._cross_attention_kwargs
1069
+
1070
+ @property
1071
+ def denoising_end(self):
1072
+ return self._denoising_end
1073
+
1074
+ @property
1075
+ def denoising_start(self):
1076
+ return self._denoising_start
1077
+
1078
+ @property
1079
+ def num_timesteps(self):
1080
+ return self._num_timesteps
1081
+
1082
+ @property
1083
+ def interrupt(self):
1084
+ return self._interrupt
1085
+
1086
+ @torch.no_grad()
1087
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1088
+ def __call__(
1089
+ self,
1090
+ prompt: Union[str, List[str]] = None,
1091
+ prompt_2: Optional[Union[str, List[str]]] = None,
1092
+ image: PipelineImageInput = None,
1093
+ mask_image: PipelineImageInput = None,
1094
+ masked_image_latents: torch.Tensor = None,
1095
+ height: Optional[int] = None,
1096
+ width: Optional[int] = None,
1097
+ padding_mask_crop: Optional[int] = None,
1098
+ strength: float = 0.9999,
1099
+ num_inference_steps: int = 50,
1100
+ timesteps: List[int] = None,
1101
+ sigmas: List[float] = None,
1102
+ denoising_start: Optional[float] = None,
1103
+ denoising_end: Optional[float] = None,
1104
+ guidance_scale: float = 7.5,
1105
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1106
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1107
+ num_images_per_prompt: Optional[int] = 1,
1108
+ eta: float = 0.0,
1109
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1110
+ latents: Optional[torch.Tensor] = None,
1111
+ prompt_embeds: Optional[torch.Tensor] = None,
1112
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1113
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1114
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1115
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1116
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1117
+ output_type: Optional[str] = "pil",
1118
+ return_dict: bool = True,
1119
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1120
+ guidance_rescale: float = 0.0,
1121
+ original_size: Tuple[int, int] = None,
1122
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1123
+ target_size: Tuple[int, int] = None,
1124
+ negative_original_size: Optional[Tuple[int, int]] = None,
1125
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1126
+ negative_target_size: Optional[Tuple[int, int]] = None,
1127
+ aesthetic_score: float = 6.0,
1128
+ negative_aesthetic_score: float = 2.5,
1129
+ clip_skip: Optional[int] = None,
1130
+ callback_on_step_end: Optional[
1131
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1132
+ ] = None,
1133
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1134
+ pag_scale: float = 3.0,
1135
+ pag_adaptive_scale: float = 0.0,
1136
+ ):
1137
+ r"""
1138
+ Function invoked when calling the pipeline for generation.
1139
+
1140
+ Args:
1141
+ prompt (`str` or `List[str]`, *optional*):
1142
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1143
+ instead.
1144
+ prompt_2 (`str` or `List[str]`, *optional*):
1145
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1146
+ used in both text-encoders
1147
+ image (`PIL.Image.Image`):
1148
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
1149
+ be masked out with `mask_image` and repainted according to `prompt`.
1150
+ mask_image (`PIL.Image.Image`):
1151
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1152
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
1153
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
1154
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
1155
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1156
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
1157
+ Anything below 512 pixels won't work well for
1158
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1159
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1160
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1161
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
1162
+ Anything below 512 pixels won't work well for
1163
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1164
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1165
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
1166
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
1167
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
1168
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
1169
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
1170
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
1171
+ the image is large and contain information irrelevant for inpainting, such as background.
1172
+ strength (`float`, *optional*, defaults to 0.9999):
1173
+ Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be
1174
+ between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the
1175
+ `strength`. The number of denoising steps depends on the amount of noise initially added. When
1176
+ `strength` is 1, added noise will be maximum and the denoising process will run for the full number of
1177
+ iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked
1178
+ portion of the reference `image`. Note that in the case of `denoising_start` being declared as an
1179
+ integer, the value of `strength` will be ignored.
1180
+ num_inference_steps (`int`, *optional*, defaults to 50):
1181
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1182
+ expense of slower inference.
1183
+ timesteps (`List[int]`, *optional*):
1184
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1185
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1186
+ passed will be used. Must be in descending order.
1187
+ sigmas (`List[float]`, *optional*):
1188
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1189
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1190
+ will be used.
1191
+ denoising_start (`float`, *optional*):
1192
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1193
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1194
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1195
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1196
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1197
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1198
+ denoising_end (`float`, *optional*):
1199
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1200
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1201
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1202
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1203
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1204
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1205
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1206
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1207
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1208
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1209
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1210
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1211
+ usually at the expense of lower image quality.
1212
+ negative_prompt (`str` or `List[str]`, *optional*):
1213
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1214
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1215
+ less than `1`).
1216
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1217
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1218
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1219
+ prompt_embeds (`torch.Tensor`, *optional*):
1220
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1221
+ provided, text embeddings will be generated from `prompt` input argument.
1222
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1223
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1224
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1225
+ argument.
1226
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1227
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1228
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1229
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1230
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1231
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1232
+ input argument.
1233
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1234
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1235
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1236
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1237
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1238
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1239
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1240
+ The number of images to generate per prompt.
1241
+ eta (`float`, *optional*, defaults to 0.0):
1242
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1243
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1244
+ generator (`torch.Generator`, *optional*):
1245
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1246
+ to make generation deterministic.
1247
+ latents (`torch.Tensor`, *optional*):
1248
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1249
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1250
+ tensor will ge generated by sampling using the supplied random `generator`.
1251
+ output_type (`str`, *optional*, defaults to `"pil"`):
1252
+ The output format of the generate image. Choose between
1253
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1254
+ return_dict (`bool`, *optional*, defaults to `True`):
1255
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1256
+ plain tuple.
1257
+ cross_attention_kwargs (`dict`, *optional*):
1258
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1259
+ `self.processor` in
1260
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1261
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1262
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1263
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1264
+ explained in section 2.2 of
1265
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1266
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1267
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1268
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1269
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1270
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1271
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1272
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1273
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1274
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1275
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1276
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1277
+ micro-conditioning as explained in section 2.2 of
1278
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1279
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1280
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1281
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1282
+ micro-conditioning as explained in section 2.2 of
1283
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1284
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1285
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1286
+ To negatively condition the generation process based on a target image resolution. It should be as same
1287
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1288
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1289
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1290
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1291
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1292
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1293
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1294
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1295
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1296
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1297
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1298
+ clip_skip (`int`, *optional*):
1299
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1300
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1301
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1302
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1303
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1304
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1305
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1306
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1307
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1308
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1309
+ `._callback_tensor_inputs` attribute of your pipeline class.
1310
+ pag_scale (`float`, *optional*, defaults to 3.0):
1311
+ The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
1312
+ guidance will not be used.
1313
+ pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
1314
+ The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
1315
+ used.
1316
+
1317
+ Examples:
1318
+
1319
+ Returns:
1320
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1321
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1322
+ `tuple. `tuple. When returning a tuple, the first element is a list with the generated images.
1323
+ """
1324
+
1325
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1326
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1327
+
1328
+ # 0. Default height and width to unet
1329
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1330
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1331
+
1332
+ # 1. Check inputs
1333
+ self.check_inputs(
1334
+ prompt,
1335
+ prompt_2,
1336
+ image,
1337
+ mask_image,
1338
+ height,
1339
+ width,
1340
+ strength,
1341
+ None,
1342
+ output_type,
1343
+ negative_prompt,
1344
+ negative_prompt_2,
1345
+ prompt_embeds,
1346
+ negative_prompt_embeds,
1347
+ ip_adapter_image,
1348
+ ip_adapter_image_embeds,
1349
+ callback_on_step_end_tensor_inputs,
1350
+ padding_mask_crop,
1351
+ )
1352
+
1353
+ self._guidance_scale = guidance_scale
1354
+ self._guidance_rescale = guidance_rescale
1355
+ self._clip_skip = clip_skip
1356
+ self._cross_attention_kwargs = cross_attention_kwargs
1357
+ self._denoising_end = denoising_end
1358
+ self._denoising_start = denoising_start
1359
+ self._interrupt = False
1360
+ self._pag_scale = pag_scale
1361
+ self._pag_adaptive_scale = pag_adaptive_scale
1362
+
1363
+ # 2. Define call parameters
1364
+ if prompt is not None and isinstance(prompt, str):
1365
+ batch_size = 1
1366
+ elif prompt is not None and isinstance(prompt, list):
1367
+ batch_size = len(prompt)
1368
+ else:
1369
+ batch_size = prompt_embeds.shape[0]
1370
+
1371
+ device = self._execution_device
1372
+
1373
+ # 3. Encode input prompt
1374
+ text_encoder_lora_scale = (
1375
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1376
+ )
1377
+
1378
+ (
1379
+ prompt_embeds,
1380
+ negative_prompt_embeds,
1381
+ pooled_prompt_embeds,
1382
+ negative_pooled_prompt_embeds,
1383
+ ) = self.encode_prompt(
1384
+ prompt=prompt,
1385
+ prompt_2=prompt_2,
1386
+ device=device,
1387
+ num_images_per_prompt=num_images_per_prompt,
1388
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1389
+ negative_prompt=negative_prompt,
1390
+ negative_prompt_2=negative_prompt_2,
1391
+ prompt_embeds=prompt_embeds,
1392
+ negative_prompt_embeds=negative_prompt_embeds,
1393
+ pooled_prompt_embeds=pooled_prompt_embeds,
1394
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1395
+ lora_scale=text_encoder_lora_scale,
1396
+ clip_skip=self.clip_skip,
1397
+ )
1398
+
1399
+ # 4. set timesteps
1400
+ def denoising_value_valid(dnv):
1401
+ return isinstance(dnv, float) and 0 < dnv < 1
1402
+
1403
+ timesteps, num_inference_steps = retrieve_timesteps(
1404
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1405
+ )
1406
+ timesteps, num_inference_steps = self.get_timesteps(
1407
+ num_inference_steps,
1408
+ strength,
1409
+ device,
1410
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1411
+ )
1412
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1413
+ if num_inference_steps < 1:
1414
+ raise ValueError(
1415
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1416
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1417
+ )
1418
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1419
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1420
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1421
+ is_strength_max = strength == 1.0
1422
+
1423
+ # 5. Preprocess mask and image
1424
+ if padding_mask_crop is not None:
1425
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
1426
+ resize_mode = "fill"
1427
+ else:
1428
+ crops_coords = None
1429
+ resize_mode = "default"
1430
+
1431
+ original_image = image
1432
+ init_image = self.image_processor.preprocess(
1433
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
1434
+ )
1435
+ init_image = init_image.to(dtype=torch.float32)
1436
+
1437
+ mask = self.mask_processor.preprocess(
1438
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
1439
+ )
1440
+
1441
+ if masked_image_latents is not None:
1442
+ masked_image = masked_image_latents
1443
+ elif init_image.shape[1] == 4:
1444
+ # if images are in latent space, we can't mask it
1445
+ masked_image = None
1446
+ else:
1447
+ masked_image = init_image * (mask < 0.5)
1448
+
1449
+ # 6. Prepare latent variables
1450
+ num_channels_latents = self.vae.config.latent_channels
1451
+ num_channels_unet = self.unet.config.in_channels
1452
+ return_image_latents = num_channels_unet == 4
1453
+
1454
+ add_noise = True if self.denoising_start is None else False
1455
+ latents_outputs = self.prepare_latents(
1456
+ batch_size * num_images_per_prompt,
1457
+ num_channels_latents,
1458
+ height,
1459
+ width,
1460
+ prompt_embeds.dtype,
1461
+ device,
1462
+ generator,
1463
+ latents,
1464
+ image=init_image,
1465
+ timestep=latent_timestep,
1466
+ is_strength_max=is_strength_max,
1467
+ add_noise=add_noise,
1468
+ return_noise=True,
1469
+ return_image_latents=return_image_latents,
1470
+ )
1471
+
1472
+ if return_image_latents:
1473
+ latents, noise, image_latents = latents_outputs
1474
+ else:
1475
+ latents, noise = latents_outputs
1476
+
1477
+ # 7. Prepare mask latent variables
1478
+ mask, masked_image_latents = self.prepare_mask_latents(
1479
+ mask,
1480
+ masked_image,
1481
+ batch_size * num_images_per_prompt,
1482
+ height,
1483
+ width,
1484
+ prompt_embeds.dtype,
1485
+ device,
1486
+ generator,
1487
+ self.do_classifier_free_guidance,
1488
+ )
1489
+ if self.do_perturbed_attention_guidance:
1490
+ if self.do_classifier_free_guidance:
1491
+ mask, _ = mask.chunk(2)
1492
+ masked_image_latents, _ = masked_image_latents.chunk(2)
1493
+ mask = self._prepare_perturbed_attention_guidance(mask, mask, self.do_classifier_free_guidance)
1494
+ masked_image_latents = self._prepare_perturbed_attention_guidance(
1495
+ masked_image_latents, masked_image_latents, self.do_classifier_free_guidance
1496
+ )
1497
+
1498
+ # 8. Check that sizes of mask, masked image and latents match
1499
+ if num_channels_unet == 9:
1500
+ # default case for runwayml/stable-diffusion-inpainting
1501
+ num_channels_mask = mask.shape[1]
1502
+ num_channels_masked_image = masked_image_latents.shape[1]
1503
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1504
+ raise ValueError(
1505
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1506
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1507
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1508
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1509
+ " `pipeline.unet` or your `mask_image` or `image` input."
1510
+ )
1511
+ elif num_channels_unet != 4:
1512
+ raise ValueError(
1513
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1514
+ )
1515
+ # 8.1 Prepare extra step kwargs.
1516
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1517
+
1518
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1519
+ height, width = latents.shape[-2:]
1520
+ height = height * self.vae_scale_factor
1521
+ width = width * self.vae_scale_factor
1522
+
1523
+ original_size = original_size or (height, width)
1524
+ target_size = target_size or (height, width)
1525
+
1526
+ # 10. Prepare added time ids & embeddings
1527
+ if negative_original_size is None:
1528
+ negative_original_size = original_size
1529
+ if negative_target_size is None:
1530
+ negative_target_size = target_size
1531
+
1532
+ add_text_embeds = pooled_prompt_embeds
1533
+ if self.text_encoder_2 is None:
1534
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1535
+ else:
1536
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1537
+
1538
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1539
+ original_size,
1540
+ crops_coords_top_left,
1541
+ target_size,
1542
+ aesthetic_score,
1543
+ negative_aesthetic_score,
1544
+ negative_original_size,
1545
+ negative_crops_coords_top_left,
1546
+ negative_target_size,
1547
+ dtype=prompt_embeds.dtype,
1548
+ text_encoder_projection_dim=text_encoder_projection_dim,
1549
+ )
1550
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1551
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1552
+
1553
+ if self.do_perturbed_attention_guidance:
1554
+ prompt_embeds = self._prepare_perturbed_attention_guidance(
1555
+ prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
1556
+ )
1557
+ add_text_embeds = self._prepare_perturbed_attention_guidance(
1558
+ add_text_embeds, negative_pooled_prompt_embeds, self.do_classifier_free_guidance
1559
+ )
1560
+ add_time_ids = self._prepare_perturbed_attention_guidance(
1561
+ add_time_ids, add_neg_time_ids, self.do_classifier_free_guidance
1562
+ )
1563
+
1564
+ elif self.do_classifier_free_guidance:
1565
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1566
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1567
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1568
+
1569
+ prompt_embeds = prompt_embeds.to(device)
1570
+ add_text_embeds = add_text_embeds.to(device)
1571
+ add_time_ids = add_time_ids.to(device)
1572
+
1573
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1574
+ ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
1575
+ ip_adapter_image,
1576
+ ip_adapter_image_embeds,
1577
+ device,
1578
+ batch_size * num_images_per_prompt,
1579
+ self.do_classifier_free_guidance,
1580
+ )
1581
+ for i, image_embeds in enumerate(ip_adapter_image_embeds):
1582
+ negative_image_embeds = None
1583
+ if self.do_classifier_free_guidance:
1584
+ negative_image_embeds, image_embeds = image_embeds.chunk(2)
1585
+
1586
+ if self.do_perturbed_attention_guidance:
1587
+ image_embeds = self._prepare_perturbed_attention_guidance(
1588
+ image_embeds, negative_image_embeds, self.do_classifier_free_guidance
1589
+ )
1590
+ elif self.do_classifier_free_guidance:
1591
+ image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
1592
+ image_embeds = image_embeds.to(device)
1593
+ ip_adapter_image_embeds[i] = image_embeds
1594
+
1595
+ # 11. Denoising loop
1596
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1597
+
1598
+ if (
1599
+ self.denoising_end is not None
1600
+ and self.denoising_start is not None
1601
+ and denoising_value_valid(self.denoising_end)
1602
+ and denoising_value_valid(self.denoising_start)
1603
+ and self.denoising_start >= self.denoising_end
1604
+ ):
1605
+ raise ValueError(
1606
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1607
+ + f" {self.denoising_end} when using type float."
1608
+ )
1609
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1610
+ discrete_timestep_cutoff = int(
1611
+ round(
1612
+ self.scheduler.config.num_train_timesteps
1613
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1614
+ )
1615
+ )
1616
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1617
+ timesteps = timesteps[:num_inference_steps]
1618
+
1619
+ # 11.1 Optionally get Guidance Scale Embedding
1620
+ timestep_cond = None
1621
+ if self.unet.config.time_cond_proj_dim is not None:
1622
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1623
+ timestep_cond = self.get_guidance_scale_embedding(
1624
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1625
+ ).to(device=device, dtype=latents.dtype)
1626
+
1627
+ if self.do_perturbed_attention_guidance:
1628
+ original_attn_proc = self.unet.attn_processors
1629
+ self._set_pag_attn_processor(
1630
+ pag_applied_layers=self.pag_applied_layers,
1631
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1632
+ )
1633
+
1634
+ self._num_timesteps = len(timesteps)
1635
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1636
+ for i, t in enumerate(timesteps):
1637
+ if self.interrupt:
1638
+ continue
1639
+ # expand the latents if we are doing classifier free guidance
1640
+ latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
1641
+
1642
+ # concat latents, mask, masked_image_latents in the channel dimension
1643
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1644
+
1645
+ if num_channels_unet == 9:
1646
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1647
+
1648
+ # predict the noise residual
1649
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1650
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1651
+ added_cond_kwargs["image_embeds"] = ip_adapter_image_embeds
1652
+ noise_pred = self.unet(
1653
+ latent_model_input,
1654
+ t,
1655
+ encoder_hidden_states=prompt_embeds,
1656
+ timestep_cond=timestep_cond,
1657
+ cross_attention_kwargs=self.cross_attention_kwargs,
1658
+ added_cond_kwargs=added_cond_kwargs,
1659
+ return_dict=False,
1660
+ )[0]
1661
+
1662
+ # perform guidance
1663
+ if self.do_perturbed_attention_guidance:
1664
+ noise_pred, noise_pred_text = self._apply_perturbed_attention_guidance(
1665
+ noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t, True
1666
+ )
1667
+ elif self.do_classifier_free_guidance:
1668
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1669
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1670
+
1671
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1672
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1673
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1674
+
1675
+ # compute the previous noisy sample x_t -> x_t-1
1676
+ latents_dtype = latents.dtype
1677
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1678
+ if latents.dtype != latents_dtype:
1679
+ if torch.backends.mps.is_available():
1680
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1681
+ latents = latents.to(latents_dtype)
1682
+
1683
+ if num_channels_unet == 4:
1684
+ init_latents_proper = image_latents
1685
+ if self.do_perturbed_attention_guidance:
1686
+ init_mask, *_ = mask.chunk(3) if self.do_classifier_free_guidance else mask.chunk(2)
1687
+ else:
1688
+ init_mask, *_ = mask.chunk(2) if self.do_classifier_free_guidance else mask
1689
+
1690
+ if i < len(timesteps) - 1:
1691
+ noise_timestep = timesteps[i + 1]
1692
+ init_latents_proper = self.scheduler.add_noise(
1693
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1694
+ )
1695
+
1696
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1697
+
1698
+ if callback_on_step_end is not None:
1699
+ callback_kwargs = {}
1700
+ for k in callback_on_step_end_tensor_inputs:
1701
+ callback_kwargs[k] = locals()[k]
1702
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1703
+
1704
+ latents = callback_outputs.pop("latents", latents)
1705
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1706
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1707
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1708
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1709
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1710
+ )
1711
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1712
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1713
+ mask = callback_outputs.pop("mask", mask)
1714
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
1715
+
1716
+ # call the callback, if provided
1717
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1718
+ progress_bar.update()
1719
+
1720
+ if XLA_AVAILABLE:
1721
+ xm.mark_step()
1722
+
1723
+ if not output_type == "latent":
1724
+ # make sure the VAE is in float32 mode, as it overflows in float16
1725
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1726
+
1727
+ if needs_upcasting:
1728
+ self.upcast_vae()
1729
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1730
+ elif latents.dtype != self.vae.dtype:
1731
+ if torch.backends.mps.is_available():
1732
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1733
+ self.vae = self.vae.to(latents.dtype)
1734
+
1735
+ # unscale/denormalize the latents
1736
+ # denormalize with the mean and std if available and not None
1737
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1738
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1739
+ if has_latents_mean and has_latents_std:
1740
+ latents_mean = (
1741
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1742
+ )
1743
+ latents_std = (
1744
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1745
+ )
1746
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1747
+ else:
1748
+ latents = latents / self.vae.config.scaling_factor
1749
+
1750
+ image = self.vae.decode(latents, return_dict=False)[0]
1751
+
1752
+ # cast back to fp16 if needed
1753
+ if needs_upcasting:
1754
+ self.vae.to(dtype=torch.float16)
1755
+ else:
1756
+ return StableDiffusionXLPipelineOutput(images=latents)
1757
+
1758
+ # apply watermark if available
1759
+ if self.watermark is not None:
1760
+ image = self.watermark.apply_watermark(image)
1761
+
1762
+ image = self.image_processor.postprocess(image, output_type=output_type)
1763
+
1764
+ if padding_mask_crop is not None:
1765
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
1766
+
1767
+ # Offload all models
1768
+ self.maybe_free_model_hooks()
1769
+
1770
+ if self.do_perturbed_attention_guidance:
1771
+ self.unet.set_attn_processor(original_attn_proc)
1772
+
1773
+ if not return_dict:
1774
+ return (image,)
1775
+
1776
+ return StableDiffusionXLPipelineOutput(images=image)