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,1790 @@
1
+ # Copyright 2024 Harutatsu Akiyama, Jinbin Bai, and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ CLIPVisionModelWithProjection,
28
+ )
29
+
30
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
31
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
32
+ from ...loaders import (
33
+ FromSingleFileMixin,
34
+ IPAdapterMixin,
35
+ StableDiffusionXLLoraLoaderMixin,
36
+ TextualInversionLoaderMixin,
37
+ )
38
+ from ...models import AutoencoderKL, ControlNetModel, ControlNetUnionModel, ImageProjection, UNet2DConditionModel
39
+ from ...models.attention_processor import (
40
+ AttnProcessor2_0,
41
+ XFormersAttnProcessor,
42
+ )
43
+ from ...models.lora import adjust_lora_scale_text_encoder
44
+ from ...schedulers import KarrasDiffusionSchedulers
45
+ from ...utils import (
46
+ USE_PEFT_BACKEND,
47
+ deprecate,
48
+ is_invisible_watermark_available,
49
+ logging,
50
+ replace_example_docstring,
51
+ scale_lora_layers,
52
+ unscale_lora_layers,
53
+ )
54
+ from ...utils.torch_utils import is_compiled_module, randn_tensor
55
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
56
+ from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
57
+
58
+
59
+ if is_invisible_watermark_available():
60
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
61
+
62
+
63
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
64
+
65
+
66
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
67
+ def retrieve_latents(
68
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
69
+ ):
70
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
71
+ return encoder_output.latent_dist.sample(generator)
72
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
73
+ return encoder_output.latent_dist.mode()
74
+ elif hasattr(encoder_output, "latents"):
75
+ return encoder_output.latents
76
+ else:
77
+ raise AttributeError("Could not access latents of provided encoder_output")
78
+
79
+
80
+ EXAMPLE_DOC_STRING = """
81
+ Examples:
82
+ ```py
83
+ from diffusers import StableDiffusionXLControlNetUnionInpaintPipeline, ControlNetUnionModel, AutoencoderKL
84
+ from diffusers.utils import load_image
85
+ import torch
86
+ import numpy as np
87
+ from PIL import Image
88
+
89
+ prompt = "A cat"
90
+ # download an image
91
+ image = load_image(
92
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo.png"
93
+ ).resize((1024, 1024))
94
+ mask = load_image(
95
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo_mask.png"
96
+ ).resize((1024, 1024))
97
+ # initialize the models and pipeline
98
+ controlnet = ControlNetUnionModel.from_pretrained(
99
+ "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
100
+ )
101
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
102
+ pipe = StableDiffusionXLControlNetUnionInpaintPipeline.from_pretrained(
103
+ "stabilityai/stable-diffusion-xl-base-1.0",
104
+ controlnet=controlnet,
105
+ vae=vae,
106
+ torch_dtype=torch.float16,
107
+ variant="fp16",
108
+ )
109
+ pipe.enable_model_cpu_offload()
110
+ controlnet_img = image.copy()
111
+ controlnet_img_np = np.array(controlnet_img)
112
+ mask_np = np.array(mask)
113
+ controlnet_img_np[mask_np > 0] = 0
114
+ controlnet_img = Image.fromarray(controlnet_img_np)
115
+ # generate image
116
+ image = pipe(prompt, image=image, mask_image=mask, control_image=[controlnet_img], control_mode=[7]).images[0]
117
+ image.save("inpaint.png")
118
+ ```
119
+ """
120
+
121
+
122
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
123
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
124
+ r"""
125
+ Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
126
+ Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
127
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf).
128
+
129
+ Args:
130
+ noise_cfg (`torch.Tensor`):
131
+ The predicted noise tensor for the guided diffusion process.
132
+ noise_pred_text (`torch.Tensor`):
133
+ The predicted noise tensor for the text-guided diffusion process.
134
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
135
+ A rescale factor applied to the noise predictions.
136
+
137
+ Returns:
138
+ noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
139
+ """
140
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
141
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
142
+ # rescale the results from guidance (fixes overexposure)
143
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
144
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
145
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
146
+ return noise_cfg
147
+
148
+
149
+ class StableDiffusionXLControlNetUnionInpaintPipeline(
150
+ DiffusionPipeline,
151
+ StableDiffusionMixin,
152
+ StableDiffusionXLLoraLoaderMixin,
153
+ FromSingleFileMixin,
154
+ IPAdapterMixin,
155
+ TextualInversionLoaderMixin,
156
+ ):
157
+ r"""
158
+ Pipeline for text-to-image generation using Stable Diffusion XL.
159
+
160
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
161
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
162
+
163
+ The pipeline also inherits the following loading methods:
164
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
165
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
166
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
167
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
168
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
169
+
170
+ Args:
171
+ vae ([`AutoencoderKL`]):
172
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
173
+ text_encoder ([`CLIPTextModel`]):
174
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
175
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
176
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
177
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
178
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
179
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
180
+ specifically the
181
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
182
+ variant.
183
+ tokenizer (`CLIPTokenizer`):
184
+ Tokenizer of class
185
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
186
+ tokenizer_2 (`CLIPTokenizer`):
187
+ Second Tokenizer of class
188
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
189
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
190
+ scheduler ([`SchedulerMixin`]):
191
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
192
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
193
+ """
194
+
195
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
196
+
197
+ _optional_components = [
198
+ "tokenizer",
199
+ "tokenizer_2",
200
+ "text_encoder",
201
+ "text_encoder_2",
202
+ "image_encoder",
203
+ "feature_extractor",
204
+ ]
205
+ _callback_tensor_inputs = [
206
+ "latents",
207
+ "prompt_embeds",
208
+ "add_text_embeds",
209
+ "add_time_ids",
210
+ "mask",
211
+ "masked_image_latents",
212
+ ]
213
+
214
+ def __init__(
215
+ self,
216
+ vae: AutoencoderKL,
217
+ text_encoder: CLIPTextModel,
218
+ text_encoder_2: CLIPTextModelWithProjection,
219
+ tokenizer: CLIPTokenizer,
220
+ tokenizer_2: CLIPTokenizer,
221
+ unet: UNet2DConditionModel,
222
+ controlnet: ControlNetUnionModel,
223
+ scheduler: KarrasDiffusionSchedulers,
224
+ requires_aesthetics_score: bool = False,
225
+ force_zeros_for_empty_prompt: bool = True,
226
+ add_watermarker: Optional[bool] = None,
227
+ feature_extractor: Optional[CLIPImageProcessor] = None,
228
+ image_encoder: Optional[CLIPVisionModelWithProjection] = None,
229
+ ):
230
+ super().__init__()
231
+
232
+ if not isinstance(controlnet, ControlNetUnionModel):
233
+ raise ValueError("Expected `controlnet` to be of type `ControlNetUnionModel`.")
234
+
235
+ self.register_modules(
236
+ vae=vae,
237
+ text_encoder=text_encoder,
238
+ text_encoder_2=text_encoder_2,
239
+ tokenizer=tokenizer,
240
+ tokenizer_2=tokenizer_2,
241
+ unet=unet,
242
+ controlnet=controlnet,
243
+ scheduler=scheduler,
244
+ feature_extractor=feature_extractor,
245
+ image_encoder=image_encoder,
246
+ )
247
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
248
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
249
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
250
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
251
+ self.mask_processor = VaeImageProcessor(
252
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
253
+ )
254
+ self.control_image_processor = VaeImageProcessor(
255
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
256
+ )
257
+
258
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
259
+
260
+ if add_watermarker:
261
+ self.watermark = StableDiffusionXLWatermarker()
262
+ else:
263
+ self.watermark = None
264
+
265
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
266
+ def encode_prompt(
267
+ self,
268
+ prompt: str,
269
+ prompt_2: Optional[str] = None,
270
+ device: Optional[torch.device] = None,
271
+ num_images_per_prompt: int = 1,
272
+ do_classifier_free_guidance: bool = True,
273
+ negative_prompt: Optional[str] = None,
274
+ negative_prompt_2: Optional[str] = None,
275
+ prompt_embeds: Optional[torch.Tensor] = None,
276
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
277
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
278
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
279
+ lora_scale: Optional[float] = None,
280
+ clip_skip: Optional[int] = None,
281
+ ):
282
+ r"""
283
+ Encodes the prompt into text encoder hidden states.
284
+
285
+ Args:
286
+ prompt (`str` or `List[str]`, *optional*):
287
+ prompt to be encoded
288
+ prompt_2 (`str` or `List[str]`, *optional*):
289
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
290
+ used in both text-encoders
291
+ device: (`torch.device`):
292
+ torch device
293
+ num_images_per_prompt (`int`):
294
+ number of images that should be generated per prompt
295
+ do_classifier_free_guidance (`bool`):
296
+ whether to use classifier free guidance or not
297
+ negative_prompt (`str` or `List[str]`, *optional*):
298
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
299
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
300
+ less than `1`).
301
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
302
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
303
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
304
+ prompt_embeds (`torch.Tensor`, *optional*):
305
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
306
+ provided, text embeddings will be generated from `prompt` input argument.
307
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
308
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
309
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
310
+ argument.
311
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
312
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
313
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
314
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
315
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
316
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
317
+ input argument.
318
+ lora_scale (`float`, *optional*):
319
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
320
+ clip_skip (`int`, *optional*):
321
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
322
+ the output of the pre-final layer will be used for computing the prompt embeddings.
323
+ """
324
+ device = device or self._execution_device
325
+
326
+ # set lora scale so that monkey patched LoRA
327
+ # function of text encoder can correctly access it
328
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
329
+ self._lora_scale = lora_scale
330
+
331
+ # dynamically adjust the LoRA scale
332
+ if self.text_encoder is not None:
333
+ if not USE_PEFT_BACKEND:
334
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
335
+ else:
336
+ scale_lora_layers(self.text_encoder, lora_scale)
337
+
338
+ if self.text_encoder_2 is not None:
339
+ if not USE_PEFT_BACKEND:
340
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
341
+ else:
342
+ scale_lora_layers(self.text_encoder_2, lora_scale)
343
+
344
+ prompt = [prompt] if isinstance(prompt, str) else prompt
345
+
346
+ if prompt is not None:
347
+ batch_size = len(prompt)
348
+ else:
349
+ batch_size = prompt_embeds.shape[0]
350
+
351
+ # Define tokenizers and text encoders
352
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
353
+ text_encoders = (
354
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
355
+ )
356
+
357
+ if prompt_embeds is None:
358
+ prompt_2 = prompt_2 or prompt
359
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
360
+
361
+ # textual inversion: process multi-vector tokens if necessary
362
+ prompt_embeds_list = []
363
+ prompts = [prompt, prompt_2]
364
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
365
+ if isinstance(self, TextualInversionLoaderMixin):
366
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
367
+
368
+ text_inputs = tokenizer(
369
+ prompt,
370
+ padding="max_length",
371
+ max_length=tokenizer.model_max_length,
372
+ truncation=True,
373
+ return_tensors="pt",
374
+ )
375
+
376
+ text_input_ids = text_inputs.input_ids
377
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
378
+
379
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
380
+ text_input_ids, untruncated_ids
381
+ ):
382
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
383
+ logger.warning(
384
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
385
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
386
+ )
387
+
388
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
389
+
390
+ # We are only ALWAYS interested in the pooled output of the final text encoder
391
+ pooled_prompt_embeds = prompt_embeds[0]
392
+ if clip_skip is None:
393
+ prompt_embeds = prompt_embeds.hidden_states[-2]
394
+ else:
395
+ # "2" because SDXL always indexes from the penultimate layer.
396
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
397
+
398
+ prompt_embeds_list.append(prompt_embeds)
399
+
400
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
401
+
402
+ # get unconditional embeddings for classifier free guidance
403
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
404
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
405
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
406
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
407
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
408
+ negative_prompt = negative_prompt or ""
409
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
410
+
411
+ # normalize str to list
412
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
413
+ negative_prompt_2 = (
414
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
415
+ )
416
+
417
+ uncond_tokens: List[str]
418
+ if prompt is not None and type(prompt) is not type(negative_prompt):
419
+ raise TypeError(
420
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
421
+ f" {type(prompt)}."
422
+ )
423
+ elif batch_size != len(negative_prompt):
424
+ raise ValueError(
425
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
426
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
427
+ " the batch size of `prompt`."
428
+ )
429
+ else:
430
+ uncond_tokens = [negative_prompt, negative_prompt_2]
431
+
432
+ negative_prompt_embeds_list = []
433
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
434
+ if isinstance(self, TextualInversionLoaderMixin):
435
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
436
+
437
+ max_length = prompt_embeds.shape[1]
438
+ uncond_input = tokenizer(
439
+ negative_prompt,
440
+ padding="max_length",
441
+ max_length=max_length,
442
+ truncation=True,
443
+ return_tensors="pt",
444
+ )
445
+
446
+ negative_prompt_embeds = text_encoder(
447
+ uncond_input.input_ids.to(device),
448
+ output_hidden_states=True,
449
+ )
450
+ # We are only ALWAYS interested in the pooled output of the final text encoder
451
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
452
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
453
+
454
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
455
+
456
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
457
+
458
+ if self.text_encoder_2 is not None:
459
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
460
+ else:
461
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
462
+
463
+ bs_embed, seq_len, _ = prompt_embeds.shape
464
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
465
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
466
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
467
+
468
+ if do_classifier_free_guidance:
469
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
470
+ seq_len = negative_prompt_embeds.shape[1]
471
+
472
+ if self.text_encoder_2 is not None:
473
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
474
+ else:
475
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
476
+
477
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
478
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
479
+
480
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
481
+ bs_embed * num_images_per_prompt, -1
482
+ )
483
+ if do_classifier_free_guidance:
484
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
485
+ bs_embed * num_images_per_prompt, -1
486
+ )
487
+
488
+ if self.text_encoder is not None:
489
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
490
+ # Retrieve the original scale by scaling back the LoRA layers
491
+ unscale_lora_layers(self.text_encoder, lora_scale)
492
+
493
+ if self.text_encoder_2 is not None:
494
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
495
+ # Retrieve the original scale by scaling back the LoRA layers
496
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
497
+
498
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
499
+
500
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
501
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
502
+ dtype = next(self.image_encoder.parameters()).dtype
503
+
504
+ if not isinstance(image, torch.Tensor):
505
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
506
+
507
+ image = image.to(device=device, dtype=dtype)
508
+ if output_hidden_states:
509
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
510
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
511
+ uncond_image_enc_hidden_states = self.image_encoder(
512
+ torch.zeros_like(image), output_hidden_states=True
513
+ ).hidden_states[-2]
514
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
515
+ num_images_per_prompt, dim=0
516
+ )
517
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
518
+ else:
519
+ image_embeds = self.image_encoder(image).image_embeds
520
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
521
+ uncond_image_embeds = torch.zeros_like(image_embeds)
522
+
523
+ return image_embeds, uncond_image_embeds
524
+
525
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
526
+ def prepare_ip_adapter_image_embeds(
527
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
528
+ ):
529
+ image_embeds = []
530
+ if do_classifier_free_guidance:
531
+ negative_image_embeds = []
532
+ if ip_adapter_image_embeds is None:
533
+ if not isinstance(ip_adapter_image, list):
534
+ ip_adapter_image = [ip_adapter_image]
535
+
536
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
537
+ raise ValueError(
538
+ 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."
539
+ )
540
+
541
+ for single_ip_adapter_image, image_proj_layer in zip(
542
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
543
+ ):
544
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
545
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
546
+ single_ip_adapter_image, device, 1, output_hidden_state
547
+ )
548
+
549
+ image_embeds.append(single_image_embeds[None, :])
550
+ if do_classifier_free_guidance:
551
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
552
+ else:
553
+ for single_image_embeds in ip_adapter_image_embeds:
554
+ if do_classifier_free_guidance:
555
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
556
+ negative_image_embeds.append(single_negative_image_embeds)
557
+ image_embeds.append(single_image_embeds)
558
+
559
+ ip_adapter_image_embeds = []
560
+ for i, single_image_embeds in enumerate(image_embeds):
561
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
562
+ if do_classifier_free_guidance:
563
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
564
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
565
+
566
+ single_image_embeds = single_image_embeds.to(device=device)
567
+ ip_adapter_image_embeds.append(single_image_embeds)
568
+
569
+ return ip_adapter_image_embeds
570
+
571
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
572
+ def prepare_extra_step_kwargs(self, generator, eta):
573
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
574
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
575
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
576
+ # and should be between [0, 1]
577
+
578
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
579
+ extra_step_kwargs = {}
580
+ if accepts_eta:
581
+ extra_step_kwargs["eta"] = eta
582
+
583
+ # check if the scheduler accepts generator
584
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
585
+ if accepts_generator:
586
+ extra_step_kwargs["generator"] = generator
587
+ return extra_step_kwargs
588
+
589
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
590
+ def check_image(self, image, prompt, prompt_embeds):
591
+ image_is_pil = isinstance(image, PIL.Image.Image)
592
+ image_is_tensor = isinstance(image, torch.Tensor)
593
+ image_is_np = isinstance(image, np.ndarray)
594
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
595
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
596
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
597
+
598
+ if (
599
+ not image_is_pil
600
+ and not image_is_tensor
601
+ and not image_is_np
602
+ and not image_is_pil_list
603
+ and not image_is_tensor_list
604
+ and not image_is_np_list
605
+ ):
606
+ raise TypeError(
607
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
608
+ )
609
+
610
+ if image_is_pil:
611
+ image_batch_size = 1
612
+ else:
613
+ image_batch_size = len(image)
614
+
615
+ if prompt is not None and isinstance(prompt, str):
616
+ prompt_batch_size = 1
617
+ elif prompt is not None and isinstance(prompt, list):
618
+ prompt_batch_size = len(prompt)
619
+ elif prompt_embeds is not None:
620
+ prompt_batch_size = prompt_embeds.shape[0]
621
+
622
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
623
+ raise ValueError(
624
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
625
+ )
626
+
627
+ def check_inputs(
628
+ self,
629
+ prompt,
630
+ prompt_2,
631
+ image,
632
+ mask_image,
633
+ strength,
634
+ num_inference_steps,
635
+ callback_steps,
636
+ output_type,
637
+ negative_prompt=None,
638
+ negative_prompt_2=None,
639
+ prompt_embeds=None,
640
+ negative_prompt_embeds=None,
641
+ ip_adapter_image=None,
642
+ ip_adapter_image_embeds=None,
643
+ pooled_prompt_embeds=None,
644
+ negative_pooled_prompt_embeds=None,
645
+ controlnet_conditioning_scale=1.0,
646
+ control_guidance_start=0.0,
647
+ control_guidance_end=1.0,
648
+ callback_on_step_end_tensor_inputs=None,
649
+ padding_mask_crop=None,
650
+ ):
651
+ if strength < 0 or strength > 1:
652
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
653
+ if num_inference_steps is None:
654
+ raise ValueError("`num_inference_steps` cannot be None.")
655
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
656
+ raise ValueError(
657
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
658
+ f" {type(num_inference_steps)}."
659
+ )
660
+
661
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
662
+ raise ValueError(
663
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
664
+ f" {type(callback_steps)}."
665
+ )
666
+
667
+ if callback_on_step_end_tensor_inputs is not None and not all(
668
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
669
+ ):
670
+ raise ValueError(
671
+ 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]}"
672
+ )
673
+
674
+ if prompt is not None and prompt_embeds is not None:
675
+ raise ValueError(
676
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
677
+ " only forward one of the two."
678
+ )
679
+ elif prompt_2 is not None and prompt_embeds is not None:
680
+ raise ValueError(
681
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
682
+ " only forward one of the two."
683
+ )
684
+ elif prompt is None and prompt_embeds is None:
685
+ raise ValueError(
686
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
687
+ )
688
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
689
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
690
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
691
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
692
+
693
+ if negative_prompt is not None and negative_prompt_embeds is not None:
694
+ raise ValueError(
695
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
696
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
697
+ )
698
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
699
+ raise ValueError(
700
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
701
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
702
+ )
703
+
704
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
705
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
706
+ raise ValueError(
707
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
708
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
709
+ f" {negative_prompt_embeds.shape}."
710
+ )
711
+
712
+ if padding_mask_crop is not None:
713
+ if not isinstance(image, PIL.Image.Image):
714
+ raise ValueError(
715
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
716
+ )
717
+ if not isinstance(mask_image, PIL.Image.Image):
718
+ raise ValueError(
719
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
720
+ f" {type(mask_image)}."
721
+ )
722
+ if output_type != "pil":
723
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
724
+
725
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
726
+ raise ValueError(
727
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
728
+ )
729
+
730
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
731
+ raise ValueError(
732
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
733
+ )
734
+
735
+ # Check `image`
736
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
737
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
738
+ )
739
+ if (
740
+ isinstance(self.controlnet, ControlNetModel)
741
+ or is_compiled
742
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
743
+ ):
744
+ self.check_image(image, prompt, prompt_embeds)
745
+ elif (
746
+ isinstance(self.controlnet, ControlNetUnionModel)
747
+ or is_compiled
748
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
749
+ ):
750
+ self.check_image(image, prompt, prompt_embeds)
751
+
752
+ else:
753
+ assert False
754
+
755
+ # Check `controlnet_conditioning_scale`
756
+ if (
757
+ isinstance(self.controlnet, ControlNetModel)
758
+ or is_compiled
759
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
760
+ ):
761
+ if not isinstance(controlnet_conditioning_scale, float):
762
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
763
+
764
+ elif (
765
+ isinstance(self.controlnet, ControlNetUnionModel)
766
+ or is_compiled
767
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
768
+ ):
769
+ if not isinstance(controlnet_conditioning_scale, float):
770
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
771
+
772
+ else:
773
+ assert False
774
+
775
+ if not isinstance(control_guidance_start, (tuple, list)):
776
+ control_guidance_start = [control_guidance_start]
777
+
778
+ if not isinstance(control_guidance_end, (tuple, list)):
779
+ control_guidance_end = [control_guidance_end]
780
+
781
+ if len(control_guidance_start) != len(control_guidance_end):
782
+ raise ValueError(
783
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
784
+ )
785
+
786
+ for start, end in zip(control_guidance_start, control_guidance_end):
787
+ if start >= end:
788
+ raise ValueError(
789
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
790
+ )
791
+ if start < 0.0:
792
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
793
+ if end > 1.0:
794
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
795
+
796
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
797
+ raise ValueError(
798
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
799
+ )
800
+
801
+ if ip_adapter_image_embeds is not None:
802
+ if not isinstance(ip_adapter_image_embeds, list):
803
+ raise ValueError(
804
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
805
+ )
806
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
807
+ raise ValueError(
808
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
809
+ )
810
+
811
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_inpaint_sd_xl.StableDiffusionXLControlNetInpaintPipeline.prepare_control_image
812
+ def prepare_control_image(
813
+ self,
814
+ image,
815
+ width,
816
+ height,
817
+ batch_size,
818
+ num_images_per_prompt,
819
+ device,
820
+ dtype,
821
+ crops_coords,
822
+ resize_mode,
823
+ do_classifier_free_guidance=False,
824
+ guess_mode=False,
825
+ ):
826
+ image = self.control_image_processor.preprocess(
827
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
828
+ ).to(dtype=torch.float32)
829
+ image_batch_size = image.shape[0]
830
+
831
+ if image_batch_size == 1:
832
+ repeat_by = batch_size
833
+ else:
834
+ # image batch size is the same as prompt batch size
835
+ repeat_by = num_images_per_prompt
836
+
837
+ image = image.repeat_interleave(repeat_by, dim=0)
838
+
839
+ image = image.to(device=device, dtype=dtype)
840
+
841
+ if do_classifier_free_guidance and not guess_mode:
842
+ image = torch.cat([image] * 2)
843
+
844
+ return image
845
+
846
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_inpaint_sd_xl.StableDiffusionXLControlNetInpaintPipeline.prepare_latents
847
+ def prepare_latents(
848
+ self,
849
+ batch_size,
850
+ num_channels_latents,
851
+ height,
852
+ width,
853
+ dtype,
854
+ device,
855
+ generator,
856
+ latents=None,
857
+ image=None,
858
+ timestep=None,
859
+ is_strength_max=True,
860
+ add_noise=True,
861
+ return_noise=False,
862
+ return_image_latents=False,
863
+ ):
864
+ shape = (
865
+ batch_size,
866
+ num_channels_latents,
867
+ int(height) // self.vae_scale_factor,
868
+ int(width) // self.vae_scale_factor,
869
+ )
870
+ if isinstance(generator, list) and len(generator) != batch_size:
871
+ raise ValueError(
872
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
873
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
874
+ )
875
+
876
+ if (image is None or timestep is None) and not is_strength_max:
877
+ raise ValueError(
878
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
879
+ "However, either the image or the noise timestep has not been provided."
880
+ )
881
+
882
+ if return_image_latents or (latents is None and not is_strength_max):
883
+ image = image.to(device=device, dtype=dtype)
884
+
885
+ if image.shape[1] == 4:
886
+ image_latents = image
887
+ else:
888
+ image_latents = self._encode_vae_image(image=image, generator=generator)
889
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
890
+
891
+ if latents is None and add_noise:
892
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
893
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
894
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
895
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
896
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
897
+ elif add_noise:
898
+ noise = latents.to(device)
899
+ latents = noise * self.scheduler.init_noise_sigma
900
+ else:
901
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
902
+ latents = image_latents.to(device)
903
+
904
+ outputs = (latents,)
905
+
906
+ if return_noise:
907
+ outputs += (noise,)
908
+
909
+ if return_image_latents:
910
+ outputs += (image_latents,)
911
+
912
+ return outputs
913
+
914
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_inpaint_sd_xl.StableDiffusionXLControlNetInpaintPipeline._encode_vae_image
915
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
916
+ dtype = image.dtype
917
+ if self.vae.config.force_upcast:
918
+ image = image.float()
919
+ self.vae.to(dtype=torch.float32)
920
+
921
+ if isinstance(generator, list):
922
+ image_latents = [
923
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
924
+ for i in range(image.shape[0])
925
+ ]
926
+ image_latents = torch.cat(image_latents, dim=0)
927
+ else:
928
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
929
+
930
+ if self.vae.config.force_upcast:
931
+ self.vae.to(dtype)
932
+
933
+ image_latents = image_latents.to(dtype)
934
+ image_latents = self.vae.config.scaling_factor * image_latents
935
+
936
+ return image_latents
937
+
938
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_inpaint_sd_xl.StableDiffusionXLControlNetInpaintPipeline.prepare_mask_latents
939
+ def prepare_mask_latents(
940
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
941
+ ):
942
+ # resize the mask to latents shape as we concatenate the mask to the latents
943
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
944
+ # and half precision
945
+ mask = torch.nn.functional.interpolate(
946
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
947
+ )
948
+ mask = mask.to(device=device, dtype=dtype)
949
+
950
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
951
+ if mask.shape[0] < batch_size:
952
+ if not batch_size % mask.shape[0] == 0:
953
+ raise ValueError(
954
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
955
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
956
+ " of masks that you pass is divisible by the total requested batch size."
957
+ )
958
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
959
+
960
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
961
+
962
+ masked_image_latents = None
963
+ if masked_image is not None:
964
+ masked_image = masked_image.to(device=device, dtype=dtype)
965
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
966
+ if masked_image_latents.shape[0] < batch_size:
967
+ if not batch_size % masked_image_latents.shape[0] == 0:
968
+ raise ValueError(
969
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
970
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
971
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
972
+ )
973
+ masked_image_latents = masked_image_latents.repeat(
974
+ batch_size // masked_image_latents.shape[0], 1, 1, 1
975
+ )
976
+
977
+ masked_image_latents = (
978
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
979
+ )
980
+
981
+ # aligning device to prevent device errors when concating it with the latent model input
982
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
983
+
984
+ return mask, masked_image_latents
985
+
986
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
987
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
988
+ # get the original timestep using init_timestep
989
+ if denoising_start is None:
990
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
991
+ t_start = max(num_inference_steps - init_timestep, 0)
992
+
993
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
994
+ if hasattr(self.scheduler, "set_begin_index"):
995
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
996
+
997
+ return timesteps, num_inference_steps - t_start
998
+
999
+ else:
1000
+ # Strength is irrelevant if we directly request a timestep to start at;
1001
+ # that is, strength is determined by the denoising_start instead.
1002
+ discrete_timestep_cutoff = int(
1003
+ round(
1004
+ self.scheduler.config.num_train_timesteps
1005
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
1006
+ )
1007
+ )
1008
+
1009
+ num_inference_steps = (self.scheduler.timesteps < discrete_timestep_cutoff).sum().item()
1010
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
1011
+ # if the scheduler is a 2nd order scheduler we might have to do +1
1012
+ # because `num_inference_steps` might be even given that every timestep
1013
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
1014
+ # mean that we cut the timesteps in the middle of the denoising step
1015
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
1016
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
1017
+ num_inference_steps = num_inference_steps + 1
1018
+
1019
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
1020
+ t_start = len(self.scheduler.timesteps) - num_inference_steps
1021
+ timesteps = self.scheduler.timesteps[t_start:]
1022
+ if hasattr(self.scheduler, "set_begin_index"):
1023
+ self.scheduler.set_begin_index(t_start)
1024
+ return timesteps, num_inference_steps
1025
+
1026
+ def _get_add_time_ids(
1027
+ self,
1028
+ original_size,
1029
+ crops_coords_top_left,
1030
+ target_size,
1031
+ aesthetic_score,
1032
+ negative_aesthetic_score,
1033
+ dtype,
1034
+ text_encoder_projection_dim=None,
1035
+ ):
1036
+ if self.config.requires_aesthetics_score:
1037
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
1038
+ add_neg_time_ids = list(original_size + crops_coords_top_left + (negative_aesthetic_score,))
1039
+ else:
1040
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1041
+ add_neg_time_ids = list(original_size + crops_coords_top_left + target_size)
1042
+
1043
+ passed_add_embed_dim = (
1044
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
1045
+ )
1046
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
1047
+
1048
+ if (
1049
+ expected_add_embed_dim > passed_add_embed_dim
1050
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
1051
+ ):
1052
+ raise ValueError(
1053
+ 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."
1054
+ )
1055
+ elif (
1056
+ expected_add_embed_dim < passed_add_embed_dim
1057
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
1058
+ ):
1059
+ raise ValueError(
1060
+ 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."
1061
+ )
1062
+ elif expected_add_embed_dim != passed_add_embed_dim:
1063
+ raise ValueError(
1064
+ 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`."
1065
+ )
1066
+
1067
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1068
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
1069
+
1070
+ return add_time_ids, add_neg_time_ids
1071
+
1072
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
1073
+ def upcast_vae(self):
1074
+ dtype = self.vae.dtype
1075
+ self.vae.to(dtype=torch.float32)
1076
+ use_torch_2_0_or_xformers = isinstance(
1077
+ self.vae.decoder.mid_block.attentions[0].processor,
1078
+ (
1079
+ AttnProcessor2_0,
1080
+ XFormersAttnProcessor,
1081
+ ),
1082
+ )
1083
+ # if xformers or torch_2_0 is used attention block does not need
1084
+ # to be in float32 which can save lots of memory
1085
+ if use_torch_2_0_or_xformers:
1086
+ self.vae.post_quant_conv.to(dtype)
1087
+ self.vae.decoder.conv_in.to(dtype)
1088
+ self.vae.decoder.mid_block.to(dtype)
1089
+
1090
+ @property
1091
+ def guidance_scale(self):
1092
+ return self._guidance_scale
1093
+
1094
+ @property
1095
+ def clip_skip(self):
1096
+ return self._clip_skip
1097
+
1098
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1099
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1100
+ # corresponds to doing no classifier free guidance.
1101
+ @property
1102
+ def do_classifier_free_guidance(self):
1103
+ return self._guidance_scale > 1
1104
+
1105
+ @property
1106
+ def cross_attention_kwargs(self):
1107
+ return self._cross_attention_kwargs
1108
+
1109
+ @property
1110
+ def num_timesteps(self):
1111
+ return self._num_timesteps
1112
+
1113
+ @property
1114
+ def interrupt(self):
1115
+ return self._interrupt
1116
+
1117
+ @torch.no_grad()
1118
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1119
+ def __call__(
1120
+ self,
1121
+ prompt: Union[str, List[str]] = None,
1122
+ prompt_2: Optional[Union[str, List[str]]] = None,
1123
+ image: PipelineImageInput = None,
1124
+ mask_image: PipelineImageInput = None,
1125
+ control_image: PipelineImageInput = None,
1126
+ height: Optional[int] = None,
1127
+ width: Optional[int] = None,
1128
+ padding_mask_crop: Optional[int] = None,
1129
+ strength: float = 0.9999,
1130
+ num_inference_steps: int = 50,
1131
+ denoising_start: Optional[float] = None,
1132
+ denoising_end: Optional[float] = None,
1133
+ guidance_scale: float = 5.0,
1134
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1135
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1136
+ num_images_per_prompt: Optional[int] = 1,
1137
+ eta: float = 0.0,
1138
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1139
+ latents: Optional[torch.Tensor] = None,
1140
+ prompt_embeds: Optional[torch.Tensor] = None,
1141
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1142
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1143
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1144
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1145
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1146
+ output_type: Optional[str] = "pil",
1147
+ return_dict: bool = True,
1148
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1149
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1150
+ guess_mode: bool = False,
1151
+ control_guidance_start: Union[float, List[float]] = 0.0,
1152
+ control_guidance_end: Union[float, List[float]] = 1.0,
1153
+ control_mode: Optional[Union[int, List[int]]] = None,
1154
+ guidance_rescale: float = 0.0,
1155
+ original_size: Tuple[int, int] = None,
1156
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1157
+ target_size: Tuple[int, int] = None,
1158
+ aesthetic_score: float = 6.0,
1159
+ negative_aesthetic_score: float = 2.5,
1160
+ clip_skip: Optional[int] = None,
1161
+ callback_on_step_end: Optional[
1162
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1163
+ ] = None,
1164
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1165
+ **kwargs,
1166
+ ):
1167
+ r"""
1168
+ Function invoked when calling the pipeline for generation.
1169
+
1170
+ Args:
1171
+ prompt (`str` or `List[str]`, *optional*):
1172
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1173
+ instead.
1174
+ prompt_2 (`str` or `List[str]`, *optional*):
1175
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1176
+ used in both text-encoders
1177
+ image (`PIL.Image.Image`):
1178
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
1179
+ be masked out with `mask_image` and repainted according to `prompt`.
1180
+ mask_image (`PIL.Image.Image`):
1181
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1182
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
1183
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
1184
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
1185
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1186
+ The height in pixels of the generated image.
1187
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1188
+ The width in pixels of the generated image.
1189
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
1190
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
1191
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
1192
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
1193
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
1194
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
1195
+ the image is large and contain information irrelevant for inpainting, such as background.
1196
+ strength (`float`, *optional*, defaults to 0.9999):
1197
+ Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be
1198
+ between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the
1199
+ `strength`. The number of denoising steps depends on the amount of noise initially added. When
1200
+ `strength` is 1, added noise will be maximum and the denoising process will run for the full number of
1201
+ iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked
1202
+ portion of the reference `image`. Note that in the case of `denoising_start` being declared as an
1203
+ integer, the value of `strength` will be ignored.
1204
+ num_inference_steps (`int`, *optional*, defaults to 50):
1205
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1206
+ expense of slower inference.
1207
+ denoising_start (`float`, *optional*):
1208
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1209
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1210
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1211
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1212
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1213
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1214
+ denoising_end (`float`, *optional*):
1215
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1216
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1217
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1218
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1219
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1220
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1221
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1222
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1223
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1224
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1225
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1226
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1227
+ usually at the expense of lower image quality.
1228
+ negative_prompt (`str` or `List[str]`, *optional*):
1229
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1230
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1231
+ less than `1`).
1232
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1233
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1234
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1235
+ prompt_embeds (`torch.Tensor`, *optional*):
1236
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1237
+ provided, text embeddings will be generated from `prompt` input argument.
1238
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1239
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1240
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1241
+ argument.
1242
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1243
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1244
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1245
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1246
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1247
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1248
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1249
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1250
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1251
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1252
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1253
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1254
+ input argument.
1255
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1256
+ The number of images to generate per prompt.
1257
+ eta (`float`, *optional*, defaults to 0.0):
1258
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1259
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1260
+ generator (`torch.Generator`, *optional*):
1261
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1262
+ to make generation deterministic.
1263
+ latents (`torch.Tensor`, *optional*):
1264
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1265
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1266
+ tensor will ge generated by sampling using the supplied random `generator`.
1267
+ output_type (`str`, *optional*, defaults to `"pil"`):
1268
+ The output format of the generate image. Choose between
1269
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1270
+ return_dict (`bool`, *optional*, defaults to `True`):
1271
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1272
+ plain tuple.
1273
+ cross_attention_kwargs (`dict`, *optional*):
1274
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1275
+ `self.processor` in
1276
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1277
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1278
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1279
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
1280
+ explained in section 2.2 of
1281
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1282
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1283
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1284
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1285
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1286
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1287
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1288
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1289
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
1290
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1291
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1292
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1293
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1294
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1295
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1296
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1297
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1298
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1299
+ clip_skip (`int`, *optional*):
1300
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1301
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1302
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1303
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1304
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1305
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1306
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1307
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1308
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1309
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1310
+ `._callback_tensor_inputs` attribute of your pipeline class.
1311
+
1312
+ Examples:
1313
+
1314
+ Returns:
1315
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1316
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1317
+ `tuple. `tuple. When returning a tuple, the first element is a list with the generated images.
1318
+ """
1319
+
1320
+ callback = kwargs.pop("callback", None)
1321
+ callback_steps = kwargs.pop("callback_steps", None)
1322
+
1323
+ if callback is not None:
1324
+ deprecate(
1325
+ "callback",
1326
+ "1.0.0",
1327
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1328
+ )
1329
+ if callback_steps is not None:
1330
+ deprecate(
1331
+ "callback_steps",
1332
+ "1.0.0",
1333
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1334
+ )
1335
+
1336
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1337
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1338
+
1339
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1340
+
1341
+ # align format for control guidance
1342
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1343
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1344
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1345
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1346
+
1347
+ # # 0.0 Default height and width to unet
1348
+ # height = height or self.unet.config.sample_size * self.vae_scale_factor
1349
+ # width = width or self.unet.config.sample_size * self.vae_scale_factor
1350
+
1351
+ # 0.1 align format for control guidance
1352
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1353
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1354
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1355
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1356
+
1357
+ if not isinstance(control_image, list):
1358
+ control_image = [control_image]
1359
+
1360
+ if not isinstance(control_mode, list):
1361
+ control_mode = [control_mode]
1362
+
1363
+ if len(control_image) != len(control_mode):
1364
+ raise ValueError("Expected len(control_image) == len(control_type)")
1365
+
1366
+ num_control_type = controlnet.config.num_control_type
1367
+
1368
+ # 1. Check inputs
1369
+ control_type = [0 for _ in range(num_control_type)]
1370
+ for _image, control_idx in zip(control_image, control_mode):
1371
+ control_type[control_idx] = 1
1372
+ self.check_inputs(
1373
+ prompt,
1374
+ prompt_2,
1375
+ _image,
1376
+ mask_image,
1377
+ strength,
1378
+ num_inference_steps,
1379
+ callback_steps,
1380
+ output_type,
1381
+ negative_prompt,
1382
+ negative_prompt_2,
1383
+ prompt_embeds,
1384
+ negative_prompt_embeds,
1385
+ ip_adapter_image,
1386
+ ip_adapter_image_embeds,
1387
+ pooled_prompt_embeds,
1388
+ negative_pooled_prompt_embeds,
1389
+ controlnet_conditioning_scale,
1390
+ control_guidance_start,
1391
+ control_guidance_end,
1392
+ callback_on_step_end_tensor_inputs,
1393
+ padding_mask_crop,
1394
+ )
1395
+
1396
+ control_type = torch.Tensor(control_type)
1397
+
1398
+ self._guidance_scale = guidance_scale
1399
+ self._clip_skip = clip_skip
1400
+ self._cross_attention_kwargs = cross_attention_kwargs
1401
+ self._interrupt = False
1402
+
1403
+ # 2. Define call parameters
1404
+ if prompt is not None and isinstance(prompt, str):
1405
+ batch_size = 1
1406
+ elif prompt is not None and isinstance(prompt, list):
1407
+ batch_size = len(prompt)
1408
+ else:
1409
+ batch_size = prompt_embeds.shape[0]
1410
+
1411
+ device = self._execution_device
1412
+
1413
+ # 3. Encode input prompt
1414
+ text_encoder_lora_scale = (
1415
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1416
+ )
1417
+
1418
+ (
1419
+ prompt_embeds,
1420
+ negative_prompt_embeds,
1421
+ pooled_prompt_embeds,
1422
+ negative_pooled_prompt_embeds,
1423
+ ) = self.encode_prompt(
1424
+ prompt=prompt,
1425
+ prompt_2=prompt_2,
1426
+ device=device,
1427
+ num_images_per_prompt=num_images_per_prompt,
1428
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1429
+ negative_prompt=negative_prompt,
1430
+ negative_prompt_2=negative_prompt_2,
1431
+ prompt_embeds=prompt_embeds,
1432
+ negative_prompt_embeds=negative_prompt_embeds,
1433
+ pooled_prompt_embeds=pooled_prompt_embeds,
1434
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1435
+ lora_scale=text_encoder_lora_scale,
1436
+ clip_skip=self.clip_skip,
1437
+ )
1438
+
1439
+ # 3.1 Encode ip_adapter_image
1440
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1441
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1442
+ ip_adapter_image,
1443
+ ip_adapter_image_embeds,
1444
+ device,
1445
+ batch_size * num_images_per_prompt,
1446
+ self.do_classifier_free_guidance,
1447
+ )
1448
+
1449
+ # 4. set timesteps
1450
+ def denoising_value_valid(dnv):
1451
+ return isinstance(dnv, float) and 0 < dnv < 1
1452
+
1453
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1454
+ timesteps, num_inference_steps = self.get_timesteps(
1455
+ num_inference_steps,
1456
+ strength,
1457
+ device,
1458
+ denoising_start=denoising_start if denoising_value_valid(denoising_start) else None,
1459
+ )
1460
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1461
+ if num_inference_steps < 1:
1462
+ raise ValueError(
1463
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1464
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1465
+ )
1466
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1467
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1468
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1469
+ is_strength_max = strength == 1.0
1470
+ self._num_timesteps = len(timesteps)
1471
+
1472
+ # 5. Preprocess mask and image - resizes image and mask w.r.t height and width
1473
+ # 5.1 Prepare init image
1474
+ if padding_mask_crop is not None:
1475
+ height, width = self.image_processor.get_default_height_width(image, height, width)
1476
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
1477
+ resize_mode = "fill"
1478
+ else:
1479
+ crops_coords = None
1480
+ resize_mode = "default"
1481
+
1482
+ original_image = image
1483
+ init_image = self.image_processor.preprocess(
1484
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
1485
+ )
1486
+ init_image = init_image.to(dtype=torch.float32)
1487
+
1488
+ # 5.2 Prepare control images
1489
+ for idx, _ in enumerate(control_image):
1490
+ control_image[idx] = self.prepare_control_image(
1491
+ image=control_image[idx],
1492
+ width=width,
1493
+ height=height,
1494
+ batch_size=batch_size * num_images_per_prompt,
1495
+ num_images_per_prompt=num_images_per_prompt,
1496
+ device=device,
1497
+ dtype=controlnet.dtype,
1498
+ crops_coords=crops_coords,
1499
+ resize_mode=resize_mode,
1500
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1501
+ guess_mode=guess_mode,
1502
+ )
1503
+ height, width = control_image[idx].shape[-2:]
1504
+
1505
+ # 5.3 Prepare mask
1506
+ mask = self.mask_processor.preprocess(
1507
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
1508
+ )
1509
+
1510
+ masked_image = init_image * (mask < 0.5)
1511
+ _, _, height, width = init_image.shape
1512
+
1513
+ # 6. Prepare latent variables
1514
+ num_channels_latents = self.vae.config.latent_channels
1515
+ num_channels_unet = self.unet.config.in_channels
1516
+ return_image_latents = num_channels_unet == 4
1517
+
1518
+ add_noise = True if denoising_start is None else False
1519
+ latents_outputs = self.prepare_latents(
1520
+ batch_size * num_images_per_prompt,
1521
+ num_channels_latents,
1522
+ height,
1523
+ width,
1524
+ prompt_embeds.dtype,
1525
+ device,
1526
+ generator,
1527
+ latents,
1528
+ image=init_image,
1529
+ timestep=latent_timestep,
1530
+ is_strength_max=is_strength_max,
1531
+ add_noise=add_noise,
1532
+ return_noise=True,
1533
+ return_image_latents=return_image_latents,
1534
+ )
1535
+
1536
+ if return_image_latents:
1537
+ latents, noise, image_latents = latents_outputs
1538
+ else:
1539
+ latents, noise = latents_outputs
1540
+
1541
+ # 7. Prepare mask latent variables
1542
+ mask, _ = self.prepare_mask_latents(
1543
+ mask,
1544
+ masked_image,
1545
+ batch_size * num_images_per_prompt,
1546
+ height,
1547
+ width,
1548
+ prompt_embeds.dtype,
1549
+ device,
1550
+ generator,
1551
+ self.do_classifier_free_guidance,
1552
+ )
1553
+
1554
+ # 8. Check that sizes of mask, masked image and latents match
1555
+ if num_channels_unet != 4:
1556
+ raise ValueError(
1557
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1558
+ )
1559
+ # 8.1 Prepare extra step kwargs.
1560
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1561
+
1562
+ # 8.2 Create tensor stating which controlnets to keep
1563
+ controlnet_keep = []
1564
+ for i in range(len(timesteps)):
1565
+ controlnet_keep.append(
1566
+ 1.0
1567
+ - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1568
+ )
1569
+
1570
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1571
+ height, width = latents.shape[-2:]
1572
+ height = height * self.vae_scale_factor
1573
+ width = width * self.vae_scale_factor
1574
+
1575
+ original_size = original_size or (height, width)
1576
+ target_size = target_size or (height, width)
1577
+ for _image in control_image:
1578
+ if isinstance(_image, torch.Tensor):
1579
+ original_size = original_size or _image.shape[-2:]
1580
+
1581
+ # 10. Prepare added time ids & embeddings
1582
+ add_text_embeds = pooled_prompt_embeds
1583
+ if self.text_encoder_2 is None:
1584
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1585
+ else:
1586
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1587
+
1588
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1589
+ original_size,
1590
+ crops_coords_top_left,
1591
+ target_size,
1592
+ aesthetic_score,
1593
+ negative_aesthetic_score,
1594
+ dtype=prompt_embeds.dtype,
1595
+ text_encoder_projection_dim=text_encoder_projection_dim,
1596
+ )
1597
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1598
+
1599
+ if self.do_classifier_free_guidance:
1600
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1601
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1602
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1603
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1604
+
1605
+ prompt_embeds = prompt_embeds.to(device)
1606
+ add_text_embeds = add_text_embeds.to(device)
1607
+ add_time_ids = add_time_ids.to(device)
1608
+
1609
+ # 11. Denoising loop
1610
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1611
+
1612
+ if (
1613
+ denoising_end is not None
1614
+ and denoising_start is not None
1615
+ and denoising_value_valid(denoising_end)
1616
+ and denoising_value_valid(denoising_start)
1617
+ and denoising_start >= denoising_end
1618
+ ):
1619
+ raise ValueError(
1620
+ f"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: "
1621
+ + f" {denoising_end} when using type float."
1622
+ )
1623
+ elif denoising_end is not None and denoising_value_valid(denoising_end):
1624
+ discrete_timestep_cutoff = int(
1625
+ round(
1626
+ self.scheduler.config.num_train_timesteps
1627
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1628
+ )
1629
+ )
1630
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1631
+ timesteps = timesteps[:num_inference_steps]
1632
+
1633
+ control_type = (
1634
+ control_type.reshape(1, -1)
1635
+ .to(device, dtype=prompt_embeds.dtype)
1636
+ .repeat(batch_size * num_images_per_prompt * 2, 1)
1637
+ )
1638
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1639
+ for i, t in enumerate(timesteps):
1640
+ if self.interrupt:
1641
+ continue
1642
+
1643
+ # expand the latents if we are doing classifier free guidance
1644
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1645
+
1646
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1647
+
1648
+ added_cond_kwargs = {
1649
+ "text_embeds": add_text_embeds,
1650
+ "time_ids": add_time_ids,
1651
+ }
1652
+
1653
+ # controlnet(s) inference
1654
+ if guess_mode and self.do_classifier_free_guidance:
1655
+ # Infer ControlNet only for the conditional batch.
1656
+ control_model_input = latents
1657
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1658
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1659
+ controlnet_added_cond_kwargs = {
1660
+ "text_embeds": add_text_embeds.chunk(2)[1],
1661
+ "time_ids": add_time_ids.chunk(2)[1],
1662
+ }
1663
+ else:
1664
+ control_model_input = latent_model_input
1665
+ controlnet_prompt_embeds = prompt_embeds
1666
+ controlnet_added_cond_kwargs = added_cond_kwargs
1667
+
1668
+ if isinstance(controlnet_keep[i], list):
1669
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1670
+ else:
1671
+ controlnet_cond_scale = controlnet_conditioning_scale
1672
+ if isinstance(controlnet_cond_scale, list):
1673
+ controlnet_cond_scale = controlnet_cond_scale[0]
1674
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1675
+
1676
+ # # Resize control_image to match the size of the input to the controlnet
1677
+ # if control_image.shape[-2:] != control_model_input.shape[-2:]:
1678
+ # control_image = F.interpolate(control_image, size=control_model_input.shape[-2:], mode="bilinear", align_corners=False)
1679
+
1680
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1681
+ control_model_input,
1682
+ t,
1683
+ encoder_hidden_states=controlnet_prompt_embeds,
1684
+ controlnet_cond=control_image,
1685
+ control_type=control_type,
1686
+ control_type_idx=control_mode,
1687
+ conditioning_scale=cond_scale,
1688
+ guess_mode=guess_mode,
1689
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1690
+ return_dict=False,
1691
+ )
1692
+
1693
+ if guess_mode and self.do_classifier_free_guidance:
1694
+ # Inferred ControlNet only for the conditional batch.
1695
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1696
+ # add 0 to the unconditional batch to keep it unchanged.
1697
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1698
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1699
+
1700
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1701
+ added_cond_kwargs["image_embeds"] = image_embeds
1702
+
1703
+ # predict the noise residual
1704
+ noise_pred = self.unet(
1705
+ latent_model_input,
1706
+ t,
1707
+ encoder_hidden_states=prompt_embeds,
1708
+ cross_attention_kwargs=self.cross_attention_kwargs,
1709
+ down_block_additional_residuals=down_block_res_samples,
1710
+ mid_block_additional_residual=mid_block_res_sample,
1711
+ added_cond_kwargs=added_cond_kwargs,
1712
+ return_dict=False,
1713
+ )[0]
1714
+
1715
+ # perform guidance
1716
+ if self.do_classifier_free_guidance:
1717
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1718
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1719
+
1720
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
1721
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1722
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1723
+
1724
+ # compute the previous noisy sample x_t -> x_t-1
1725
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1726
+
1727
+ init_latents_proper = image_latents
1728
+ if self.do_classifier_free_guidance:
1729
+ init_mask, _ = mask.chunk(2)
1730
+ else:
1731
+ init_mask = mask
1732
+
1733
+ if i < len(timesteps) - 1:
1734
+ noise_timestep = timesteps[i + 1]
1735
+ init_latents_proper = self.scheduler.add_noise(
1736
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1737
+ )
1738
+
1739
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1740
+
1741
+ if callback_on_step_end is not None:
1742
+ callback_kwargs = {}
1743
+ for k in callback_on_step_end_tensor_inputs:
1744
+ callback_kwargs[k] = locals()[k]
1745
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1746
+
1747
+ latents = callback_outputs.pop("latents", latents)
1748
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1749
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1750
+
1751
+ # call the callback, if provided
1752
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1753
+ progress_bar.update()
1754
+ if callback is not None and i % callback_steps == 0:
1755
+ step_idx = i // getattr(self.scheduler, "order", 1)
1756
+ callback(step_idx, t, latents)
1757
+
1758
+ # make sure the VAE is in float32 mode, as it overflows in float16
1759
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1760
+ self.upcast_vae()
1761
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1762
+
1763
+ # If we do sequential model offloading, let's offload unet and controlnet
1764
+ # manually for max memory savings
1765
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1766
+ self.unet.to("cpu")
1767
+ self.controlnet.to("cpu")
1768
+ torch.cuda.empty_cache()
1769
+
1770
+ if not output_type == "latent":
1771
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1772
+ else:
1773
+ return StableDiffusionXLPipelineOutput(images=latents)
1774
+
1775
+ # apply watermark if available
1776
+ if self.watermark is not None:
1777
+ image = self.watermark.apply_watermark(image)
1778
+
1779
+ image = self.image_processor.postprocess(image, output_type=output_type)
1780
+
1781
+ if padding_mask_crop is not None:
1782
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
1783
+
1784
+ # Offload all models
1785
+ self.maybe_free_model_hooks()
1786
+
1787
+ if not return_dict:
1788
+ return (image,)
1789
+
1790
+ return StableDiffusionXLPipelineOutput(images=image)