diffusers 0.33.0__py3-none-any.whl → 0.34.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (478) hide show
  1. diffusers/__init__.py +48 -1
  2. diffusers/commands/__init__.py +1 -1
  3. diffusers/commands/diffusers_cli.py +1 -1
  4. diffusers/commands/env.py +1 -1
  5. diffusers/commands/fp16_safetensors.py +1 -1
  6. diffusers/dependency_versions_check.py +1 -1
  7. diffusers/dependency_versions_table.py +1 -1
  8. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  9. diffusers/hooks/faster_cache.py +2 -2
  10. diffusers/hooks/group_offloading.py +128 -29
  11. diffusers/hooks/hooks.py +2 -2
  12. diffusers/hooks/layerwise_casting.py +3 -3
  13. diffusers/hooks/pyramid_attention_broadcast.py +1 -1
  14. diffusers/image_processor.py +7 -2
  15. diffusers/loaders/__init__.py +4 -0
  16. diffusers/loaders/ip_adapter.py +5 -14
  17. diffusers/loaders/lora_base.py +212 -111
  18. diffusers/loaders/lora_conversion_utils.py +275 -34
  19. diffusers/loaders/lora_pipeline.py +1554 -819
  20. diffusers/loaders/peft.py +52 -109
  21. diffusers/loaders/single_file.py +2 -2
  22. diffusers/loaders/single_file_model.py +20 -4
  23. diffusers/loaders/single_file_utils.py +225 -5
  24. diffusers/loaders/textual_inversion.py +3 -2
  25. diffusers/loaders/transformer_flux.py +1 -1
  26. diffusers/loaders/transformer_sd3.py +2 -2
  27. diffusers/loaders/unet.py +2 -16
  28. diffusers/loaders/unet_loader_utils.py +1 -1
  29. diffusers/loaders/utils.py +1 -1
  30. diffusers/models/__init__.py +15 -1
  31. diffusers/models/activations.py +5 -5
  32. diffusers/models/adapter.py +2 -3
  33. diffusers/models/attention.py +4 -4
  34. diffusers/models/attention_flax.py +10 -10
  35. diffusers/models/attention_processor.py +14 -10
  36. diffusers/models/auto_model.py +47 -10
  37. diffusers/models/autoencoders/__init__.py +1 -0
  38. diffusers/models/autoencoders/autoencoder_asym_kl.py +4 -4
  39. diffusers/models/autoencoders/autoencoder_dc.py +3 -3
  40. diffusers/models/autoencoders/autoencoder_kl.py +4 -4
  41. diffusers/models/autoencoders/autoencoder_kl_allegro.py +4 -4
  42. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +6 -6
  43. diffusers/models/autoencoders/autoencoder_kl_cosmos.py +1108 -0
  44. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +2 -2
  45. diffusers/models/autoencoders/autoencoder_kl_ltx.py +3 -3
  46. diffusers/models/autoencoders/autoencoder_kl_magvit.py +4 -4
  47. diffusers/models/autoencoders/autoencoder_kl_mochi.py +3 -3
  48. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +4 -4
  49. diffusers/models/autoencoders/autoencoder_kl_wan.py +256 -22
  50. diffusers/models/autoencoders/autoencoder_oobleck.py +1 -1
  51. diffusers/models/autoencoders/autoencoder_tiny.py +3 -3
  52. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  53. diffusers/models/autoencoders/vae.py +13 -2
  54. diffusers/models/autoencoders/vq_model.py +2 -2
  55. diffusers/models/cache_utils.py +1 -1
  56. diffusers/models/controlnet.py +1 -1
  57. diffusers/models/controlnet_flux.py +1 -1
  58. diffusers/models/controlnet_sd3.py +1 -1
  59. diffusers/models/controlnet_sparsectrl.py +1 -1
  60. diffusers/models/controlnets/__init__.py +1 -0
  61. diffusers/models/controlnets/controlnet.py +3 -3
  62. diffusers/models/controlnets/controlnet_flax.py +1 -1
  63. diffusers/models/controlnets/controlnet_flux.py +16 -15
  64. diffusers/models/controlnets/controlnet_hunyuan.py +2 -2
  65. diffusers/models/controlnets/controlnet_sana.py +290 -0
  66. diffusers/models/controlnets/controlnet_sd3.py +1 -1
  67. diffusers/models/controlnets/controlnet_sparsectrl.py +2 -2
  68. diffusers/models/controlnets/controlnet_union.py +1 -1
  69. diffusers/models/controlnets/controlnet_xs.py +7 -7
  70. diffusers/models/controlnets/multicontrolnet.py +4 -5
  71. diffusers/models/controlnets/multicontrolnet_union.py +5 -6
  72. diffusers/models/downsampling.py +2 -2
  73. diffusers/models/embeddings.py +10 -12
  74. diffusers/models/embeddings_flax.py +2 -2
  75. diffusers/models/lora.py +3 -3
  76. diffusers/models/modeling_utils.py +44 -14
  77. diffusers/models/normalization.py +4 -4
  78. diffusers/models/resnet.py +2 -2
  79. diffusers/models/resnet_flax.py +1 -1
  80. diffusers/models/transformers/__init__.py +5 -0
  81. diffusers/models/transformers/auraflow_transformer_2d.py +70 -24
  82. diffusers/models/transformers/cogvideox_transformer_3d.py +1 -1
  83. diffusers/models/transformers/consisid_transformer_3d.py +1 -1
  84. diffusers/models/transformers/dit_transformer_2d.py +2 -2
  85. diffusers/models/transformers/dual_transformer_2d.py +1 -1
  86. diffusers/models/transformers/hunyuan_transformer_2d.py +2 -2
  87. diffusers/models/transformers/latte_transformer_3d.py +4 -5
  88. diffusers/models/transformers/lumina_nextdit2d.py +2 -2
  89. diffusers/models/transformers/pixart_transformer_2d.py +3 -3
  90. diffusers/models/transformers/prior_transformer.py +1 -1
  91. diffusers/models/transformers/sana_transformer.py +8 -3
  92. diffusers/models/transformers/stable_audio_transformer.py +5 -9
  93. diffusers/models/transformers/t5_film_transformer.py +3 -3
  94. diffusers/models/transformers/transformer_2d.py +1 -1
  95. diffusers/models/transformers/transformer_allegro.py +1 -1
  96. diffusers/models/transformers/transformer_chroma.py +742 -0
  97. diffusers/models/transformers/transformer_cogview3plus.py +5 -10
  98. diffusers/models/transformers/transformer_cogview4.py +317 -25
  99. diffusers/models/transformers/transformer_cosmos.py +579 -0
  100. diffusers/models/transformers/transformer_flux.py +9 -11
  101. diffusers/models/transformers/transformer_hidream_image.py +942 -0
  102. diffusers/models/transformers/transformer_hunyuan_video.py +6 -8
  103. diffusers/models/transformers/transformer_hunyuan_video_framepack.py +416 -0
  104. diffusers/models/transformers/transformer_ltx.py +2 -2
  105. diffusers/models/transformers/transformer_lumina2.py +1 -1
  106. diffusers/models/transformers/transformer_mochi.py +1 -1
  107. diffusers/models/transformers/transformer_omnigen.py +2 -2
  108. diffusers/models/transformers/transformer_sd3.py +7 -7
  109. diffusers/models/transformers/transformer_temporal.py +1 -1
  110. diffusers/models/transformers/transformer_wan.py +24 -8
  111. diffusers/models/transformers/transformer_wan_vace.py +393 -0
  112. diffusers/models/unets/unet_1d.py +1 -1
  113. diffusers/models/unets/unet_1d_blocks.py +1 -1
  114. diffusers/models/unets/unet_2d.py +1 -1
  115. diffusers/models/unets/unet_2d_blocks.py +1 -1
  116. diffusers/models/unets/unet_2d_blocks_flax.py +8 -7
  117. diffusers/models/unets/unet_2d_condition.py +2 -2
  118. diffusers/models/unets/unet_2d_condition_flax.py +2 -2
  119. diffusers/models/unets/unet_3d_blocks.py +1 -1
  120. diffusers/models/unets/unet_3d_condition.py +3 -3
  121. diffusers/models/unets/unet_i2vgen_xl.py +3 -3
  122. diffusers/models/unets/unet_kandinsky3.py +1 -1
  123. diffusers/models/unets/unet_motion_model.py +2 -2
  124. diffusers/models/unets/unet_stable_cascade.py +1 -1
  125. diffusers/models/upsampling.py +2 -2
  126. diffusers/models/vae_flax.py +2 -2
  127. diffusers/models/vq_model.py +1 -1
  128. diffusers/pipelines/__init__.py +37 -6
  129. diffusers/pipelines/allegro/pipeline_allegro.py +11 -11
  130. diffusers/pipelines/amused/pipeline_amused.py +7 -6
  131. diffusers/pipelines/amused/pipeline_amused_img2img.py +6 -5
  132. diffusers/pipelines/amused/pipeline_amused_inpaint.py +6 -5
  133. diffusers/pipelines/animatediff/pipeline_animatediff.py +6 -6
  134. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +6 -6
  135. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +16 -15
  136. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +6 -6
  137. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +5 -5
  138. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +5 -5
  139. diffusers/pipelines/audioldm/pipeline_audioldm.py +8 -7
  140. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  141. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +23 -13
  142. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +48 -11
  143. diffusers/pipelines/auto_pipeline.py +6 -7
  144. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  145. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
  146. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +11 -10
  147. diffusers/pipelines/chroma/__init__.py +49 -0
  148. diffusers/pipelines/chroma/pipeline_chroma.py +949 -0
  149. diffusers/pipelines/chroma/pipeline_chroma_img2img.py +1034 -0
  150. diffusers/pipelines/chroma/pipeline_output.py +21 -0
  151. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +8 -8
  152. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +8 -8
  153. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +8 -8
  154. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +8 -8
  155. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +9 -9
  156. diffusers/pipelines/cogview4/pipeline_cogview4.py +7 -7
  157. diffusers/pipelines/cogview4/pipeline_cogview4_control.py +7 -7
  158. diffusers/pipelines/consisid/consisid_utils.py +2 -2
  159. diffusers/pipelines/consisid/pipeline_consisid.py +8 -8
  160. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  161. diffusers/pipelines/controlnet/pipeline_controlnet.py +7 -7
  162. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +8 -8
  163. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +7 -7
  164. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +7 -7
  165. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +14 -14
  166. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +10 -6
  167. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +13 -13
  168. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +14 -14
  169. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +5 -5
  170. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +13 -13
  171. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  172. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +8 -8
  173. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +7 -7
  174. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
  175. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +12 -10
  176. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +9 -7
  177. diffusers/pipelines/cosmos/__init__.py +54 -0
  178. diffusers/pipelines/cosmos/pipeline_cosmos2_text2image.py +673 -0
  179. diffusers/pipelines/cosmos/pipeline_cosmos2_video2world.py +792 -0
  180. diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +664 -0
  181. diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +826 -0
  182. diffusers/pipelines/cosmos/pipeline_output.py +40 -0
  183. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +5 -4
  184. diffusers/pipelines/ddim/pipeline_ddim.py +4 -4
  185. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
  186. diffusers/pipelines/deepfloyd_if/pipeline_if.py +10 -10
  187. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +10 -10
  188. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +10 -10
  189. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +10 -10
  190. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +10 -10
  191. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +10 -10
  192. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +8 -8
  193. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -5
  194. diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
  195. diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +3 -3
  196. diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
  197. diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +2 -2
  198. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +4 -3
  199. diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
  200. diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
  201. diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
  202. diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
  203. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
  204. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +7 -7
  205. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py +9 -9
  206. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +10 -10
  207. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -8
  208. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -5
  209. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +18 -18
  210. diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
  211. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +2 -2
  212. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +6 -6
  213. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +5 -5
  214. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +5 -5
  215. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +5 -5
  216. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
  217. diffusers/pipelines/dit/pipeline_dit.py +1 -1
  218. diffusers/pipelines/easyanimate/pipeline_easyanimate.py +4 -4
  219. diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py +4 -4
  220. diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py +7 -6
  221. diffusers/pipelines/flux/modeling_flux.py +1 -1
  222. diffusers/pipelines/flux/pipeline_flux.py +10 -17
  223. diffusers/pipelines/flux/pipeline_flux_control.py +6 -6
  224. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +6 -6
  225. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +6 -6
  226. diffusers/pipelines/flux/pipeline_flux_controlnet.py +6 -6
  227. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +30 -22
  228. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +2 -1
  229. diffusers/pipelines/flux/pipeline_flux_fill.py +6 -6
  230. diffusers/pipelines/flux/pipeline_flux_img2img.py +39 -6
  231. diffusers/pipelines/flux/pipeline_flux_inpaint.py +11 -6
  232. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
  233. diffusers/pipelines/free_init_utils.py +2 -2
  234. diffusers/pipelines/free_noise_utils.py +3 -3
  235. diffusers/pipelines/hidream_image/__init__.py +47 -0
  236. diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1026 -0
  237. diffusers/pipelines/hidream_image/pipeline_output.py +35 -0
  238. diffusers/pipelines/hunyuan_video/__init__.py +2 -0
  239. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py +8 -8
  240. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +8 -8
  241. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_framepack.py +1114 -0
  242. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py +71 -15
  243. diffusers/pipelines/hunyuan_video/pipeline_output.py +19 -0
  244. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +8 -8
  245. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +10 -8
  246. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +6 -6
  247. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +34 -34
  248. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +19 -26
  249. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +7 -7
  250. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +11 -11
  251. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  252. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +35 -35
  253. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +6 -6
  254. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +17 -39
  255. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +17 -45
  256. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +7 -7
  257. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +10 -10
  258. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +10 -10
  259. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +7 -7
  260. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +17 -38
  261. diffusers/pipelines/kolors/pipeline_kolors.py +10 -10
  262. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +12 -12
  263. diffusers/pipelines/kolors/text_encoder.py +3 -3
  264. diffusers/pipelines/kolors/tokenizer.py +1 -1
  265. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +2 -2
  266. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +2 -2
  267. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  268. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py +3 -3
  269. diffusers/pipelines/latte/pipeline_latte.py +12 -12
  270. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +13 -13
  271. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +17 -16
  272. diffusers/pipelines/ltx/__init__.py +4 -0
  273. diffusers/pipelines/ltx/modeling_latent_upsampler.py +188 -0
  274. diffusers/pipelines/ltx/pipeline_ltx.py +51 -6
  275. diffusers/pipelines/ltx/pipeline_ltx_condition.py +107 -29
  276. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +50 -6
  277. diffusers/pipelines/ltx/pipeline_ltx_latent_upsample.py +277 -0
  278. diffusers/pipelines/lumina/pipeline_lumina.py +13 -13
  279. diffusers/pipelines/lumina2/pipeline_lumina2.py +10 -10
  280. diffusers/pipelines/marigold/marigold_image_processing.py +2 -2
  281. diffusers/pipelines/mochi/pipeline_mochi.py +6 -6
  282. diffusers/pipelines/musicldm/pipeline_musicldm.py +16 -13
  283. diffusers/pipelines/omnigen/pipeline_omnigen.py +13 -11
  284. diffusers/pipelines/omnigen/processor_omnigen.py +8 -3
  285. diffusers/pipelines/onnx_utils.py +15 -2
  286. diffusers/pipelines/pag/pag_utils.py +2 -2
  287. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +12 -8
  288. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +7 -7
  289. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +10 -6
  290. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +14 -14
  291. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +8 -8
  292. diffusers/pipelines/pag/pipeline_pag_kolors.py +10 -10
  293. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +11 -11
  294. diffusers/pipelines/pag/pipeline_pag_sana.py +18 -12
  295. diffusers/pipelines/pag/pipeline_pag_sd.py +8 -8
  296. diffusers/pipelines/pag/pipeline_pag_sd_3.py +7 -7
  297. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +7 -7
  298. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +6 -6
  299. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +5 -5
  300. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +8 -8
  301. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +16 -15
  302. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +18 -17
  303. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +12 -12
  304. diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
  305. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +8 -7
  306. diffusers/pipelines/pia/pipeline_pia.py +8 -6
  307. diffusers/pipelines/pipeline_flax_utils.py +3 -4
  308. diffusers/pipelines/pipeline_loading_utils.py +89 -13
  309. diffusers/pipelines/pipeline_utils.py +105 -33
  310. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +11 -11
  311. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +11 -11
  312. diffusers/pipelines/sana/__init__.py +4 -0
  313. diffusers/pipelines/sana/pipeline_sana.py +23 -21
  314. diffusers/pipelines/sana/pipeline_sana_controlnet.py +1106 -0
  315. diffusers/pipelines/sana/pipeline_sana_sprint.py +23 -19
  316. diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py +981 -0
  317. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +7 -6
  318. diffusers/pipelines/shap_e/camera.py +1 -1
  319. diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
  320. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
  321. diffusers/pipelines/shap_e/renderer.py +3 -3
  322. diffusers/pipelines/stable_audio/modeling_stable_audio.py +1 -1
  323. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +5 -5
  324. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +8 -8
  325. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +13 -13
  326. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +9 -9
  327. diffusers/pipelines/stable_diffusion/__init__.py +0 -7
  328. diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
  329. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +11 -4
  330. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  331. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +1 -1
  332. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
  333. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +10 -10
  334. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +10 -10
  335. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +10 -10
  336. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +9 -9
  337. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +8 -8
  338. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -5
  339. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +5 -5
  340. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -5
  341. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +5 -5
  342. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +5 -5
  343. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -4
  344. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -5
  345. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +7 -7
  346. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -5
  347. diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
  348. diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
  349. diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
  350. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +7 -7
  351. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +7 -7
  352. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +7 -7
  353. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +12 -8
  354. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +15 -9
  355. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +11 -9
  356. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -9
  357. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +18 -12
  358. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +11 -8
  359. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +11 -8
  360. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +15 -12
  361. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +8 -6
  362. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  363. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +15 -11
  364. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  365. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -15
  366. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -17
  367. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +12 -12
  368. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -15
  369. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +3 -3
  370. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +12 -12
  371. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -17
  372. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +12 -7
  373. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +12 -7
  374. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +15 -13
  375. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +24 -21
  376. diffusers/pipelines/unclip/pipeline_unclip.py +4 -3
  377. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +4 -3
  378. diffusers/pipelines/unclip/text_proj.py +2 -2
  379. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +2 -2
  380. diffusers/pipelines/unidiffuser/modeling_uvit.py +1 -1
  381. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +8 -7
  382. diffusers/pipelines/visualcloze/__init__.py +52 -0
  383. diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.py +444 -0
  384. diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py +952 -0
  385. diffusers/pipelines/visualcloze/visualcloze_utils.py +251 -0
  386. diffusers/pipelines/wan/__init__.py +2 -0
  387. diffusers/pipelines/wan/pipeline_wan.py +17 -12
  388. diffusers/pipelines/wan/pipeline_wan_i2v.py +42 -20
  389. diffusers/pipelines/wan/pipeline_wan_vace.py +976 -0
  390. diffusers/pipelines/wan/pipeline_wan_video2video.py +18 -18
  391. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  392. diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +1 -1
  393. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  394. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
  395. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +16 -15
  396. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +6 -6
  397. diffusers/quantizers/__init__.py +179 -1
  398. diffusers/quantizers/base.py +6 -1
  399. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -0
  400. diffusers/quantizers/bitsandbytes/utils.py +10 -7
  401. diffusers/quantizers/gguf/gguf_quantizer.py +13 -4
  402. diffusers/quantizers/gguf/utils.py +16 -13
  403. diffusers/quantizers/quantization_config.py +18 -16
  404. diffusers/quantizers/quanto/quanto_quantizer.py +4 -0
  405. diffusers/quantizers/torchao/torchao_quantizer.py +5 -1
  406. diffusers/schedulers/__init__.py +3 -1
  407. diffusers/schedulers/deprecated/scheduling_karras_ve.py +4 -3
  408. diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
  409. diffusers/schedulers/scheduling_consistency_models.py +1 -1
  410. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +10 -5
  411. diffusers/schedulers/scheduling_ddim.py +8 -8
  412. diffusers/schedulers/scheduling_ddim_cogvideox.py +5 -5
  413. diffusers/schedulers/scheduling_ddim_flax.py +6 -6
  414. diffusers/schedulers/scheduling_ddim_inverse.py +6 -6
  415. diffusers/schedulers/scheduling_ddim_parallel.py +22 -22
  416. diffusers/schedulers/scheduling_ddpm.py +9 -9
  417. diffusers/schedulers/scheduling_ddpm_flax.py +7 -7
  418. diffusers/schedulers/scheduling_ddpm_parallel.py +18 -18
  419. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +2 -2
  420. diffusers/schedulers/scheduling_deis_multistep.py +8 -8
  421. diffusers/schedulers/scheduling_dpm_cogvideox.py +5 -5
  422. diffusers/schedulers/scheduling_dpmsolver_multistep.py +12 -12
  423. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +22 -20
  424. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +11 -11
  425. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -2
  426. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -13
  427. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +13 -8
  428. diffusers/schedulers/scheduling_edm_euler.py +20 -11
  429. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +3 -3
  430. diffusers/schedulers/scheduling_euler_discrete.py +3 -3
  431. diffusers/schedulers/scheduling_euler_discrete_flax.py +3 -3
  432. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +20 -5
  433. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +1 -1
  434. diffusers/schedulers/scheduling_flow_match_lcm.py +561 -0
  435. diffusers/schedulers/scheduling_heun_discrete.py +2 -2
  436. diffusers/schedulers/scheduling_ipndm.py +2 -2
  437. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -2
  438. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -2
  439. diffusers/schedulers/scheduling_karras_ve_flax.py +5 -5
  440. diffusers/schedulers/scheduling_lcm.py +3 -3
  441. diffusers/schedulers/scheduling_lms_discrete.py +2 -2
  442. diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
  443. diffusers/schedulers/scheduling_pndm.py +4 -4
  444. diffusers/schedulers/scheduling_pndm_flax.py +4 -4
  445. diffusers/schedulers/scheduling_repaint.py +9 -9
  446. diffusers/schedulers/scheduling_sasolver.py +15 -15
  447. diffusers/schedulers/scheduling_scm.py +1 -1
  448. diffusers/schedulers/scheduling_sde_ve.py +1 -1
  449. diffusers/schedulers/scheduling_sde_ve_flax.py +2 -2
  450. diffusers/schedulers/scheduling_tcd.py +3 -3
  451. diffusers/schedulers/scheduling_unclip.py +5 -5
  452. diffusers/schedulers/scheduling_unipc_multistep.py +11 -11
  453. diffusers/schedulers/scheduling_utils.py +1 -1
  454. diffusers/schedulers/scheduling_utils_flax.py +1 -1
  455. diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
  456. diffusers/training_utils.py +13 -5
  457. diffusers/utils/__init__.py +5 -0
  458. diffusers/utils/accelerate_utils.py +1 -1
  459. diffusers/utils/doc_utils.py +1 -1
  460. diffusers/utils/dummy_pt_objects.py +120 -0
  461. diffusers/utils/dummy_torch_and_transformers_objects.py +225 -0
  462. diffusers/utils/dynamic_modules_utils.py +21 -3
  463. diffusers/utils/export_utils.py +1 -1
  464. diffusers/utils/import_utils.py +81 -18
  465. diffusers/utils/logging.py +1 -1
  466. diffusers/utils/outputs.py +2 -1
  467. diffusers/utils/peft_utils.py +91 -8
  468. diffusers/utils/state_dict_utils.py +20 -3
  469. diffusers/utils/testing_utils.py +59 -7
  470. diffusers/utils/torch_utils.py +25 -5
  471. diffusers/video_processor.py +2 -2
  472. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/METADATA +3 -3
  473. diffusers-0.34.0.dist-info/RECORD +639 -0
  474. diffusers-0.33.0.dist-info/RECORD +0 -608
  475. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/LICENSE +0 -0
  476. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/WHEEL +0 -0
  477. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/entry_points.txt +0 -0
  478. {diffusers-0.33.0.dist-info → diffusers-0.34.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,952 @@
1
+ # Copyright 2025 VisualCloze team 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
+ from typing import Any, Callable, Dict, List, Optional, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
20
+
21
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
22
+ from ...models.autoencoders import AutoencoderKL
23
+ from ...models.transformers import FluxTransformer2DModel
24
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
25
+ from ...utils import (
26
+ USE_PEFT_BACKEND,
27
+ is_torch_xla_available,
28
+ logging,
29
+ replace_example_docstring,
30
+ scale_lora_layers,
31
+ unscale_lora_layers,
32
+ )
33
+ from ...utils.torch_utils import randn_tensor
34
+ from ..flux.pipeline_flux_fill import calculate_shift, retrieve_latents, retrieve_timesteps
35
+ from ..flux.pipeline_output import FluxPipelineOutput
36
+ from ..pipeline_utils import DiffusionPipeline
37
+ from .visualcloze_utils import VisualClozeProcessor
38
+
39
+
40
+ if is_torch_xla_available():
41
+ import torch_xla.core.xla_model as xm
42
+
43
+ XLA_AVAILABLE = True
44
+ else:
45
+ XLA_AVAILABLE = False
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+
51
+ EXAMPLE_DOC_STRING = """
52
+ Examples:
53
+ ```python
54
+ >>> import torch
55
+ >>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
56
+ >>> from diffusers.utils import load_image
57
+ >>> from PIL import Image
58
+
59
+ >>> image_paths = [
60
+ ... # in-context examples
61
+ ... [
62
+ ... load_image(
63
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
64
+ ... ),
65
+ ... load_image(
66
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
67
+ ... ),
68
+ ... ],
69
+ ... # query with the target image
70
+ ... [
71
+ ... load_image(
72
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
73
+ ... ),
74
+ ... None, # No image needed for the target image
75
+ ... ],
76
+ ... ]
77
+ >>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
78
+ >>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
79
+ >>> pipe = VisualClozeGenerationPipeline.from_pretrained(
80
+ ... "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
81
+ ... )
82
+ >>> pipe.to("cuda")
83
+
84
+ >>> image = pipe(
85
+ ... task_prompt=task_prompt,
86
+ ... content_prompt=content_prompt,
87
+ ... image=image_paths,
88
+ ... guidance_scale=30,
89
+ ... num_inference_steps=30,
90
+ ... max_sequence_length=512,
91
+ ... generator=torch.Generator("cpu").manual_seed(0),
92
+ ... ).images[0][0]
93
+
94
+ >>> # optional, upsampling the generated image
95
+ >>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
96
+ >>> pipe_upsample.to("cuda")
97
+
98
+ >>> mask_image = Image.new("RGB", image.size, (255, 255, 255))
99
+
100
+ >>> image = pipe_upsample(
101
+ ... image=image,
102
+ ... mask_image=mask_image,
103
+ ... prompt=content_prompt,
104
+ ... width=1344,
105
+ ... height=768,
106
+ ... strength=0.4,
107
+ ... guidance_scale=30,
108
+ ... num_inference_steps=30,
109
+ ... max_sequence_length=512,
110
+ ... generator=torch.Generator("cpu").manual_seed(0),
111
+ ... ).images[0]
112
+
113
+ >>> image.save("visualcloze.png")
114
+ ```
115
+ """
116
+
117
+
118
+ class VisualClozeGenerationPipeline(
119
+ DiffusionPipeline,
120
+ FluxLoraLoaderMixin,
121
+ FromSingleFileMixin,
122
+ TextualInversionLoaderMixin,
123
+ ):
124
+ r"""
125
+ The VisualCloze pipeline for image generation with visual context. Reference:
126
+ https://github.com/lzyhha/VisualCloze/tree/main This pipeline is designed to generate images based on visual
127
+ in-context examples.
128
+
129
+ Args:
130
+ transformer ([`FluxTransformer2DModel`]):
131
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
132
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
133
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
134
+ vae ([`AutoencoderKL`]):
135
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
136
+ text_encoder ([`CLIPTextModel`]):
137
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
138
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
139
+ text_encoder_2 ([`T5EncoderModel`]):
140
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
141
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
142
+ tokenizer (`CLIPTokenizer`):
143
+ Tokenizer of class
144
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
145
+ tokenizer_2 (`T5TokenizerFast`):
146
+ Second Tokenizer of class
147
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
148
+ resolution (`int`, *optional*, defaults to 384):
149
+ The resolution of each image when concatenating images from the query and in-context examples.
150
+ """
151
+
152
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
153
+ _optional_components = []
154
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
155
+
156
+ def __init__(
157
+ self,
158
+ scheduler: FlowMatchEulerDiscreteScheduler,
159
+ vae: AutoencoderKL,
160
+ text_encoder: CLIPTextModel,
161
+ tokenizer: CLIPTokenizer,
162
+ text_encoder_2: T5EncoderModel,
163
+ tokenizer_2: T5TokenizerFast,
164
+ transformer: FluxTransformer2DModel,
165
+ resolution: int = 384,
166
+ ):
167
+ super().__init__()
168
+
169
+ self.register_modules(
170
+ vae=vae,
171
+ text_encoder=text_encoder,
172
+ text_encoder_2=text_encoder_2,
173
+ tokenizer=tokenizer,
174
+ tokenizer_2=tokenizer_2,
175
+ transformer=transformer,
176
+ scheduler=scheduler,
177
+ )
178
+ self.resolution = resolution
179
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
180
+ # Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
181
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
182
+ self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
183
+ self.image_processor = VisualClozeProcessor(
184
+ vae_scale_factor=self.vae_scale_factor * 2, vae_latent_channels=self.latent_channels, resolution=resolution
185
+ )
186
+ self.tokenizer_max_length = (
187
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
188
+ )
189
+ self.default_sample_size = 128
190
+
191
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
192
+ def _get_t5_prompt_embeds(
193
+ self,
194
+ prompt: Union[str, List[str]] = None,
195
+ num_images_per_prompt: int = 1,
196
+ max_sequence_length: int = 512,
197
+ device: Optional[torch.device] = None,
198
+ dtype: Optional[torch.dtype] = None,
199
+ ):
200
+ device = device or self._execution_device
201
+ dtype = dtype or self.text_encoder.dtype
202
+
203
+ prompt = [prompt] if isinstance(prompt, str) else prompt
204
+ batch_size = len(prompt)
205
+
206
+ if isinstance(self, TextualInversionLoaderMixin):
207
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
208
+
209
+ text_inputs = self.tokenizer_2(
210
+ prompt,
211
+ padding="max_length",
212
+ max_length=max_sequence_length,
213
+ truncation=True,
214
+ return_length=False,
215
+ return_overflowing_tokens=False,
216
+ return_tensors="pt",
217
+ )
218
+ text_input_ids = text_inputs.input_ids
219
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
220
+
221
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
222
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
223
+ logger.warning(
224
+ "The following part of your input was truncated because `max_sequence_length` is set to "
225
+ f" {max_sequence_length} tokens: {removed_text}"
226
+ )
227
+
228
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
229
+
230
+ dtype = self.text_encoder_2.dtype
231
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
232
+
233
+ _, seq_len, _ = prompt_embeds.shape
234
+
235
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
236
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
237
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
238
+
239
+ return prompt_embeds
240
+
241
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
242
+ def _get_clip_prompt_embeds(
243
+ self,
244
+ prompt: Union[str, List[str]],
245
+ num_images_per_prompt: int = 1,
246
+ device: Optional[torch.device] = None,
247
+ ):
248
+ device = device or self._execution_device
249
+
250
+ prompt = [prompt] if isinstance(prompt, str) else prompt
251
+ batch_size = len(prompt)
252
+
253
+ if isinstance(self, TextualInversionLoaderMixin):
254
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
255
+
256
+ text_inputs = self.tokenizer(
257
+ prompt,
258
+ padding="max_length",
259
+ max_length=self.tokenizer_max_length,
260
+ truncation=True,
261
+ return_overflowing_tokens=False,
262
+ return_length=False,
263
+ return_tensors="pt",
264
+ )
265
+
266
+ text_input_ids = text_inputs.input_ids
267
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
268
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
269
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
270
+ logger.warning(
271
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
272
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
273
+ )
274
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
275
+
276
+ # Use pooled output of CLIPTextModel
277
+ prompt_embeds = prompt_embeds.pooler_output
278
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
279
+
280
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
281
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
282
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
283
+
284
+ return prompt_embeds
285
+
286
+ # Modified from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
287
+ def encode_prompt(
288
+ self,
289
+ layout_prompt: Union[str, List[str]],
290
+ task_prompt: Union[str, List[str]],
291
+ content_prompt: Union[str, List[str]],
292
+ device: Optional[torch.device] = None,
293
+ num_images_per_prompt: int = 1,
294
+ prompt_embeds: Optional[torch.FloatTensor] = None,
295
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
296
+ max_sequence_length: int = 512,
297
+ lora_scale: Optional[float] = None,
298
+ ):
299
+ r"""
300
+
301
+ Args:
302
+ layout_prompt (`str` or `List[str]`, *optional*):
303
+ The prompt or prompts to define the number of in-context examples and the number of images involved in
304
+ the task.
305
+ task_prompt (`str` or `List[str]`, *optional*):
306
+ The prompt or prompts to define the task intention.
307
+ content_prompt (`str` or `List[str]`, *optional*):
308
+ The prompt or prompts to define the content or caption of the target image to be generated.
309
+ device: (`torch.device`):
310
+ torch device
311
+ num_images_per_prompt (`int`):
312
+ number of images that should be generated per prompt
313
+ prompt_embeds (`torch.FloatTensor`, *optional*):
314
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
315
+ provided, text embeddings will be generated from `prompt` input argument.
316
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
317
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
318
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
319
+ lora_scale (`float`, *optional*):
320
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
321
+ """
322
+ device = device or self._execution_device
323
+
324
+ # set lora scale so that monkey patched LoRA
325
+ # function of text encoder can correctly access it
326
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
327
+ self._lora_scale = lora_scale
328
+
329
+ # dynamically adjust the LoRA scale
330
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
331
+ scale_lora_layers(self.text_encoder, lora_scale)
332
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
333
+ scale_lora_layers(self.text_encoder_2, lora_scale)
334
+
335
+ if isinstance(layout_prompt, str):
336
+ layout_prompt = [layout_prompt]
337
+ task_prompt = [task_prompt]
338
+ content_prompt = [content_prompt]
339
+
340
+ def _preprocess(prompt, content=False):
341
+ if prompt is not None:
342
+ return f"The last image of the last row depicts: {prompt}" if content else prompt
343
+ else:
344
+ return ""
345
+
346
+ prompt = [
347
+ f"{_preprocess(layout_prompt[i])} {_preprocess(task_prompt[i])} {_preprocess(content_prompt[i], content=True)}".strip()
348
+ for i in range(len(layout_prompt))
349
+ ]
350
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
351
+ prompt=prompt,
352
+ device=device,
353
+ num_images_per_prompt=num_images_per_prompt,
354
+ )
355
+ prompt_embeds = self._get_t5_prompt_embeds(
356
+ prompt=prompt,
357
+ num_images_per_prompt=num_images_per_prompt,
358
+ max_sequence_length=max_sequence_length,
359
+ device=device,
360
+ )
361
+
362
+ if self.text_encoder is not None:
363
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
364
+ # Retrieve the original scale by scaling back the LoRA layers
365
+ unscale_lora_layers(self.text_encoder, lora_scale)
366
+
367
+ if self.text_encoder_2 is not None:
368
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
369
+ # Retrieve the original scale by scaling back the LoRA layers
370
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
371
+
372
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
373
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
374
+
375
+ return prompt_embeds, pooled_prompt_embeds, text_ids
376
+
377
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
378
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
379
+ if isinstance(generator, list):
380
+ image_latents = [
381
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
382
+ for i in range(image.shape[0])
383
+ ]
384
+ image_latents = torch.cat(image_latents, dim=0)
385
+ else:
386
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
387
+
388
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
389
+
390
+ return image_latents
391
+
392
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
393
+ def get_timesteps(self, num_inference_steps, strength, device):
394
+ # get the original timestep using init_timestep
395
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
396
+
397
+ t_start = int(max(num_inference_steps - init_timestep, 0))
398
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
399
+ if hasattr(self.scheduler, "set_begin_index"):
400
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
401
+
402
+ return timesteps, num_inference_steps - t_start
403
+
404
+ def check_inputs(
405
+ self,
406
+ image,
407
+ task_prompt,
408
+ content_prompt,
409
+ prompt_embeds=None,
410
+ pooled_prompt_embeds=None,
411
+ callback_on_step_end_tensor_inputs=None,
412
+ max_sequence_length=None,
413
+ ):
414
+ if callback_on_step_end_tensor_inputs is not None and not all(
415
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
416
+ ):
417
+ raise ValueError(
418
+ 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]}"
419
+ )
420
+
421
+ # Validate prompt inputs
422
+ if (task_prompt is not None or content_prompt is not None) and prompt_embeds is not None:
423
+ raise ValueError("Cannot provide both text `task_prompt` + `content_prompt` and `prompt_embeds`. ")
424
+
425
+ if task_prompt is None and content_prompt is None and prompt_embeds is None:
426
+ raise ValueError("Must provide either `task_prompt` + `content_prompt` or pre-computed `prompt_embeds`. ")
427
+
428
+ # Validate prompt types and consistency
429
+ if task_prompt is None:
430
+ raise ValueError("`task_prompt` is missing.")
431
+
432
+ if task_prompt is not None and not isinstance(task_prompt, (str, list)):
433
+ raise ValueError(f"`task_prompt` must be str or list, got {type(task_prompt)}")
434
+
435
+ if content_prompt is not None and not isinstance(content_prompt, (str, list)):
436
+ raise ValueError(f"`content_prompt` must be str or list, got {type(content_prompt)}")
437
+
438
+ if isinstance(task_prompt, list) or isinstance(content_prompt, list):
439
+ if not isinstance(task_prompt, list) or not isinstance(content_prompt, list):
440
+ raise ValueError(
441
+ f"`task_prompt` and `content_prompt` must both be lists, or both be of type str or None, "
442
+ f"got {type(task_prompt)} and {type(content_prompt)}"
443
+ )
444
+ if len(content_prompt) != len(task_prompt):
445
+ raise ValueError("`task_prompt` and `content_prompt` must have the same length whe they are lists.")
446
+
447
+ for sample in image:
448
+ if not isinstance(sample, list) or not isinstance(sample[0], list):
449
+ raise ValueError("Each sample in the batch must have a 2D list of images.")
450
+ if len({len(row) for row in sample}) != 1:
451
+ raise ValueError("Each in-context example and query should contain the same number of images.")
452
+ if not any(img is None for img in sample[-1]):
453
+ raise ValueError("There are no targets in the query, which should be represented as None.")
454
+ for row in sample[:-1]:
455
+ if any(img is None for img in row):
456
+ raise ValueError("Images are missing in in-context examples.")
457
+
458
+ # Validate embeddings
459
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
460
+ raise ValueError(
461
+ "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`."
462
+ )
463
+
464
+ # Validate sequence length
465
+ if max_sequence_length is not None and max_sequence_length > 512:
466
+ raise ValueError(f"max_sequence_length cannot exceed 512, got {max_sequence_length}")
467
+
468
+ @staticmethod
469
+ def _prepare_latent_image_ids(image, vae_scale_factor, device, dtype):
470
+ latent_image_ids = []
471
+
472
+ for idx, img in enumerate(image, start=1):
473
+ img = img.squeeze(0)
474
+ channels, height, width = img.shape
475
+
476
+ num_patches_h = height // vae_scale_factor // 2
477
+ num_patches_w = width // vae_scale_factor // 2
478
+
479
+ patch_ids = torch.zeros(num_patches_h, num_patches_w, 3, device=device, dtype=dtype)
480
+ patch_ids[..., 0] = idx
481
+ patch_ids[..., 1] = torch.arange(num_patches_h, device=device, dtype=dtype)[:, None]
482
+ patch_ids[..., 2] = torch.arange(num_patches_w, device=device, dtype=dtype)[None, :]
483
+
484
+ patch_ids = patch_ids.reshape(-1, 3)
485
+ latent_image_ids.append(patch_ids)
486
+
487
+ return torch.cat(latent_image_ids, dim=0)
488
+
489
+ @staticmethod
490
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
491
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
492
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
493
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
494
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
495
+
496
+ return latents
497
+
498
+ @staticmethod
499
+ def _unpack_latents(latents, sizes, vae_scale_factor):
500
+ batch_size, num_patches, channels = latents.shape
501
+
502
+ start = 0
503
+ unpacked_latents = []
504
+ for i in range(len(sizes)):
505
+ cur_size = sizes[i]
506
+ height = cur_size[0][0] // vae_scale_factor
507
+ width = sum([size[1] for size in cur_size]) // vae_scale_factor
508
+
509
+ end = start + (height * width) // 4
510
+
511
+ cur_latents = latents[:, start:end]
512
+ cur_latents = cur_latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
513
+ cur_latents = cur_latents.permute(0, 3, 1, 4, 2, 5)
514
+ cur_latents = cur_latents.reshape(batch_size, channels // (2 * 2), height, width)
515
+
516
+ unpacked_latents.append(cur_latents)
517
+
518
+ start = end
519
+
520
+ return unpacked_latents
521
+
522
+ def enable_vae_slicing(self):
523
+ r"""
524
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
525
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
526
+ """
527
+ self.vae.enable_slicing()
528
+
529
+ def disable_vae_slicing(self):
530
+ r"""
531
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
532
+ computing decoding in one step.
533
+ """
534
+ self.vae.disable_slicing()
535
+
536
+ def enable_vae_tiling(self):
537
+ r"""
538
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
539
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
540
+ processing larger images.
541
+ """
542
+ self.vae.enable_tiling()
543
+
544
+ def disable_vae_tiling(self):
545
+ r"""
546
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
547
+ computing decoding in one step.
548
+ """
549
+ self.vae.disable_tiling()
550
+
551
+ def _prepare_latents(self, image, mask, gen, vae_scale_factor, device, dtype):
552
+ """Helper function to prepare latents for a single batch."""
553
+ # Concatenate images and masks along width dimension
554
+ image = [torch.cat(img, dim=3).to(device=device, dtype=dtype) for img in image]
555
+ mask = [torch.cat(m, dim=3).to(device=device, dtype=dtype) for m in mask]
556
+
557
+ # Generate latent image IDs
558
+ latent_image_ids = self._prepare_latent_image_ids(image, vae_scale_factor, device, dtype)
559
+
560
+ # For initial encoding, use actual images
561
+ image_latent = [self._encode_vae_image(img, gen) for img in image]
562
+ masked_image_latent = [img.clone() for img in image_latent]
563
+
564
+ for i in range(len(image_latent)):
565
+ # Rearrange latents and masks for patch processing
566
+ num_channels_latents, height, width = image_latent[i].shape[1:]
567
+ image_latent[i] = self._pack_latents(image_latent[i], 1, num_channels_latents, height, width)
568
+ masked_image_latent[i] = self._pack_latents(masked_image_latent[i], 1, num_channels_latents, height, width)
569
+
570
+ # Rearrange masks for patch processing
571
+ num_channels_latents, height, width = mask[i].shape[1:]
572
+ mask[i] = mask[i].view(
573
+ 1,
574
+ num_channels_latents,
575
+ height // vae_scale_factor,
576
+ vae_scale_factor,
577
+ width // vae_scale_factor,
578
+ vae_scale_factor,
579
+ )
580
+ mask[i] = mask[i].permute(0, 1, 3, 5, 2, 4)
581
+ mask[i] = mask[i].reshape(
582
+ 1,
583
+ num_channels_latents * (vae_scale_factor**2),
584
+ height // vae_scale_factor,
585
+ width // vae_scale_factor,
586
+ )
587
+ mask[i] = self._pack_latents(
588
+ mask[i],
589
+ 1,
590
+ num_channels_latents * (vae_scale_factor**2),
591
+ height // vae_scale_factor,
592
+ width // vae_scale_factor,
593
+ )
594
+
595
+ # Concatenate along batch dimension
596
+ image_latent = torch.cat(image_latent, dim=1)
597
+ masked_image_latent = torch.cat(masked_image_latent, dim=1)
598
+ mask = torch.cat(mask, dim=1)
599
+
600
+ return image_latent, masked_image_latent, mask, latent_image_ids
601
+
602
+ def prepare_latents(
603
+ self,
604
+ input_image,
605
+ input_mask,
606
+ timestep,
607
+ batch_size,
608
+ dtype,
609
+ device,
610
+ generator,
611
+ vae_scale_factor,
612
+ ):
613
+ if isinstance(generator, list) and len(generator) != batch_size:
614
+ raise ValueError(
615
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
616
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
617
+ )
618
+
619
+ # Process each batch
620
+ masked_image_latents = []
621
+ image_latents = []
622
+ masks = []
623
+ latent_image_ids = []
624
+
625
+ for i in range(len(input_image)):
626
+ _image_latent, _masked_image_latent, _mask, _latent_image_ids = self._prepare_latents(
627
+ input_image[i],
628
+ input_mask[i],
629
+ generator if isinstance(generator, torch.Generator) else generator[i],
630
+ vae_scale_factor,
631
+ device,
632
+ dtype,
633
+ )
634
+ masked_image_latents.append(_masked_image_latent)
635
+ image_latents.append(_image_latent)
636
+ masks.append(_mask)
637
+ latent_image_ids.append(_latent_image_ids)
638
+
639
+ # Concatenate all batches
640
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
641
+ image_latents = torch.cat(image_latents, dim=0)
642
+ masks = torch.cat(masks, dim=0)
643
+
644
+ # Handle batch size expansion
645
+ if batch_size > masked_image_latents.shape[0]:
646
+ if batch_size % masked_image_latents.shape[0] == 0:
647
+ # Expand batches by repeating
648
+ additional_image_per_prompt = batch_size // masked_image_latents.shape[0]
649
+ masked_image_latents = torch.cat([masked_image_latents] * additional_image_per_prompt, dim=0)
650
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
651
+ masks = torch.cat([masks] * additional_image_per_prompt, dim=0)
652
+ else:
653
+ raise ValueError(
654
+ f"Cannot expand batch size from {masked_image_latents.shape[0]} to {batch_size}. "
655
+ "Batch sizes must be multiples of each other."
656
+ )
657
+
658
+ # Add noise to latents
659
+ noises = randn_tensor(image_latents.shape, generator=generator, device=device, dtype=dtype)
660
+ latents = self.scheduler.scale_noise(image_latents, timestep, noises).to(dtype=dtype)
661
+
662
+ # Combine masked latents with masks
663
+ masked_image_latents = torch.cat((masked_image_latents, masks), dim=-1).to(dtype=dtype)
664
+
665
+ return latents, masked_image_latents, latent_image_ids[0]
666
+
667
+ @property
668
+ def guidance_scale(self):
669
+ return self._guidance_scale
670
+
671
+ @property
672
+ def joint_attention_kwargs(self):
673
+ return self._joint_attention_kwargs
674
+
675
+ @property
676
+ def num_timesteps(self):
677
+ return self._num_timesteps
678
+
679
+ @property
680
+ def interrupt(self):
681
+ return self._interrupt
682
+
683
+ @torch.no_grad()
684
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
685
+ def __call__(
686
+ self,
687
+ task_prompt: Union[str, List[str]] = None,
688
+ content_prompt: Union[str, List[str]] = None,
689
+ image: Optional[torch.FloatTensor] = None,
690
+ num_inference_steps: int = 50,
691
+ sigmas: Optional[List[float]] = None,
692
+ guidance_scale: float = 30.0,
693
+ num_images_per_prompt: Optional[int] = 1,
694
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
695
+ latents: Optional[torch.FloatTensor] = None,
696
+ prompt_embeds: Optional[torch.FloatTensor] = None,
697
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
698
+ output_type: Optional[str] = "pil",
699
+ return_dict: bool = True,
700
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
701
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
702
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
703
+ max_sequence_length: int = 512,
704
+ ):
705
+ r"""
706
+ Function invoked when calling the VisualCloze pipeline for generation.
707
+
708
+ Args:
709
+ task_prompt (`str` or `List[str]`, *optional*):
710
+ The prompt or prompts to define the task intention.
711
+ content_prompt (`str` or `List[str]`, *optional*):
712
+ The prompt or prompts to define the content or caption of the target image to be generated.
713
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
714
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
715
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
716
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
717
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)`.
718
+ num_inference_steps (`int`, *optional*, defaults to 50):
719
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
720
+ expense of slower inference.
721
+ sigmas (`List[float]`, *optional*):
722
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
723
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
724
+ will be used.
725
+ guidance_scale (`float`, *optional*, defaults to 30.0):
726
+ Guidance scale as defined in [Classifier-Free Diffusion
727
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
728
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
729
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
730
+ the text `prompt`, usually at the expense of lower image quality.
731
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
732
+ The number of images to generate per prompt.
733
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
734
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
735
+ to make generation deterministic.
736
+ latents (`torch.FloatTensor`, *optional*):
737
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
738
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
739
+ tensor will ge generated by sampling using the supplied random `generator`.
740
+ prompt_embeds (`torch.FloatTensor`, *optional*):
741
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
742
+ provided, text embeddings will be generated from `prompt` input argument.
743
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
744
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
745
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
746
+ output_type (`str`, *optional*, defaults to `"pil"`):
747
+ The output format of the generate image. Choose between
748
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
749
+ return_dict (`bool`, *optional*, defaults to `True`):
750
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
751
+ joint_attention_kwargs (`dict`, *optional*):
752
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
753
+ `self.processor` in
754
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
755
+ callback_on_step_end (`Callable`, *optional*):
756
+ A function that calls at the end of each denoising steps during the inference. The function is called
757
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
758
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
759
+ `callback_on_step_end_tensor_inputs`.
760
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
761
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
762
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
763
+ `._callback_tensor_inputs` attribute of your pipeline class.
764
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
765
+
766
+ Examples:
767
+
768
+ Returns:
769
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
770
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
771
+ images.
772
+ """
773
+
774
+ # 1. Check inputs. Raise error if not correct
775
+ self.check_inputs(
776
+ image,
777
+ task_prompt,
778
+ content_prompt,
779
+ prompt_embeds=prompt_embeds,
780
+ pooled_prompt_embeds=pooled_prompt_embeds,
781
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
782
+ max_sequence_length=max_sequence_length,
783
+ )
784
+
785
+ self._guidance_scale = guidance_scale
786
+ self._joint_attention_kwargs = joint_attention_kwargs
787
+ self._interrupt = False
788
+
789
+ processor_output = self.image_processor.preprocess(
790
+ task_prompt, content_prompt, image, vae_scale_factor=self.vae_scale_factor
791
+ )
792
+
793
+ # 2. Define call parameters
794
+ if processor_output["task_prompt"] is not None and isinstance(processor_output["task_prompt"], str):
795
+ batch_size = 1
796
+ elif processor_output["task_prompt"] is not None and isinstance(processor_output["task_prompt"], list):
797
+ batch_size = len(processor_output["task_prompt"])
798
+
799
+ device = self._execution_device
800
+
801
+ # 3. Prepare prompt embeddings
802
+ lora_scale = (
803
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
804
+ )
805
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
806
+ layout_prompt=processor_output["layout_prompt"],
807
+ task_prompt=processor_output["task_prompt"],
808
+ content_prompt=processor_output["content_prompt"],
809
+ prompt_embeds=prompt_embeds,
810
+ pooled_prompt_embeds=pooled_prompt_embeds,
811
+ device=device,
812
+ num_images_per_prompt=num_images_per_prompt,
813
+ max_sequence_length=max_sequence_length,
814
+ lora_scale=lora_scale,
815
+ )
816
+
817
+ # 4. Prepare timesteps
818
+ # Calculate sequence length and shift factor
819
+ image_seq_len = sum(
820
+ (size[0] // self.vae_scale_factor // 2) * (size[1] // self.vae_scale_factor // 2)
821
+ for sample in processor_output["image_size"][0]
822
+ for size in sample
823
+ )
824
+
825
+ # Calculate noise schedule parameters
826
+ mu = calculate_shift(
827
+ image_seq_len,
828
+ self.scheduler.config.get("base_image_seq_len", 256),
829
+ self.scheduler.config.get("max_image_seq_len", 4096),
830
+ self.scheduler.config.get("base_shift", 0.5),
831
+ self.scheduler.config.get("max_shift", 1.15),
832
+ )
833
+
834
+ # Get timesteps
835
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
836
+ timesteps, num_inference_steps = retrieve_timesteps(
837
+ self.scheduler,
838
+ num_inference_steps,
839
+ device,
840
+ sigmas=sigmas,
841
+ mu=mu,
842
+ )
843
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, 1.0, device)
844
+
845
+ # 5. Prepare latent variables
846
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
847
+ latents, masked_image_latents, latent_image_ids = self.prepare_latents(
848
+ processor_output["init_image"],
849
+ processor_output["mask"],
850
+ latent_timestep,
851
+ batch_size * num_images_per_prompt,
852
+ prompt_embeds.dtype,
853
+ device,
854
+ generator,
855
+ vae_scale_factor=self.vae_scale_factor,
856
+ )
857
+
858
+ # Calculate warmup steps
859
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
860
+ self._num_timesteps = len(timesteps)
861
+
862
+ # Prepare guidance
863
+ if self.transformer.config.guidance_embeds:
864
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
865
+ guidance = guidance.expand(latents.shape[0])
866
+ else:
867
+ guidance = None
868
+
869
+ # 6. Denoising loop
870
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
871
+ for i, t in enumerate(timesteps):
872
+ if self.interrupt:
873
+ continue
874
+
875
+ # Broadcast to batch dimension in a way that's compatible with ONNX/Core ML
876
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
877
+ latent_model_input = torch.cat((latents, masked_image_latents), dim=2)
878
+
879
+ noise_pred = self.transformer(
880
+ hidden_states=latent_model_input,
881
+ timestep=timestep / 1000,
882
+ guidance=guidance,
883
+ pooled_projections=pooled_prompt_embeds,
884
+ encoder_hidden_states=prompt_embeds,
885
+ txt_ids=text_ids,
886
+ img_ids=latent_image_ids,
887
+ joint_attention_kwargs=self.joint_attention_kwargs,
888
+ return_dict=False,
889
+ )[0]
890
+
891
+ # Compute the previous noisy sample x_t -> x_t-1
892
+ latents_dtype = latents.dtype
893
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
894
+
895
+ if latents.dtype != latents_dtype:
896
+ if torch.backends.mps.is_available():
897
+ # Some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
898
+ latents = latents.to(latents_dtype)
899
+
900
+ if callback_on_step_end is not None:
901
+ callback_kwargs = {}
902
+ for k in callback_on_step_end_tensor_inputs:
903
+ callback_kwargs[k] = locals()[k]
904
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
905
+
906
+ latents = callback_outputs.pop("latents", latents)
907
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
908
+
909
+ # Call the callback, if provided
910
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
911
+ progress_bar.update()
912
+
913
+ # XLA optimization
914
+ if XLA_AVAILABLE:
915
+ xm.mark_step()
916
+
917
+ # 7. Post-process the image
918
+ # Crop the target image
919
+ # Since the generated image is a concatenation of the conditional and target regions,
920
+ # we need to extract only the target regions based on their positions
921
+ image = []
922
+ if output_type == "latent":
923
+ image = latents
924
+ else:
925
+ for b in range(len(latents)):
926
+ cur_image_size = processor_output["image_size"][b % batch_size]
927
+ cur_target_position = processor_output["target_position"][b % batch_size]
928
+ cur_latent = self._unpack_latents(latents[b].unsqueeze(0), cur_image_size, self.vae_scale_factor)[-1]
929
+ cur_latent = (cur_latent / self.vae.config.scaling_factor) + self.vae.config.shift_factor
930
+ cur_image = self.vae.decode(cur_latent, return_dict=False)[0]
931
+ cur_image = self.image_processor.postprocess(cur_image, output_type=output_type)[0]
932
+
933
+ start = 0
934
+ cropped = []
935
+ for i, size in enumerate(cur_image_size[-1]):
936
+ if cur_target_position[i]:
937
+ if output_type == "pil":
938
+ cropped.append(cur_image.crop((start, 0, start + size[1], size[0])))
939
+ else:
940
+ cropped.append(cur_image[0 : size[0], start : start + size[1]])
941
+ start += size[1]
942
+ image.append(cropped)
943
+ if output_type != "pil":
944
+ image = np.concatenate([arr[None] for sub_image in image for arr in sub_image], axis=0)
945
+
946
+ # Offload all models
947
+ self.maybe_free_model_hooks()
948
+
949
+ if not return_dict:
950
+ return (image,)
951
+
952
+ return FluxPipelineOutput(images=image)