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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (299) hide show
  1. diffusers/__init__.py +20 -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/configuration_utils.py +7 -3
  7. diffusers/dependency_versions_check.py +1 -1
  8. diffusers/dependency_versions_table.py +2 -2
  9. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  10. diffusers/image_processor.py +110 -4
  11. diffusers/loaders/autoencoder.py +7 -8
  12. diffusers/loaders/controlnet.py +17 -8
  13. diffusers/loaders/ip_adapter.py +86 -23
  14. diffusers/loaders/lora.py +105 -310
  15. diffusers/loaders/lora_conversion_utils.py +1 -1
  16. diffusers/loaders/peft.py +1 -1
  17. diffusers/loaders/single_file.py +51 -12
  18. diffusers/loaders/single_file_utils.py +274 -49
  19. diffusers/loaders/textual_inversion.py +23 -4
  20. diffusers/loaders/unet.py +195 -41
  21. diffusers/loaders/utils.py +1 -1
  22. diffusers/models/__init__.py +3 -1
  23. diffusers/models/activations.py +9 -9
  24. diffusers/models/attention.py +26 -36
  25. diffusers/models/attention_flax.py +1 -1
  26. diffusers/models/attention_processor.py +171 -114
  27. diffusers/models/autoencoders/autoencoder_asym_kl.py +1 -1
  28. diffusers/models/autoencoders/autoencoder_kl.py +3 -1
  29. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  30. diffusers/models/autoencoders/autoencoder_tiny.py +4 -2
  31. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  32. diffusers/models/autoencoders/vae.py +1 -1
  33. diffusers/models/controlnet.py +1 -1
  34. diffusers/models/controlnet_flax.py +1 -1
  35. diffusers/models/downsampling.py +8 -12
  36. diffusers/models/dual_transformer_2d.py +1 -1
  37. diffusers/models/embeddings.py +3 -4
  38. diffusers/models/embeddings_flax.py +1 -1
  39. diffusers/models/lora.py +33 -10
  40. diffusers/models/modeling_flax_pytorch_utils.py +1 -1
  41. diffusers/models/modeling_flax_utils.py +1 -1
  42. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  43. diffusers/models/modeling_utils.py +4 -6
  44. diffusers/models/normalization.py +1 -1
  45. diffusers/models/resnet.py +31 -58
  46. diffusers/models/resnet_flax.py +1 -1
  47. diffusers/models/t5_film_transformer.py +1 -1
  48. diffusers/models/transformer_2d.py +1 -1
  49. diffusers/models/transformer_temporal.py +1 -1
  50. diffusers/models/transformers/dual_transformer_2d.py +1 -1
  51. diffusers/models/transformers/t5_film_transformer.py +1 -1
  52. diffusers/models/transformers/transformer_2d.py +29 -31
  53. diffusers/models/transformers/transformer_temporal.py +1 -1
  54. diffusers/models/unet_1d.py +1 -1
  55. diffusers/models/unet_1d_blocks.py +1 -1
  56. diffusers/models/unet_2d.py +1 -1
  57. diffusers/models/unet_2d_blocks.py +1 -1
  58. diffusers/models/unet_2d_condition.py +1 -1
  59. diffusers/models/unets/__init__.py +1 -0
  60. diffusers/models/unets/unet_1d.py +1 -1
  61. diffusers/models/unets/unet_1d_blocks.py +1 -1
  62. diffusers/models/unets/unet_2d.py +4 -4
  63. diffusers/models/unets/unet_2d_blocks.py +238 -98
  64. diffusers/models/unets/unet_2d_blocks_flax.py +1 -1
  65. diffusers/models/unets/unet_2d_condition.py +420 -323
  66. diffusers/models/unets/unet_2d_condition_flax.py +21 -12
  67. diffusers/models/unets/unet_3d_blocks.py +50 -40
  68. diffusers/models/unets/unet_3d_condition.py +47 -8
  69. diffusers/models/unets/unet_i2vgen_xl.py +75 -30
  70. diffusers/models/unets/unet_kandinsky3.py +1 -1
  71. diffusers/models/unets/unet_motion_model.py +48 -8
  72. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  73. diffusers/models/unets/unet_stable_cascade.py +610 -0
  74. diffusers/models/unets/uvit_2d.py +1 -1
  75. diffusers/models/upsampling.py +10 -16
  76. diffusers/models/vae_flax.py +1 -1
  77. diffusers/models/vq_model.py +1 -1
  78. diffusers/optimization.py +1 -1
  79. diffusers/pipelines/__init__.py +26 -0
  80. diffusers/pipelines/amused/pipeline_amused.py +1 -1
  81. diffusers/pipelines/amused/pipeline_amused_img2img.py +1 -1
  82. diffusers/pipelines/amused/pipeline_amused_inpaint.py +1 -1
  83. diffusers/pipelines/animatediff/pipeline_animatediff.py +162 -417
  84. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +165 -137
  85. diffusers/pipelines/animatediff/pipeline_output.py +7 -6
  86. diffusers/pipelines/audioldm/pipeline_audioldm.py +3 -19
  87. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  88. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +3 -3
  89. diffusers/pipelines/auto_pipeline.py +7 -16
  90. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  91. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  92. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +2 -2
  93. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  94. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  95. diffusers/pipelines/controlnet/pipeline_controlnet.py +90 -90
  96. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  97. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +98 -90
  98. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +92 -90
  99. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +145 -70
  100. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +126 -89
  101. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +108 -96
  102. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  103. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -1
  104. diffusers/pipelines/ddim/pipeline_ddim.py +1 -1
  105. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -1
  106. diffusers/pipelines/deepfloyd_if/pipeline_if.py +4 -4
  107. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +4 -4
  108. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +5 -5
  109. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +4 -4
  110. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +5 -5
  111. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +5 -5
  112. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +10 -120
  113. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +10 -91
  114. diffusers/pipelines/deprecated/audio_diffusion/mel.py +1 -1
  115. diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py +1 -1
  116. diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +1 -1
  117. diffusers/pipelines/deprecated/pndm/pipeline_pndm.py +1 -1
  118. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +1 -1
  119. diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py +1 -1
  120. diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py +1 -1
  121. diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py +1 -1
  122. diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py +1 -1
  123. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -1
  124. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +5 -4
  125. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +5 -4
  126. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +7 -22
  127. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +5 -39
  128. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +5 -5
  129. diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py +1 -1
  130. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +31 -22
  131. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -1
  132. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -1
  133. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -2
  134. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +1 -1
  135. diffusers/pipelines/dit/pipeline_dit.py +1 -1
  136. diffusers/pipelines/free_init_utils.py +184 -0
  137. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +22 -104
  138. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +1 -1
  139. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +1 -1
  140. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +1 -1
  141. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +2 -2
  142. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -1
  143. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  144. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +1 -1
  145. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +1 -1
  146. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +1 -1
  147. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  148. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +2 -2
  149. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +104 -93
  150. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +112 -74
  151. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  152. diffusers/pipelines/ledits_pp/__init__.py +55 -0
  153. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +1505 -0
  154. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +1797 -0
  155. diffusers/pipelines/ledits_pp/pipeline_output.py +43 -0
  156. diffusers/pipelines/musicldm/pipeline_musicldm.py +3 -19
  157. diffusers/pipelines/onnx_utils.py +1 -1
  158. diffusers/pipelines/paint_by_example/image_encoder.py +1 -1
  159. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +3 -3
  160. diffusers/pipelines/pia/pipeline_pia.py +168 -327
  161. diffusers/pipelines/pipeline_flax_utils.py +1 -1
  162. diffusers/pipelines/pipeline_loading_utils.py +508 -0
  163. diffusers/pipelines/pipeline_utils.py +188 -534
  164. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +56 -10
  165. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +3 -3
  166. diffusers/pipelines/shap_e/camera.py +1 -1
  167. diffusers/pipelines/shap_e/pipeline_shap_e.py +1 -1
  168. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +1 -1
  169. diffusers/pipelines/shap_e/renderer.py +1 -1
  170. diffusers/pipelines/stable_cascade/__init__.py +50 -0
  171. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +482 -0
  172. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +311 -0
  173. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +638 -0
  174. diffusers/pipelines/stable_diffusion/clip_image_project_model.py +1 -1
  175. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +4 -1
  176. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  177. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py +2 -2
  178. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py +1 -1
  179. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +1 -1
  180. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +1 -1
  181. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -1
  182. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +1 -1
  183. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +90 -146
  184. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +5 -4
  185. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +4 -32
  186. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -119
  187. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -119
  188. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +13 -59
  189. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +3 -31
  190. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +5 -33
  191. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -21
  192. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +7 -21
  193. diffusers/pipelines/stable_diffusion/safety_checker.py +1 -1
  194. diffusers/pipelines/stable_diffusion/safety_checker_flax.py +1 -1
  195. diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py +1 -1
  196. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +5 -21
  197. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +9 -38
  198. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -34
  199. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +6 -35
  200. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +7 -6
  201. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +4 -124
  202. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +282 -80
  203. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +94 -46
  204. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +3 -3
  205. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  206. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +6 -22
  207. diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py +1 -1
  208. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +96 -148
  209. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +98 -154
  210. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +98 -153
  211. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +25 -87
  212. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +89 -80
  213. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +5 -49
  214. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +80 -88
  215. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +8 -6
  216. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +15 -86
  217. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +20 -93
  218. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +5 -5
  219. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +3 -19
  220. diffusers/pipelines/unclip/pipeline_unclip.py +1 -1
  221. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -1
  222. diffusers/pipelines/unclip/text_proj.py +1 -1
  223. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +35 -35
  224. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  225. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +4 -21
  226. diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py +2 -2
  227. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +4 -5
  228. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +8 -8
  229. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +1 -1
  230. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +2 -2
  231. diffusers/schedulers/__init__.py +7 -1
  232. diffusers/schedulers/deprecated/scheduling_karras_ve.py +1 -1
  233. diffusers/schedulers/deprecated/scheduling_sde_vp.py +1 -1
  234. diffusers/schedulers/scheduling_consistency_models.py +42 -19
  235. diffusers/schedulers/scheduling_ddim.py +2 -4
  236. diffusers/schedulers/scheduling_ddim_flax.py +13 -5
  237. diffusers/schedulers/scheduling_ddim_inverse.py +2 -4
  238. diffusers/schedulers/scheduling_ddim_parallel.py +2 -4
  239. diffusers/schedulers/scheduling_ddpm.py +2 -4
  240. diffusers/schedulers/scheduling_ddpm_flax.py +1 -1
  241. diffusers/schedulers/scheduling_ddpm_parallel.py +2 -4
  242. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +1 -1
  243. diffusers/schedulers/scheduling_deis_multistep.py +46 -19
  244. diffusers/schedulers/scheduling_dpmsolver_multistep.py +107 -21
  245. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +1 -1
  246. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +9 -7
  247. diffusers/schedulers/scheduling_dpmsolver_sde.py +35 -35
  248. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +49 -18
  249. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +683 -0
  250. diffusers/schedulers/scheduling_edm_euler.py +381 -0
  251. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +43 -15
  252. diffusers/schedulers/scheduling_euler_discrete.py +42 -17
  253. diffusers/schedulers/scheduling_euler_discrete_flax.py +1 -1
  254. diffusers/schedulers/scheduling_heun_discrete.py +35 -35
  255. diffusers/schedulers/scheduling_ipndm.py +37 -11
  256. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +44 -44
  257. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +44 -44
  258. diffusers/schedulers/scheduling_karras_ve_flax.py +1 -1
  259. diffusers/schedulers/scheduling_lcm.py +38 -14
  260. diffusers/schedulers/scheduling_lms_discrete.py +43 -15
  261. diffusers/schedulers/scheduling_lms_discrete_flax.py +1 -1
  262. diffusers/schedulers/scheduling_pndm.py +2 -4
  263. diffusers/schedulers/scheduling_pndm_flax.py +2 -4
  264. diffusers/schedulers/scheduling_repaint.py +1 -1
  265. diffusers/schedulers/scheduling_sasolver.py +41 -9
  266. diffusers/schedulers/scheduling_sde_ve.py +1 -1
  267. diffusers/schedulers/scheduling_sde_ve_flax.py +1 -1
  268. diffusers/schedulers/scheduling_tcd.py +686 -0
  269. diffusers/schedulers/scheduling_unclip.py +1 -1
  270. diffusers/schedulers/scheduling_unipc_multistep.py +46 -19
  271. diffusers/schedulers/scheduling_utils.py +2 -1
  272. diffusers/schedulers/scheduling_utils_flax.py +1 -1
  273. diffusers/schedulers/scheduling_vq_diffusion.py +1 -1
  274. diffusers/training_utils.py +9 -2
  275. diffusers/utils/__init__.py +2 -1
  276. diffusers/utils/accelerate_utils.py +1 -1
  277. diffusers/utils/constants.py +1 -1
  278. diffusers/utils/doc_utils.py +1 -1
  279. diffusers/utils/dummy_pt_objects.py +60 -0
  280. diffusers/utils/dummy_torch_and_transformers_objects.py +75 -0
  281. diffusers/utils/dynamic_modules_utils.py +1 -1
  282. diffusers/utils/export_utils.py +3 -3
  283. diffusers/utils/hub_utils.py +60 -16
  284. diffusers/utils/import_utils.py +15 -1
  285. diffusers/utils/loading_utils.py +2 -0
  286. diffusers/utils/logging.py +1 -1
  287. diffusers/utils/model_card_template.md +24 -0
  288. diffusers/utils/outputs.py +14 -7
  289. diffusers/utils/peft_utils.py +1 -1
  290. diffusers/utils/state_dict_utils.py +1 -1
  291. diffusers/utils/testing_utils.py +2 -0
  292. diffusers/utils/torch_utils.py +1 -1
  293. {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/METADATA +46 -46
  294. diffusers-0.27.0.dist-info/RECORD +399 -0
  295. {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/WHEEL +1 -1
  296. diffusers-0.26.3.dist-info/RECORD +0 -384
  297. {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/LICENSE +0 -0
  298. {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/entry_points.txt +0 -0
  299. {diffusers-0.26.3.dist-info → diffusers-0.27.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,683 @@
1
+ # Copyright 2024 TSAIL 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
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver and https://github.com/NVlabs/edm
16
+
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ from ..configuration_utils import ConfigMixin, register_to_config
23
+ from ..utils.torch_utils import randn_tensor
24
+ from .scheduling_utils import SchedulerMixin, SchedulerOutput
25
+
26
+
27
+ class EDMDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
28
+ """
29
+ Implements DPMSolverMultistepScheduler in EDM formulation as presented in Karras et al. 2022 [1].
30
+ `EDMDPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.
31
+
32
+ [1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models."
33
+ https://arxiv.org/abs/2206.00364
34
+
35
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
36
+ methods the library implements for all schedulers such as loading and saving.
37
+
38
+ Args:
39
+ sigma_min (`float`, *optional*, defaults to 0.002):
40
+ Minimum noise magnitude in the sigma schedule. This was set to 0.002 in the EDM paper [1]; a reasonable
41
+ range is [0, 10].
42
+ sigma_max (`float`, *optional*, defaults to 80.0):
43
+ Maximum noise magnitude in the sigma schedule. This was set to 80.0 in the EDM paper [1]; a reasonable
44
+ range is [0.2, 80.0].
45
+ sigma_data (`float`, *optional*, defaults to 0.5):
46
+ The standard deviation of the data distribution. This is set to 0.5 in the EDM paper [1].
47
+ num_train_timesteps (`int`, defaults to 1000):
48
+ The number of diffusion steps to train the model.
49
+ solver_order (`int`, defaults to 2):
50
+ The DPMSolver order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided
51
+ sampling, and `solver_order=3` for unconditional sampling.
52
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
53
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
54
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
55
+ Video](https://imagen.research.google/video/paper.pdf) paper).
56
+ thresholding (`bool`, defaults to `False`):
57
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
58
+ as Stable Diffusion.
59
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
60
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
61
+ sample_max_value (`float`, defaults to 1.0):
62
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
63
+ `algorithm_type="dpmsolver++"`.
64
+ algorithm_type (`str`, defaults to `dpmsolver++`):
65
+ Algorithm type for the solver; can be `dpmsolver++` or `sde-dpmsolver++`. The
66
+ `dpmsolver++` type implements the algorithms in the
67
+ [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or
68
+ `sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion.
69
+ solver_type (`str`, defaults to `midpoint`):
70
+ Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
71
+ sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
72
+ lower_order_final (`bool`, defaults to `True`):
73
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
74
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
75
+ euler_at_final (`bool`, defaults to `False`):
76
+ Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
77
+ richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
78
+ steps, but sometimes may result in blurring.
79
+ final_sigmas_type (`str`, defaults to `"zero"`):
80
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final sigma
81
+ is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
82
+ """
83
+
84
+ _compatibles = []
85
+ order = 1
86
+
87
+ @register_to_config
88
+ def __init__(
89
+ self,
90
+ sigma_min: float = 0.002,
91
+ sigma_max: float = 80.0,
92
+ sigma_data: float = 0.5,
93
+ num_train_timesteps: int = 1000,
94
+ prediction_type: str = "epsilon",
95
+ rho: float = 7.0,
96
+ solver_order: int = 2,
97
+ thresholding: bool = False,
98
+ dynamic_thresholding_ratio: float = 0.995,
99
+ sample_max_value: float = 1.0,
100
+ algorithm_type: str = "dpmsolver++",
101
+ solver_type: str = "midpoint",
102
+ lower_order_final: bool = True,
103
+ euler_at_final: bool = False,
104
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
105
+ ):
106
+ # settings for DPM-Solver
107
+ if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"]:
108
+ if algorithm_type == "deis":
109
+ self.register_to_config(algorithm_type="dpmsolver++")
110
+ else:
111
+ raise NotImplementedError(f"{algorithm_type} is not implemented for {self.__class__}")
112
+
113
+ if solver_type not in ["midpoint", "heun"]:
114
+ if solver_type in ["logrho", "bh1", "bh2"]:
115
+ self.register_to_config(solver_type="midpoint")
116
+ else:
117
+ raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}")
118
+
119
+ if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"] and final_sigmas_type == "zero":
120
+ raise ValueError(
121
+ f"`final_sigmas_type` {final_sigmas_type} is not supported for `algorithm_type` {algorithm_type}. Please choose `sigma_min` instead."
122
+ )
123
+
124
+ ramp = torch.linspace(0, 1, num_train_timesteps)
125
+ sigmas = self._compute_sigmas(ramp)
126
+ self.timesteps = self.precondition_noise(sigmas)
127
+
128
+ self.sigmas = self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
129
+
130
+ # setable values
131
+ self.num_inference_steps = None
132
+ self.model_outputs = [None] * solver_order
133
+ self.lower_order_nums = 0
134
+ self._step_index = None
135
+ self._begin_index = None
136
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
137
+
138
+ @property
139
+ def init_noise_sigma(self):
140
+ # standard deviation of the initial noise distribution
141
+ return (self.config.sigma_max**2 + 1) ** 0.5
142
+
143
+ @property
144
+ def step_index(self):
145
+ """
146
+ The index counter for current timestep. It will increae 1 after each scheduler step.
147
+ """
148
+ return self._step_index
149
+
150
+ @property
151
+ def begin_index(self):
152
+ """
153
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
154
+ """
155
+ return self._begin_index
156
+
157
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
158
+ def set_begin_index(self, begin_index: int = 0):
159
+ """
160
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
161
+
162
+ Args:
163
+ begin_index (`int`):
164
+ The begin index for the scheduler.
165
+ """
166
+ self._begin_index = begin_index
167
+
168
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.precondition_inputs
169
+ def precondition_inputs(self, sample, sigma):
170
+ c_in = 1 / ((sigma**2 + self.config.sigma_data**2) ** 0.5)
171
+ scaled_sample = sample * c_in
172
+ return scaled_sample
173
+
174
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.precondition_noise
175
+ def precondition_noise(self, sigma):
176
+ if not isinstance(sigma, torch.Tensor):
177
+ sigma = torch.tensor([sigma])
178
+
179
+ c_noise = 0.25 * torch.log(sigma)
180
+
181
+ return c_noise
182
+
183
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.precondition_outputs
184
+ def precondition_outputs(self, sample, model_output, sigma):
185
+ sigma_data = self.config.sigma_data
186
+ c_skip = sigma_data**2 / (sigma**2 + sigma_data**2)
187
+
188
+ if self.config.prediction_type == "epsilon":
189
+ c_out = sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
190
+ elif self.config.prediction_type == "v_prediction":
191
+ c_out = -sigma * sigma_data / (sigma**2 + sigma_data**2) ** 0.5
192
+ else:
193
+ raise ValueError(f"Prediction type {self.config.prediction_type} is not supported.")
194
+
195
+ denoised = c_skip * sample + c_out * model_output
196
+
197
+ return denoised
198
+
199
+ # Copied from diffusers.schedulers.scheduling_edm_euler.EDMEulerScheduler.scale_model_input
200
+ def scale_model_input(
201
+ self, sample: torch.FloatTensor, timestep: Union[float, torch.FloatTensor]
202
+ ) -> torch.FloatTensor:
203
+ """
204
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
205
+ current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.
206
+
207
+ Args:
208
+ sample (`torch.FloatTensor`):
209
+ The input sample.
210
+ timestep (`int`, *optional*):
211
+ The current timestep in the diffusion chain.
212
+
213
+ Returns:
214
+ `torch.FloatTensor`:
215
+ A scaled input sample.
216
+ """
217
+ if self.step_index is None:
218
+ self._init_step_index(timestep)
219
+
220
+ sigma = self.sigmas[self.step_index]
221
+ sample = self.precondition_inputs(sample, sigma)
222
+
223
+ self.is_scale_input_called = True
224
+ return sample
225
+
226
+ def set_timesteps(self, num_inference_steps: int = None, device: Union[str, torch.device] = None):
227
+ """
228
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
229
+
230
+ Args:
231
+ num_inference_steps (`int`):
232
+ The number of diffusion steps used when generating samples with a pre-trained model.
233
+ device (`str` or `torch.device`, *optional*):
234
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
235
+ """
236
+
237
+ self.num_inference_steps = num_inference_steps
238
+
239
+ ramp = np.linspace(0, 1, self.num_inference_steps)
240
+ sigmas = self._compute_sigmas(ramp)
241
+
242
+ sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)
243
+ self.timesteps = self.precondition_noise(sigmas)
244
+
245
+ if self.config.final_sigmas_type == "sigma_min":
246
+ sigma_last = self.config.sigma_min
247
+ elif self.config.final_sigmas_type == "zero":
248
+ sigma_last = 0
249
+ else:
250
+ raise ValueError(
251
+ f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
252
+ )
253
+
254
+ self.sigmas = torch.cat([sigmas, torch.tensor([sigma_last], dtype=torch.float32, device=device)])
255
+
256
+ self.model_outputs = [
257
+ None,
258
+ ] * self.config.solver_order
259
+ self.lower_order_nums = 0
260
+
261
+ # add an index counter for schedulers that allow duplicated timesteps
262
+ self._step_index = None
263
+ self._begin_index = None
264
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
265
+
266
+ # Taken from https://github.com/crowsonkb/k-diffusion/blob/686dbad0f39640ea25c8a8c6a6e56bb40eacefa2/k_diffusion/sampling.py#L17
267
+ def _compute_sigmas(self, ramp, sigma_min=None, sigma_max=None) -> torch.FloatTensor:
268
+ """Constructs the noise schedule of Karras et al. (2022)."""
269
+
270
+ sigma_min = sigma_min or self.config.sigma_min
271
+ sigma_max = sigma_max or self.config.sigma_max
272
+
273
+ rho = self.config.rho
274
+ min_inv_rho = sigma_min ** (1 / rho)
275
+ max_inv_rho = sigma_max ** (1 / rho)
276
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
277
+ return sigmas
278
+
279
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
280
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
281
+ """
282
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
283
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
284
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
285
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
286
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
287
+
288
+ https://arxiv.org/abs/2205.11487
289
+ """
290
+ dtype = sample.dtype
291
+ batch_size, channels, *remaining_dims = sample.shape
292
+
293
+ if dtype not in (torch.float32, torch.float64):
294
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
295
+
296
+ # Flatten sample for doing quantile calculation along each image
297
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
298
+
299
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
300
+
301
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
302
+ s = torch.clamp(
303
+ s, min=1, max=self.config.sample_max_value
304
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
305
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
306
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
307
+
308
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
309
+ sample = sample.to(dtype)
310
+
311
+ return sample
312
+
313
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
314
+ def _sigma_to_t(self, sigma, log_sigmas):
315
+ # get log sigma
316
+ log_sigma = np.log(np.maximum(sigma, 1e-10))
317
+
318
+ # get distribution
319
+ dists = log_sigma - log_sigmas[:, np.newaxis]
320
+
321
+ # get sigmas range
322
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
323
+ high_idx = low_idx + 1
324
+
325
+ low = log_sigmas[low_idx]
326
+ high = log_sigmas[high_idx]
327
+
328
+ # interpolate sigmas
329
+ w = (low - log_sigma) / (low - high)
330
+ w = np.clip(w, 0, 1)
331
+
332
+ # transform interpolation to time range
333
+ t = (1 - w) * low_idx + w * high_idx
334
+ t = t.reshape(sigma.shape)
335
+ return t
336
+
337
+ def _sigma_to_alpha_sigma_t(self, sigma):
338
+ alpha_t = torch.tensor(1) # Inputs are pre-scaled before going into unet, so alpha_t = 1
339
+ sigma_t = sigma
340
+
341
+ return alpha_t, sigma_t
342
+
343
+ def convert_model_output(
344
+ self,
345
+ model_output: torch.FloatTensor,
346
+ sample: torch.FloatTensor = None,
347
+ ) -> torch.FloatTensor:
348
+ """
349
+ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
350
+ designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
351
+ integral of the data prediction model.
352
+
353
+ <Tip>
354
+
355
+ The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
356
+ prediction and data prediction models.
357
+
358
+ </Tip>
359
+
360
+ Args:
361
+ model_output (`torch.FloatTensor`):
362
+ The direct output from the learned diffusion model.
363
+ sample (`torch.FloatTensor`):
364
+ A current instance of a sample created by the diffusion process.
365
+
366
+ Returns:
367
+ `torch.FloatTensor`:
368
+ The converted model output.
369
+ """
370
+ sigma = self.sigmas[self.step_index]
371
+ x0_pred = self.precondition_outputs(sample, model_output, sigma)
372
+
373
+ if self.config.thresholding:
374
+ x0_pred = self._threshold_sample(x0_pred)
375
+
376
+ return x0_pred
377
+
378
+ def dpm_solver_first_order_update(
379
+ self,
380
+ model_output: torch.FloatTensor,
381
+ sample: torch.FloatTensor = None,
382
+ noise: Optional[torch.FloatTensor] = None,
383
+ ) -> torch.FloatTensor:
384
+ """
385
+ One step for the first-order DPMSolver (equivalent to DDIM).
386
+
387
+ Args:
388
+ model_output (`torch.FloatTensor`):
389
+ The direct output from the learned diffusion model.
390
+ sample (`torch.FloatTensor`):
391
+ A current instance of a sample created by the diffusion process.
392
+
393
+ Returns:
394
+ `torch.FloatTensor`:
395
+ The sample tensor at the previous timestep.
396
+ """
397
+ sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
398
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
399
+ alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
400
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
401
+ lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
402
+
403
+ h = lambda_t - lambda_s
404
+ if self.config.algorithm_type == "dpmsolver++":
405
+ x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
406
+ elif self.config.algorithm_type == "sde-dpmsolver++":
407
+ assert noise is not None
408
+ x_t = (
409
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
410
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
411
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
412
+ )
413
+
414
+ return x_t
415
+
416
+ def multistep_dpm_solver_second_order_update(
417
+ self,
418
+ model_output_list: List[torch.FloatTensor],
419
+ sample: torch.FloatTensor = None,
420
+ noise: Optional[torch.FloatTensor] = None,
421
+ ) -> torch.FloatTensor:
422
+ """
423
+ One step for the second-order multistep DPMSolver.
424
+
425
+ Args:
426
+ model_output_list (`List[torch.FloatTensor]`):
427
+ The direct outputs from learned diffusion model at current and latter timesteps.
428
+ sample (`torch.FloatTensor`):
429
+ A current instance of a sample created by the diffusion process.
430
+
431
+ Returns:
432
+ `torch.FloatTensor`:
433
+ The sample tensor at the previous timestep.
434
+ """
435
+ sigma_t, sigma_s0, sigma_s1 = (
436
+ self.sigmas[self.step_index + 1],
437
+ self.sigmas[self.step_index],
438
+ self.sigmas[self.step_index - 1],
439
+ )
440
+
441
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
442
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
443
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
444
+
445
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
446
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
447
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
448
+
449
+ m0, m1 = model_output_list[-1], model_output_list[-2]
450
+
451
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
452
+ r0 = h_0 / h
453
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
454
+ if self.config.algorithm_type == "dpmsolver++":
455
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
456
+ if self.config.solver_type == "midpoint":
457
+ x_t = (
458
+ (sigma_t / sigma_s0) * sample
459
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
460
+ - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
461
+ )
462
+ elif self.config.solver_type == "heun":
463
+ x_t = (
464
+ (sigma_t / sigma_s0) * sample
465
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
466
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
467
+ )
468
+ elif self.config.algorithm_type == "sde-dpmsolver++":
469
+ assert noise is not None
470
+ if self.config.solver_type == "midpoint":
471
+ x_t = (
472
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
473
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
474
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
475
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
476
+ )
477
+ elif self.config.solver_type == "heun":
478
+ x_t = (
479
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
480
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
481
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
482
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
483
+ )
484
+
485
+ return x_t
486
+
487
+ def multistep_dpm_solver_third_order_update(
488
+ self,
489
+ model_output_list: List[torch.FloatTensor],
490
+ sample: torch.FloatTensor = None,
491
+ ) -> torch.FloatTensor:
492
+ """
493
+ One step for the third-order multistep DPMSolver.
494
+
495
+ Args:
496
+ model_output_list (`List[torch.FloatTensor]`):
497
+ The direct outputs from learned diffusion model at current and latter timesteps.
498
+ sample (`torch.FloatTensor`):
499
+ A current instance of a sample created by diffusion process.
500
+
501
+ Returns:
502
+ `torch.FloatTensor`:
503
+ The sample tensor at the previous timestep.
504
+ """
505
+ sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
506
+ self.sigmas[self.step_index + 1],
507
+ self.sigmas[self.step_index],
508
+ self.sigmas[self.step_index - 1],
509
+ self.sigmas[self.step_index - 2],
510
+ )
511
+
512
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
513
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
514
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
515
+ alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
516
+
517
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
518
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
519
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
520
+ lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
521
+
522
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
523
+
524
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
525
+ r0, r1 = h_0 / h, h_1 / h
526
+ D0 = m0
527
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
528
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
529
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
530
+ if self.config.algorithm_type == "dpmsolver++":
531
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
532
+ x_t = (
533
+ (sigma_t / sigma_s0) * sample
534
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
535
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
536
+ - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
537
+ )
538
+
539
+ return x_t
540
+
541
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.index_for_timestep
542
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
543
+ if schedule_timesteps is None:
544
+ schedule_timesteps = self.timesteps
545
+
546
+ index_candidates = (schedule_timesteps == timestep).nonzero()
547
+
548
+ if len(index_candidates) == 0:
549
+ step_index = len(self.timesteps) - 1
550
+ # The sigma index that is taken for the **very** first `step`
551
+ # is always the second index (or the last index if there is only 1)
552
+ # This way we can ensure we don't accidentally skip a sigma in
553
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
554
+ elif len(index_candidates) > 1:
555
+ step_index = index_candidates[1].item()
556
+ else:
557
+ step_index = index_candidates[0].item()
558
+
559
+ return step_index
560
+
561
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
562
+ def _init_step_index(self, timestep):
563
+ """
564
+ Initialize the step_index counter for the scheduler.
565
+ """
566
+
567
+ if self.begin_index is None:
568
+ if isinstance(timestep, torch.Tensor):
569
+ timestep = timestep.to(self.timesteps.device)
570
+ self._step_index = self.index_for_timestep(timestep)
571
+ else:
572
+ self._step_index = self._begin_index
573
+
574
+ def step(
575
+ self,
576
+ model_output: torch.FloatTensor,
577
+ timestep: int,
578
+ sample: torch.FloatTensor,
579
+ generator=None,
580
+ return_dict: bool = True,
581
+ ) -> Union[SchedulerOutput, Tuple]:
582
+ """
583
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
584
+ the multistep DPMSolver.
585
+
586
+ Args:
587
+ model_output (`torch.FloatTensor`):
588
+ The direct output from learned diffusion model.
589
+ timestep (`int`):
590
+ The current discrete timestep in the diffusion chain.
591
+ sample (`torch.FloatTensor`):
592
+ A current instance of a sample created by the diffusion process.
593
+ generator (`torch.Generator`, *optional*):
594
+ A random number generator.
595
+ return_dict (`bool`):
596
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
597
+
598
+ Returns:
599
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
600
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
601
+ tuple is returned where the first element is the sample tensor.
602
+
603
+ """
604
+ if self.num_inference_steps is None:
605
+ raise ValueError(
606
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
607
+ )
608
+
609
+ if self.step_index is None:
610
+ self._init_step_index(timestep)
611
+
612
+ # Improve numerical stability for small number of steps
613
+ lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
614
+ self.config.euler_at_final
615
+ or (self.config.lower_order_final and len(self.timesteps) < 15)
616
+ or self.config.final_sigmas_type == "zero"
617
+ )
618
+ lower_order_second = (
619
+ (self.step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
620
+ )
621
+
622
+ model_output = self.convert_model_output(model_output, sample=sample)
623
+ for i in range(self.config.solver_order - 1):
624
+ self.model_outputs[i] = self.model_outputs[i + 1]
625
+ self.model_outputs[-1] = model_output
626
+
627
+ if self.config.algorithm_type == "sde-dpmsolver++":
628
+ noise = randn_tensor(
629
+ model_output.shape, generator=generator, device=model_output.device, dtype=model_output.dtype
630
+ )
631
+ else:
632
+ noise = None
633
+
634
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
635
+ prev_sample = self.dpm_solver_first_order_update(model_output, sample=sample, noise=noise)
636
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
637
+ prev_sample = self.multistep_dpm_solver_second_order_update(self.model_outputs, sample=sample, noise=noise)
638
+ else:
639
+ prev_sample = self.multistep_dpm_solver_third_order_update(self.model_outputs, sample=sample)
640
+
641
+ if self.lower_order_nums < self.config.solver_order:
642
+ self.lower_order_nums += 1
643
+
644
+ # upon completion increase step index by one
645
+ self._step_index += 1
646
+
647
+ if not return_dict:
648
+ return (prev_sample,)
649
+
650
+ return SchedulerOutput(prev_sample=prev_sample)
651
+
652
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.add_noise
653
+ def add_noise(
654
+ self,
655
+ original_samples: torch.FloatTensor,
656
+ noise: torch.FloatTensor,
657
+ timesteps: torch.FloatTensor,
658
+ ) -> torch.FloatTensor:
659
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
660
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
661
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
662
+ # mps does not support float64
663
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
664
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
665
+ else:
666
+ schedule_timesteps = self.timesteps.to(original_samples.device)
667
+ timesteps = timesteps.to(original_samples.device)
668
+
669
+ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
670
+ if self.begin_index is None:
671
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
672
+ else:
673
+ step_indices = [self.begin_index] * timesteps.shape[0]
674
+
675
+ sigma = sigmas[step_indices].flatten()
676
+ while len(sigma.shape) < len(original_samples.shape):
677
+ sigma = sigma.unsqueeze(-1)
678
+
679
+ noisy_samples = original_samples + noise * sigma
680
+ return noisy_samples
681
+
682
+ def __len__(self):
683
+ return self.config.num_train_timesteps