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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (445) hide show
  1. diffusers/__init__.py +233 -6
  2. diffusers/callbacks.py +209 -0
  3. diffusers/commands/env.py +102 -6
  4. diffusers/configuration_utils.py +45 -16
  5. diffusers/dependency_versions_table.py +4 -3
  6. diffusers/image_processor.py +434 -110
  7. diffusers/loaders/__init__.py +42 -9
  8. diffusers/loaders/ip_adapter.py +626 -36
  9. diffusers/loaders/lora_base.py +900 -0
  10. diffusers/loaders/lora_conversion_utils.py +991 -125
  11. diffusers/loaders/lora_pipeline.py +3812 -0
  12. diffusers/loaders/peft.py +571 -7
  13. diffusers/loaders/single_file.py +405 -173
  14. diffusers/loaders/single_file_model.py +385 -0
  15. diffusers/loaders/single_file_utils.py +1783 -713
  16. diffusers/loaders/textual_inversion.py +41 -23
  17. diffusers/loaders/transformer_flux.py +181 -0
  18. diffusers/loaders/transformer_sd3.py +89 -0
  19. diffusers/loaders/unet.py +464 -540
  20. diffusers/loaders/unet_loader_utils.py +163 -0
  21. diffusers/models/__init__.py +76 -7
  22. diffusers/models/activations.py +65 -10
  23. diffusers/models/adapter.py +53 -53
  24. diffusers/models/attention.py +605 -18
  25. diffusers/models/attention_flax.py +1 -1
  26. diffusers/models/attention_processor.py +4304 -687
  27. diffusers/models/autoencoders/__init__.py +8 -0
  28. diffusers/models/autoencoders/autoencoder_asym_kl.py +15 -17
  29. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  30. diffusers/models/autoencoders/autoencoder_kl.py +110 -28
  31. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  32. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1482 -0
  33. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  34. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  35. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  36. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +19 -24
  37. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  38. diffusers/models/autoencoders/autoencoder_tiny.py +21 -18
  39. diffusers/models/autoencoders/consistency_decoder_vae.py +45 -20
  40. diffusers/models/autoencoders/vae.py +41 -29
  41. diffusers/models/autoencoders/vq_model.py +182 -0
  42. diffusers/models/controlnet.py +47 -800
  43. diffusers/models/controlnet_flux.py +70 -0
  44. diffusers/models/controlnet_sd3.py +68 -0
  45. diffusers/models/controlnet_sparsectrl.py +116 -0
  46. diffusers/models/controlnets/__init__.py +23 -0
  47. diffusers/models/controlnets/controlnet.py +872 -0
  48. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +9 -9
  49. diffusers/models/controlnets/controlnet_flux.py +536 -0
  50. diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
  51. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  52. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  53. diffusers/models/controlnets/controlnet_union.py +832 -0
  54. diffusers/models/controlnets/controlnet_xs.py +1946 -0
  55. diffusers/models/controlnets/multicontrolnet.py +183 -0
  56. diffusers/models/downsampling.py +85 -18
  57. diffusers/models/embeddings.py +1856 -158
  58. diffusers/models/embeddings_flax.py +23 -9
  59. diffusers/models/model_loading_utils.py +480 -0
  60. diffusers/models/modeling_flax_pytorch_utils.py +2 -1
  61. diffusers/models/modeling_flax_utils.py +2 -7
  62. diffusers/models/modeling_outputs.py +14 -0
  63. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  64. diffusers/models/modeling_utils.py +611 -146
  65. diffusers/models/normalization.py +361 -20
  66. diffusers/models/resnet.py +18 -23
  67. diffusers/models/transformers/__init__.py +16 -0
  68. diffusers/models/transformers/auraflow_transformer_2d.py +544 -0
  69. diffusers/models/transformers/cogvideox_transformer_3d.py +542 -0
  70. diffusers/models/transformers/dit_transformer_2d.py +240 -0
  71. diffusers/models/transformers/dual_transformer_2d.py +9 -8
  72. diffusers/models/transformers/hunyuan_transformer_2d.py +578 -0
  73. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  74. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  75. diffusers/models/transformers/pixart_transformer_2d.py +445 -0
  76. diffusers/models/transformers/prior_transformer.py +13 -13
  77. diffusers/models/transformers/sana_transformer.py +488 -0
  78. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  79. diffusers/models/transformers/t5_film_transformer.py +17 -19
  80. diffusers/models/transformers/transformer_2d.py +297 -187
  81. diffusers/models/transformers/transformer_allegro.py +422 -0
  82. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  83. diffusers/models/transformers/transformer_flux.py +593 -0
  84. diffusers/models/transformers/transformer_hunyuan_video.py +791 -0
  85. diffusers/models/transformers/transformer_ltx.py +469 -0
  86. diffusers/models/transformers/transformer_mochi.py +499 -0
  87. diffusers/models/transformers/transformer_sd3.py +461 -0
  88. diffusers/models/transformers/transformer_temporal.py +21 -19
  89. diffusers/models/unets/unet_1d.py +8 -8
  90. diffusers/models/unets/unet_1d_blocks.py +31 -31
  91. diffusers/models/unets/unet_2d.py +17 -10
  92. diffusers/models/unets/unet_2d_blocks.py +225 -149
  93. diffusers/models/unets/unet_2d_condition.py +41 -40
  94. diffusers/models/unets/unet_2d_condition_flax.py +6 -5
  95. diffusers/models/unets/unet_3d_blocks.py +192 -1057
  96. diffusers/models/unets/unet_3d_condition.py +22 -27
  97. diffusers/models/unets/unet_i2vgen_xl.py +22 -18
  98. diffusers/models/unets/unet_kandinsky3.py +2 -2
  99. diffusers/models/unets/unet_motion_model.py +1413 -89
  100. diffusers/models/unets/unet_spatio_temporal_condition.py +40 -16
  101. diffusers/models/unets/unet_stable_cascade.py +19 -18
  102. diffusers/models/unets/uvit_2d.py +2 -2
  103. diffusers/models/upsampling.py +95 -26
  104. diffusers/models/vq_model.py +12 -164
  105. diffusers/optimization.py +1 -1
  106. diffusers/pipelines/__init__.py +202 -3
  107. diffusers/pipelines/allegro/__init__.py +48 -0
  108. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  109. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  110. diffusers/pipelines/amused/pipeline_amused.py +12 -12
  111. diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
  112. diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
  113. diffusers/pipelines/animatediff/__init__.py +8 -0
  114. diffusers/pipelines/animatediff/pipeline_animatediff.py +122 -109
  115. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1106 -0
  116. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1288 -0
  117. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1010 -0
  118. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +236 -180
  119. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  120. diffusers/pipelines/animatediff/pipeline_output.py +3 -2
  121. diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
  122. diffusers/pipelines/audioldm2/modeling_audioldm2.py +58 -39
  123. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +121 -36
  124. diffusers/pipelines/aura_flow/__init__.py +48 -0
  125. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +584 -0
  126. diffusers/pipelines/auto_pipeline.py +196 -28
  127. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  128. diffusers/pipelines/blip_diffusion/modeling_blip2.py +6 -6
  129. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
  130. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  131. diffusers/pipelines/cogvideo/__init__.py +54 -0
  132. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +772 -0
  133. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
  134. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +885 -0
  135. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +851 -0
  136. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  137. diffusers/pipelines/cogview3/__init__.py +47 -0
  138. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  139. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  140. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +6 -6
  141. diffusers/pipelines/controlnet/__init__.py +86 -80
  142. diffusers/pipelines/controlnet/multicontrolnet.py +7 -182
  143. diffusers/pipelines/controlnet/pipeline_controlnet.py +134 -87
  144. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  145. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +93 -77
  146. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +88 -197
  147. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +136 -90
  148. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +176 -80
  149. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +125 -89
  150. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  151. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  152. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  153. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  154. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  155. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1060 -0
  156. diffusers/pipelines/controlnet_sd3/__init__.py +57 -0
  157. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1133 -0
  158. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  159. diffusers/pipelines/controlnet_xs/__init__.py +68 -0
  160. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +916 -0
  161. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1111 -0
  162. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  163. diffusers/pipelines/deepfloyd_if/pipeline_if.py +16 -30
  164. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +20 -35
  165. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +23 -41
  166. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +22 -38
  167. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +25 -41
  168. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +19 -34
  169. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  170. diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
  171. diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
  172. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +70 -30
  173. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +48 -25
  174. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
  175. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
  176. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +21 -20
  177. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +27 -29
  178. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +33 -27
  179. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +33 -23
  180. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +36 -30
  181. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +102 -69
  182. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
  183. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
  184. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
  185. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
  186. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
  187. diffusers/pipelines/dit/pipeline_dit.py +7 -4
  188. diffusers/pipelines/flux/__init__.py +69 -0
  189. diffusers/pipelines/flux/modeling_flux.py +47 -0
  190. diffusers/pipelines/flux/pipeline_flux.py +957 -0
  191. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  192. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  193. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  194. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
  195. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
  196. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
  197. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  198. diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
  199. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
  200. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  201. diffusers/pipelines/flux/pipeline_output.py +37 -0
  202. diffusers/pipelines/free_init_utils.py +41 -38
  203. diffusers/pipelines/free_noise_utils.py +596 -0
  204. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  205. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  206. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  207. diffusers/pipelines/hunyuandit/__init__.py +48 -0
  208. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +916 -0
  209. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
  210. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
  211. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +32 -29
  212. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
  213. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
  214. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
  215. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  216. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +34 -31
  217. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
  218. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
  219. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
  220. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
  221. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
  222. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
  223. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
  224. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +22 -35
  225. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +26 -37
  226. diffusers/pipelines/kolors/__init__.py +54 -0
  227. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  228. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1250 -0
  229. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  230. diffusers/pipelines/kolors/text_encoder.py +889 -0
  231. diffusers/pipelines/kolors/tokenizer.py +338 -0
  232. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +82 -62
  233. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +77 -60
  234. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +12 -12
  235. diffusers/pipelines/latte/__init__.py +48 -0
  236. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  237. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +80 -74
  238. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +85 -76
  239. diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
  240. diffusers/pipelines/ltx/__init__.py +50 -0
  241. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  242. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  243. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  244. diffusers/pipelines/lumina/__init__.py +48 -0
  245. diffusers/pipelines/lumina/pipeline_lumina.py +890 -0
  246. diffusers/pipelines/marigold/__init__.py +50 -0
  247. diffusers/pipelines/marigold/marigold_image_processing.py +576 -0
  248. diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
  249. diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
  250. diffusers/pipelines/mochi/__init__.py +48 -0
  251. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  252. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  253. diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
  254. diffusers/pipelines/pag/__init__.py +80 -0
  255. diffusers/pipelines/pag/pag_utils.py +243 -0
  256. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1328 -0
  257. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
  258. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1610 -0
  259. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
  260. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +969 -0
  261. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  262. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +865 -0
  263. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  264. diffusers/pipelines/pag/pipeline_pag_sd.py +1062 -0
  265. diffusers/pipelines/pag/pipeline_pag_sd_3.py +994 -0
  266. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  267. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +866 -0
  268. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
  269. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  270. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1345 -0
  271. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1544 -0
  272. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1776 -0
  273. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
  274. diffusers/pipelines/pia/pipeline_pia.py +74 -164
  275. diffusers/pipelines/pipeline_flax_utils.py +5 -10
  276. diffusers/pipelines/pipeline_loading_utils.py +515 -53
  277. diffusers/pipelines/pipeline_utils.py +411 -222
  278. diffusers/pipelines/pixart_alpha/__init__.py +8 -1
  279. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +76 -93
  280. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +873 -0
  281. diffusers/pipelines/sana/__init__.py +47 -0
  282. diffusers/pipelines/sana/pipeline_output.py +21 -0
  283. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  284. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +27 -23
  285. diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
  286. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
  287. diffusers/pipelines/shap_e/renderer.py +1 -1
  288. diffusers/pipelines/stable_audio/__init__.py +50 -0
  289. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  290. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +756 -0
  291. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +71 -25
  292. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
  293. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +35 -34
  294. diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  295. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +20 -11
  296. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  297. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  298. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
  299. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +145 -79
  300. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +43 -28
  301. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
  302. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +100 -68
  303. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +109 -201
  304. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +131 -32
  305. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +247 -87
  306. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +30 -29
  307. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +35 -27
  308. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +49 -42
  309. diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
  310. diffusers/pipelines/stable_diffusion_3/__init__.py +54 -0
  311. diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
  312. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1140 -0
  313. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1036 -0
  314. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1250 -0
  315. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +29 -20
  316. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +59 -58
  317. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +31 -25
  318. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +38 -22
  319. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -24
  320. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -23
  321. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +107 -67
  322. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +316 -69
  323. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
  324. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  325. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +98 -30
  326. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +121 -83
  327. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +161 -105
  328. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +142 -218
  329. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -29
  330. diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
  331. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
  332. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +69 -39
  333. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +105 -74
  334. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
  335. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +29 -49
  336. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +32 -93
  337. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +37 -25
  338. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +54 -40
  339. diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
  340. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
  341. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
  342. diffusers/pipelines/unidiffuser/modeling_uvit.py +12 -12
  343. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +29 -28
  344. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
  345. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
  346. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +6 -8
  347. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
  348. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
  349. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +15 -14
  350. diffusers/{models/dual_transformer_2d.py → quantizers/__init__.py} +2 -6
  351. diffusers/quantizers/auto.py +139 -0
  352. diffusers/quantizers/base.py +233 -0
  353. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  354. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
  355. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  356. diffusers/quantizers/gguf/__init__.py +1 -0
  357. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  358. diffusers/quantizers/gguf/utils.py +456 -0
  359. diffusers/quantizers/quantization_config.py +669 -0
  360. diffusers/quantizers/torchao/__init__.py +15 -0
  361. diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
  362. diffusers/schedulers/__init__.py +12 -2
  363. diffusers/schedulers/deprecated/__init__.py +1 -1
  364. diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
  365. diffusers/schedulers/scheduling_amused.py +5 -5
  366. diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
  367. diffusers/schedulers/scheduling_consistency_models.py +23 -25
  368. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  369. diffusers/schedulers/scheduling_ddim.py +27 -26
  370. diffusers/schedulers/scheduling_ddim_cogvideox.py +452 -0
  371. diffusers/schedulers/scheduling_ddim_flax.py +2 -1
  372. diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
  373. diffusers/schedulers/scheduling_ddim_parallel.py +32 -31
  374. diffusers/schedulers/scheduling_ddpm.py +27 -30
  375. diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
  376. diffusers/schedulers/scheduling_ddpm_parallel.py +33 -36
  377. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
  378. diffusers/schedulers/scheduling_deis_multistep.py +150 -50
  379. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  380. diffusers/schedulers/scheduling_dpmsolver_multistep.py +221 -84
  381. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
  382. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +158 -52
  383. diffusers/schedulers/scheduling_dpmsolver_sde.py +153 -34
  384. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +275 -86
  385. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +81 -57
  386. diffusers/schedulers/scheduling_edm_euler.py +62 -39
  387. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +30 -29
  388. diffusers/schedulers/scheduling_euler_discrete.py +255 -74
  389. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +458 -0
  390. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +320 -0
  391. diffusers/schedulers/scheduling_heun_discrete.py +174 -46
  392. diffusers/schedulers/scheduling_ipndm.py +9 -9
  393. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +138 -29
  394. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +132 -26
  395. diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
  396. diffusers/schedulers/scheduling_lcm.py +23 -29
  397. diffusers/schedulers/scheduling_lms_discrete.py +105 -28
  398. diffusers/schedulers/scheduling_pndm.py +20 -20
  399. diffusers/schedulers/scheduling_repaint.py +21 -21
  400. diffusers/schedulers/scheduling_sasolver.py +157 -60
  401. diffusers/schedulers/scheduling_sde_ve.py +19 -19
  402. diffusers/schedulers/scheduling_tcd.py +41 -36
  403. diffusers/schedulers/scheduling_unclip.py +19 -16
  404. diffusers/schedulers/scheduling_unipc_multistep.py +243 -47
  405. diffusers/schedulers/scheduling_utils.py +12 -5
  406. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  407. diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
  408. diffusers/training_utils.py +214 -30
  409. diffusers/utils/__init__.py +17 -1
  410. diffusers/utils/constants.py +3 -0
  411. diffusers/utils/doc_utils.py +1 -0
  412. diffusers/utils/dummy_pt_objects.py +592 -7
  413. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  414. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  415. diffusers/utils/dummy_torch_and_transformers_objects.py +1001 -71
  416. diffusers/utils/dynamic_modules_utils.py +34 -29
  417. diffusers/utils/export_utils.py +50 -6
  418. diffusers/utils/hub_utils.py +131 -17
  419. diffusers/utils/import_utils.py +210 -8
  420. diffusers/utils/loading_utils.py +118 -5
  421. diffusers/utils/logging.py +4 -2
  422. diffusers/utils/peft_utils.py +37 -7
  423. diffusers/utils/state_dict_utils.py +13 -2
  424. diffusers/utils/testing_utils.py +193 -11
  425. diffusers/utils/torch_utils.py +4 -0
  426. diffusers/video_processor.py +113 -0
  427. {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
  428. diffusers-0.32.2.dist-info/RECORD +550 -0
  429. {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/WHEEL +1 -1
  430. diffusers/loaders/autoencoder.py +0 -146
  431. diffusers/loaders/controlnet.py +0 -136
  432. diffusers/loaders/lora.py +0 -1349
  433. diffusers/models/prior_transformer.py +0 -12
  434. diffusers/models/t5_film_transformer.py +0 -70
  435. diffusers/models/transformer_2d.py +0 -25
  436. diffusers/models/transformer_temporal.py +0 -34
  437. diffusers/models/unet_1d.py +0 -26
  438. diffusers/models/unet_1d_blocks.py +0 -203
  439. diffusers/models/unet_2d.py +0 -27
  440. diffusers/models/unet_2d_blocks.py +0 -375
  441. diffusers/models/unet_2d_condition.py +0 -25
  442. diffusers-0.27.1.dist-info/RECORD +0 -399
  443. {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
  444. {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
  445. {diffusers-0.27.1.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
diffusers/loaders/unet.py CHANGED
@@ -11,58 +11,46 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
- import inspect
15
14
  import os
16
15
  from collections import defaultdict
17
16
  from contextlib import nullcontext
18
- from functools import partial
19
17
  from pathlib import Path
20
- from typing import Callable, Dict, List, Optional, Union
18
+ from typing import Callable, Dict, Union
21
19
 
22
20
  import safetensors
23
21
  import torch
24
22
  import torch.nn.functional as F
25
23
  from huggingface_hub.utils import validate_hf_hub_args
26
- from torch import nn
27
24
 
28
25
  from ..models.embeddings import (
29
26
  ImageProjection,
27
+ IPAdapterFaceIDImageProjection,
28
+ IPAdapterFaceIDPlusImageProjection,
30
29
  IPAdapterFullImageProjection,
31
30
  IPAdapterPlusImageProjection,
32
31
  MultiIPAdapterImageProjection,
33
32
  )
34
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
33
+ from ..models.modeling_utils import load_model_dict_into_meta, load_state_dict
35
34
  from ..utils import (
36
35
  USE_PEFT_BACKEND,
37
36
  _get_model_file,
38
- delete_adapter_layers,
37
+ convert_unet_state_dict_to_peft,
38
+ deprecate,
39
+ get_adapter_name,
40
+ get_peft_kwargs,
39
41
  is_accelerate_available,
42
+ is_peft_version,
40
43
  is_torch_version,
41
44
  logging,
42
- set_adapter_layers,
43
- set_weights_and_activate_adapters,
44
- )
45
- from .single_file_utils import (
46
- convert_stable_cascade_unet_single_file_to_diffusers,
47
- infer_stable_cascade_single_file_config,
48
- load_single_file_model_checkpoint,
49
45
  )
46
+ from .lora_base import _func_optionally_disable_offloading
47
+ from .lora_pipeline import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE, TEXT_ENCODER_NAME, UNET_NAME
50
48
  from .utils import AttnProcsLayers
51
49
 
52
50
 
53
- if is_accelerate_available():
54
- from accelerate import init_empty_weights
55
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
56
-
57
51
  logger = logging.get_logger(__name__)
58
52
 
59
53
 
60
- TEXT_ENCODER_NAME = "text_encoder"
61
- UNET_NAME = "unet"
62
-
63
- LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
64
- LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
65
-
66
54
  CUSTOM_DIFFUSION_WEIGHT_NAME = "pytorch_custom_diffusion_weights.bin"
67
55
  CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE = "pytorch_custom_diffusion_weights.safetensors"
68
56
 
@@ -81,7 +69,8 @@ class UNet2DConditionLoadersMixin:
81
69
  Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
82
70
  defined in
83
71
  [`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
84
- and be a `torch.nn.Module` class.
72
+ and be a `torch.nn.Module` class. Currently supported: LoRA, Custom Diffusion. For LoRA, one must install
73
+ `peft`: `pip install -U peft`.
85
74
 
86
75
  Parameters:
87
76
  pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
@@ -100,9 +89,7 @@ class UNet2DConditionLoadersMixin:
100
89
  force_download (`bool`, *optional*, defaults to `False`):
101
90
  Whether or not to force the (re-)download of the model weights and configuration files, overriding the
102
91
  cached versions if they exist.
103
- resume_download (`bool`, *optional*, defaults to `False`):
104
- Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
105
- incompletely downloaded files are deleted.
92
+
106
93
  proxies (`Dict[str, str]`, *optional*):
107
94
  A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
108
95
  'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
@@ -112,20 +99,23 @@ class UNet2DConditionLoadersMixin:
112
99
  token (`str` or *bool*, *optional*):
113
100
  The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
114
101
  `diffusers-cli login` (stored in `~/.huggingface`) is used.
115
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
116
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
117
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
118
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
119
- argument to `True` will raise an error.
120
102
  revision (`str`, *optional*, defaults to `"main"`):
121
103
  The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
122
104
  allowed by Git.
123
105
  subfolder (`str`, *optional*, defaults to `""`):
124
106
  The subfolder location of a model file within a larger model repository on the Hub or locally.
125
- mirror (`str`, *optional*):
126
- Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
127
- guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
128
- information.
107
+ network_alphas (`Dict[str, float]`):
108
+ The value of the network alpha used for stable learning and preventing underflow. This value has the
109
+ same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
110
+ link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
111
+ adapter_name (`str`, *optional*, defaults to None):
112
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
113
+ `default_{i}` where i is the total number of adapters being loaded.
114
+ weight_name (`str`, *optional*, defaults to None):
115
+ Name of the serialized state dict file.
116
+ low_cpu_mem_usage (`bool`, *optional*):
117
+ Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
118
+ weights.
129
119
 
130
120
  Example:
131
121
 
@@ -141,12 +131,8 @@ class UNet2DConditionLoadersMixin:
141
131
  )
142
132
  ```
143
133
  """
144
- from ..models.attention_processor import CustomDiffusionAttnProcessor
145
- from ..models.lora import LoRACompatibleConv, LoRACompatibleLinear, LoRAConv2dLayer, LoRALinearLayer
146
-
147
134
  cache_dir = kwargs.pop("cache_dir", None)
148
135
  force_download = kwargs.pop("force_download", False)
149
- resume_download = kwargs.pop("resume_download", False)
150
136
  proxies = kwargs.pop("proxies", None)
151
137
  local_files_only = kwargs.pop("local_files_only", None)
152
138
  token = kwargs.pop("token", None)
@@ -154,17 +140,17 @@ class UNet2DConditionLoadersMixin:
154
140
  subfolder = kwargs.pop("subfolder", None)
155
141
  weight_name = kwargs.pop("weight_name", None)
156
142
  use_safetensors = kwargs.pop("use_safetensors", None)
157
- low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
158
- # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
159
- # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
160
- network_alphas = kwargs.pop("network_alphas", None)
161
-
143
+ adapter_name = kwargs.pop("adapter_name", None)
162
144
  _pipeline = kwargs.pop("_pipeline", None)
163
-
164
- is_network_alphas_none = network_alphas is None
165
-
145
+ network_alphas = kwargs.pop("network_alphas", None)
146
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", False)
166
147
  allow_pickle = False
167
148
 
149
+ if low_cpu_mem_usage and is_peft_version("<=", "0.13.0"):
150
+ raise ValueError(
151
+ "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`."
152
+ )
153
+
168
154
  if use_safetensors is None:
169
155
  use_safetensors = True
170
156
  allow_pickle = True
@@ -186,7 +172,6 @@ class UNet2DConditionLoadersMixin:
186
172
  weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
187
173
  cache_dir=cache_dir,
188
174
  force_download=force_download,
189
- resume_download=resume_download,
190
175
  proxies=proxies,
191
176
  local_files_only=local_files_only,
192
177
  token=token,
@@ -206,7 +191,6 @@ class UNet2DConditionLoadersMixin:
206
191
  weights_name=weight_name or LORA_WEIGHT_NAME,
207
192
  cache_dir=cache_dir,
208
193
  force_download=force_download,
209
- resume_download=resume_download,
210
194
  proxies=proxies,
211
195
  local_files_only=local_files_only,
212
196
  token=token,
@@ -214,198 +198,206 @@ class UNet2DConditionLoadersMixin:
214
198
  subfolder=subfolder,
215
199
  user_agent=user_agent,
216
200
  )
217
- state_dict = torch.load(model_file, map_location="cpu")
201
+ state_dict = load_state_dict(model_file)
218
202
  else:
219
203
  state_dict = pretrained_model_name_or_path_or_dict
220
204
 
221
- # fill attn processors
222
- lora_layers_list = []
223
-
224
- is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys()) and not USE_PEFT_BACKEND
225
205
  is_custom_diffusion = any("custom_diffusion" in k for k in state_dict.keys())
206
+ is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys())
207
+ is_model_cpu_offload = False
208
+ is_sequential_cpu_offload = False
226
209
 
227
210
  if is_lora:
228
- # correct keys
229
- state_dict, network_alphas = self.convert_state_dict_legacy_attn_format(state_dict, network_alphas)
211
+ deprecation_message = "Using the `load_attn_procs()` method has been deprecated and will be removed in a future version. Please use `load_lora_adapter()`."
212
+ deprecate("load_attn_procs", "0.40.0", deprecation_message)
230
213
 
231
- if network_alphas is not None:
232
- network_alphas_keys = list(network_alphas.keys())
233
- used_network_alphas_keys = set()
234
-
235
- lora_grouped_dict = defaultdict(dict)
236
- mapped_network_alphas = {}
237
-
238
- all_keys = list(state_dict.keys())
239
- for key in all_keys:
240
- value = state_dict.pop(key)
241
- attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
242
- lora_grouped_dict[attn_processor_key][sub_key] = value
243
-
244
- # Create another `mapped_network_alphas` dictionary so that we can properly map them.
245
- if network_alphas is not None:
246
- for k in network_alphas_keys:
247
- if k.replace(".alpha", "") in key:
248
- mapped_network_alphas.update({attn_processor_key: network_alphas.get(k)})
249
- used_network_alphas_keys.add(k)
250
-
251
- if not is_network_alphas_none:
252
- if len(set(network_alphas_keys) - used_network_alphas_keys) > 0:
253
- raise ValueError(
254
- f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
255
- )
214
+ if is_custom_diffusion:
215
+ attn_processors = self._process_custom_diffusion(state_dict=state_dict)
216
+ elif is_lora:
217
+ is_model_cpu_offload, is_sequential_cpu_offload = self._process_lora(
218
+ state_dict=state_dict,
219
+ unet_identifier_key=self.unet_name,
220
+ network_alphas=network_alphas,
221
+ adapter_name=adapter_name,
222
+ _pipeline=_pipeline,
223
+ low_cpu_mem_usage=low_cpu_mem_usage,
224
+ )
225
+ else:
226
+ raise ValueError(
227
+ f"{model_file} does not seem to be in the correct format expected by Custom Diffusion training."
228
+ )
256
229
 
257
- if len(state_dict) > 0:
258
- raise ValueError(
259
- f"The `state_dict` has to be empty at this point but has the following keys \n\n {', '.join(state_dict.keys())}"
260
- )
230
+ # <Unsafe code
231
+ # We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
232
+ # Now we remove any existing hooks to `_pipeline`.
261
233
 
262
- for key, value_dict in lora_grouped_dict.items():
263
- attn_processor = self
264
- for sub_key in key.split("."):
265
- attn_processor = getattr(attn_processor, sub_key)
266
-
267
- # Process non-attention layers, which don't have to_{k,v,q,out_proj}_lora layers
268
- # or add_{k,v,q,out_proj}_proj_lora layers.
269
- rank = value_dict["lora.down.weight"].shape[0]
270
-
271
- if isinstance(attn_processor, LoRACompatibleConv):
272
- in_features = attn_processor.in_channels
273
- out_features = attn_processor.out_channels
274
- kernel_size = attn_processor.kernel_size
275
-
276
- ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
277
- with ctx():
278
- lora = LoRAConv2dLayer(
279
- in_features=in_features,
280
- out_features=out_features,
281
- rank=rank,
282
- kernel_size=kernel_size,
283
- stride=attn_processor.stride,
284
- padding=attn_processor.padding,
285
- network_alpha=mapped_network_alphas.get(key),
286
- )
287
- elif isinstance(attn_processor, LoRACompatibleLinear):
288
- ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
289
- with ctx():
290
- lora = LoRALinearLayer(
291
- attn_processor.in_features,
292
- attn_processor.out_features,
293
- rank,
294
- mapped_network_alphas.get(key),
295
- )
296
- else:
297
- raise ValueError(f"Module {key} is not a LoRACompatibleConv or LoRACompatibleLinear module.")
234
+ # For LoRA, the UNet is already offloaded at this stage as it is handled inside `_process_lora`.
235
+ if is_custom_diffusion and _pipeline is not None:
236
+ is_model_cpu_offload, is_sequential_cpu_offload = self._optionally_disable_offloading(_pipeline=_pipeline)
298
237
 
299
- value_dict = {k.replace("lora.", ""): v for k, v in value_dict.items()}
300
- lora_layers_list.append((attn_processor, lora))
238
+ # only custom diffusion needs to set attn processors
239
+ self.set_attn_processor(attn_processors)
240
+ self.to(dtype=self.dtype, device=self.device)
301
241
 
302
- if low_cpu_mem_usage:
303
- device = next(iter(value_dict.values())).device
304
- dtype = next(iter(value_dict.values())).dtype
305
- load_model_dict_into_meta(lora, value_dict, device=device, dtype=dtype)
306
- else:
307
- lora.load_state_dict(value_dict)
242
+ # Offload back.
243
+ if is_model_cpu_offload:
244
+ _pipeline.enable_model_cpu_offload()
245
+ elif is_sequential_cpu_offload:
246
+ _pipeline.enable_sequential_cpu_offload()
247
+ # Unsafe code />
308
248
 
309
- elif is_custom_diffusion:
310
- attn_processors = {}
311
- custom_diffusion_grouped_dict = defaultdict(dict)
312
- for key, value in state_dict.items():
313
- if len(value) == 0:
314
- custom_diffusion_grouped_dict[key] = {}
315
- else:
316
- if "to_out" in key:
317
- attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
318
- else:
319
- attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
320
- custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
249
+ def _process_custom_diffusion(self, state_dict):
250
+ from ..models.attention_processor import CustomDiffusionAttnProcessor
321
251
 
322
- for key, value_dict in custom_diffusion_grouped_dict.items():
323
- if len(value_dict) == 0:
324
- attn_processors[key] = CustomDiffusionAttnProcessor(
325
- train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
326
- )
252
+ attn_processors = {}
253
+ custom_diffusion_grouped_dict = defaultdict(dict)
254
+ for key, value in state_dict.items():
255
+ if len(value) == 0:
256
+ custom_diffusion_grouped_dict[key] = {}
257
+ else:
258
+ if "to_out" in key:
259
+ attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
327
260
  else:
328
- cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
329
- hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
330
- train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
331
- attn_processors[key] = CustomDiffusionAttnProcessor(
332
- train_kv=True,
333
- train_q_out=train_q_out,
334
- hidden_size=hidden_size,
335
- cross_attention_dim=cross_attention_dim,
336
- )
337
- attn_processors[key].load_state_dict(value_dict)
338
- elif USE_PEFT_BACKEND:
339
- # In that case we have nothing to do as loading the adapter weights is already handled above by `set_peft_model_state_dict`
340
- # on the Unet
341
- pass
342
- else:
343
- raise ValueError(
344
- f"{model_file} does not seem to be in the correct format expected by LoRA or Custom Diffusion training."
345
- )
261
+ attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
262
+ custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
346
263
 
347
- # <Unsafe code
348
- # We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
349
- # Now we remove any existing hooks to
350
- is_model_cpu_offload = False
351
- is_sequential_cpu_offload = False
264
+ for key, value_dict in custom_diffusion_grouped_dict.items():
265
+ if len(value_dict) == 0:
266
+ attn_processors[key] = CustomDiffusionAttnProcessor(
267
+ train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
268
+ )
269
+ else:
270
+ cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
271
+ hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
272
+ train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
273
+ attn_processors[key] = CustomDiffusionAttnProcessor(
274
+ train_kv=True,
275
+ train_q_out=train_q_out,
276
+ hidden_size=hidden_size,
277
+ cross_attention_dim=cross_attention_dim,
278
+ )
279
+ attn_processors[key].load_state_dict(value_dict)
352
280
 
353
- # For PEFT backend the Unet is already offloaded at this stage as it is handled inside `load_lora_weights_into_unet`
354
- if not USE_PEFT_BACKEND:
355
- if _pipeline is not None:
356
- for _, component in _pipeline.components.items():
357
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
358
- is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
359
- is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
360
-
361
- logger.info(
362
- "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
363
- )
364
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
281
+ return attn_processors
365
282
 
366
- # only custom diffusion needs to set attn processors
367
- if is_custom_diffusion:
368
- self.set_attn_processor(attn_processors)
283
+ def _process_lora(
284
+ self, state_dict, unet_identifier_key, network_alphas, adapter_name, _pipeline, low_cpu_mem_usage
285
+ ):
286
+ # This method does the following things:
287
+ # 1. Filters the `state_dict` with keys matching `unet_identifier_key` when using the non-legacy
288
+ # format. For legacy format no filtering is applied.
289
+ # 2. Converts the `state_dict` to the `peft` compatible format.
290
+ # 3. Creates a `LoraConfig` and then injects the converted `state_dict` into the UNet per the
291
+ # `LoraConfig` specs.
292
+ # 4. It also reports if the underlying `_pipeline` has any kind of offloading inside of it.
293
+ if not USE_PEFT_BACKEND:
294
+ raise ValueError("PEFT backend is required for this method.")
369
295
 
370
- # set lora layers
371
- for target_module, lora_layer in lora_layers_list:
372
- target_module.set_lora_layer(lora_layer)
296
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
373
297
 
374
- self.to(dtype=self.dtype, device=self.device)
298
+ keys = list(state_dict.keys())
375
299
 
376
- # Offload back.
377
- if is_model_cpu_offload:
378
- _pipeline.enable_model_cpu_offload()
379
- elif is_sequential_cpu_offload:
380
- _pipeline.enable_sequential_cpu_offload()
381
- # Unsafe code />
300
+ unet_keys = [k for k in keys if k.startswith(unet_identifier_key)]
301
+ unet_state_dict = {
302
+ k.replace(f"{unet_identifier_key}.", ""): v for k, v in state_dict.items() if k in unet_keys
303
+ }
382
304
 
383
- def convert_state_dict_legacy_attn_format(self, state_dict, network_alphas):
384
- is_new_lora_format = all(
385
- key.startswith(self.unet_name) or key.startswith(self.text_encoder_name) for key in state_dict.keys()
386
- )
387
- if is_new_lora_format:
388
- # Strip the `"unet"` prefix.
389
- is_text_encoder_present = any(key.startswith(self.text_encoder_name) for key in state_dict.keys())
390
- if is_text_encoder_present:
391
- warn_message = "The state_dict contains LoRA params corresponding to the text encoder which are not being used here. To use both UNet and text encoder related LoRA params, use [`pipe.load_lora_weights()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.load_lora_weights)."
392
- logger.warning(warn_message)
393
- unet_keys = [k for k in state_dict.keys() if k.startswith(self.unet_name)]
394
- state_dict = {k.replace(f"{self.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
305
+ if network_alphas is not None:
306
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(unet_identifier_key)]
307
+ network_alphas = {
308
+ k.replace(f"{unet_identifier_key}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
309
+ }
395
310
 
396
- # change processor format to 'pure' LoRACompatibleLinear format
397
- if any("processor" in k.split(".") for k in state_dict.keys()):
311
+ is_model_cpu_offload = False
312
+ is_sequential_cpu_offload = False
313
+ state_dict_to_be_used = unet_state_dict if len(unet_state_dict) > 0 else state_dict
398
314
 
399
- def format_to_lora_compatible(key):
400
- if "processor" not in key.split("."):
401
- return key
402
- return key.replace(".processor", "").replace("to_out_lora", "to_out.0.lora").replace("_lora", ".lora")
315
+ if len(state_dict_to_be_used) > 0:
316
+ if adapter_name in getattr(self, "peft_config", {}):
317
+ raise ValueError(
318
+ f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
319
+ )
403
320
 
404
- state_dict = {format_to_lora_compatible(k): v for k, v in state_dict.items()}
321
+ state_dict = convert_unet_state_dict_to_peft(state_dict_to_be_used)
405
322
 
406
323
  if network_alphas is not None:
407
- network_alphas = {format_to_lora_compatible(k): v for k, v in network_alphas.items()}
408
- return state_dict, network_alphas
324
+ # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
325
+ # `convert_unet_state_dict_to_peft` method.
326
+ network_alphas = convert_unet_state_dict_to_peft(network_alphas)
327
+
328
+ rank = {}
329
+ for key, val in state_dict.items():
330
+ if "lora_B" in key:
331
+ rank[key] = val.shape[1]
332
+
333
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
334
+ if "use_dora" in lora_config_kwargs:
335
+ if lora_config_kwargs["use_dora"]:
336
+ if is_peft_version("<", "0.9.0"):
337
+ raise ValueError(
338
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
339
+ )
340
+ else:
341
+ if is_peft_version("<", "0.9.0"):
342
+ lora_config_kwargs.pop("use_dora")
343
+ lora_config = LoraConfig(**lora_config_kwargs)
344
+
345
+ # adapter_name
346
+ if adapter_name is None:
347
+ adapter_name = get_adapter_name(self)
348
+
349
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
350
+ # otherwise loading LoRA weights will lead to an error
351
+ is_model_cpu_offload, is_sequential_cpu_offload = self._optionally_disable_offloading(_pipeline)
352
+ peft_kwargs = {}
353
+ if is_peft_version(">=", "0.13.1"):
354
+ peft_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
355
+
356
+ inject_adapter_in_model(lora_config, self, adapter_name=adapter_name, **peft_kwargs)
357
+ incompatible_keys = set_peft_model_state_dict(self, state_dict, adapter_name, **peft_kwargs)
358
+
359
+ warn_msg = ""
360
+ if incompatible_keys is not None:
361
+ # Check only for unexpected keys.
362
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
363
+ if unexpected_keys:
364
+ lora_unexpected_keys = [k for k in unexpected_keys if "lora_" in k and adapter_name in k]
365
+ if lora_unexpected_keys:
366
+ warn_msg = (
367
+ f"Loading adapter weights from state_dict led to unexpected keys found in the model:"
368
+ f" {', '.join(lora_unexpected_keys)}. "
369
+ )
370
+
371
+ # Filter missing keys specific to the current adapter.
372
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
373
+ if missing_keys:
374
+ lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
375
+ if lora_missing_keys:
376
+ warn_msg += (
377
+ f"Loading adapter weights from state_dict led to missing keys in the model:"
378
+ f" {', '.join(lora_missing_keys)}."
379
+ )
380
+
381
+ if warn_msg:
382
+ logger.warning(warn_msg)
383
+
384
+ return is_model_cpu_offload, is_sequential_cpu_offload
385
+
386
+ @classmethod
387
+ # Copied from diffusers.loaders.lora_base.LoraBaseMixin._optionally_disable_offloading
388
+ def _optionally_disable_offloading(cls, _pipeline):
389
+ """
390
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
391
+
392
+ Args:
393
+ _pipeline (`DiffusionPipeline`):
394
+ The pipeline to disable offloading for.
395
+
396
+ Returns:
397
+ tuple:
398
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
399
+ """
400
+ return _func_optionally_disable_offloading(_pipeline=_pipeline)
409
401
 
410
402
  def save_attn_procs(
411
403
  self,
@@ -458,17 +450,6 @@ class UNet2DConditionLoadersMixin:
458
450
  logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
459
451
  return
460
452
 
461
- if save_function is None:
462
- if safe_serialization:
463
-
464
- def save_function(weights, filename):
465
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
466
-
467
- else:
468
- save_function = torch.save
469
-
470
- os.makedirs(save_directory, exist_ok=True)
471
-
472
453
  is_custom_diffusion = any(
473
454
  isinstance(
474
455
  x,
@@ -477,27 +458,37 @@ class UNet2DConditionLoadersMixin:
477
458
  for (_, x) in self.attn_processors.items()
478
459
  )
479
460
  if is_custom_diffusion:
480
- model_to_save = AttnProcsLayers(
481
- {
482
- y: x
483
- for (y, x) in self.attn_processors.items()
484
- if isinstance(
485
- x,
486
- (
487
- CustomDiffusionAttnProcessor,
488
- CustomDiffusionAttnProcessor2_0,
489
- CustomDiffusionXFormersAttnProcessor,
490
- ),
461
+ state_dict = self._get_custom_diffusion_state_dict()
462
+ if save_function is None and safe_serialization:
463
+ # safetensors does not support saving dicts with non-tensor values
464
+ empty_state_dict = {k: v for k, v in state_dict.items() if not isinstance(v, torch.Tensor)}
465
+ if len(empty_state_dict) > 0:
466
+ logger.warning(
467
+ f"Safetensors does not support saving dicts with non-tensor values. "
468
+ f"The following keys will be ignored: {empty_state_dict.keys()}"
491
469
  )
492
- }
493
- )
494
- state_dict = model_to_save.state_dict()
495
- for name, attn in self.attn_processors.items():
496
- if len(attn.state_dict()) == 0:
497
- state_dict[name] = {}
470
+ state_dict = {k: v for k, v in state_dict.items() if isinstance(v, torch.Tensor)}
498
471
  else:
499
- model_to_save = AttnProcsLayers(self.attn_processors)
500
- state_dict = model_to_save.state_dict()
472
+ deprecation_message = "Using the `save_attn_procs()` method has been deprecated and will be removed in a future version. Please use `save_lora_adapter()`."
473
+ deprecate("save_attn_procs", "0.40.0", deprecation_message)
474
+
475
+ if not USE_PEFT_BACKEND:
476
+ raise ValueError("PEFT backend is required for saving LoRAs using the `save_attn_procs()` method.")
477
+
478
+ from peft.utils import get_peft_model_state_dict
479
+
480
+ state_dict = get_peft_model_state_dict(self)
481
+
482
+ if save_function is None:
483
+ if safe_serialization:
484
+
485
+ def save_function(weights, filename):
486
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
487
+
488
+ else:
489
+ save_function = torch.save
490
+
491
+ os.makedirs(save_directory, exist_ok=True)
501
492
 
502
493
  if weight_name is None:
503
494
  if safe_serialization:
@@ -510,186 +501,33 @@ class UNet2DConditionLoadersMixin:
510
501
  save_function(state_dict, save_path)
511
502
  logger.info(f"Model weights saved in {save_path}")
512
503
 
513
- def fuse_lora(self, lora_scale=1.0, safe_fusing=False, adapter_names=None):
514
- self.lora_scale = lora_scale
515
- self._safe_fusing = safe_fusing
516
- self.apply(partial(self._fuse_lora_apply, adapter_names=adapter_names))
517
-
518
- def _fuse_lora_apply(self, module, adapter_names=None):
519
- if not USE_PEFT_BACKEND:
520
- if hasattr(module, "_fuse_lora"):
521
- module._fuse_lora(self.lora_scale, self._safe_fusing)
522
-
523
- if adapter_names is not None:
524
- raise ValueError(
525
- "The `adapter_names` argument is not supported in your environment. Please switch"
526
- " to PEFT backend to use this argument by installing latest PEFT and transformers."
527
- " `pip install -U peft transformers`"
528
- )
529
- else:
530
- from peft.tuners.tuners_utils import BaseTunerLayer
531
-
532
- merge_kwargs = {"safe_merge": self._safe_fusing}
533
-
534
- if isinstance(module, BaseTunerLayer):
535
- if self.lora_scale != 1.0:
536
- module.scale_layer(self.lora_scale)
537
-
538
- # For BC with prevous PEFT versions, we need to check the signature
539
- # of the `merge` method to see if it supports the `adapter_names` argument.
540
- supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
541
- if "adapter_names" in supported_merge_kwargs:
542
- merge_kwargs["adapter_names"] = adapter_names
543
- elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
544
- raise ValueError(
545
- "The `adapter_names` argument is not supported with your PEFT version. Please upgrade"
546
- " to the latest version of PEFT. `pip install -U peft`"
547
- )
548
-
549
- module.merge(**merge_kwargs)
550
-
551
- def unfuse_lora(self):
552
- self.apply(self._unfuse_lora_apply)
553
-
554
- def _unfuse_lora_apply(self, module):
555
- if not USE_PEFT_BACKEND:
556
- if hasattr(module, "_unfuse_lora"):
557
- module._unfuse_lora()
558
- else:
559
- from peft.tuners.tuners_utils import BaseTunerLayer
560
-
561
- if isinstance(module, BaseTunerLayer):
562
- module.unmerge()
563
-
564
- def set_adapters(
565
- self,
566
- adapter_names: Union[List[str], str],
567
- weights: Optional[Union[List[float], float]] = None,
568
- ):
569
- """
570
- Set the currently active adapters for use in the UNet.
571
-
572
- Args:
573
- adapter_names (`List[str]` or `str`):
574
- The names of the adapters to use.
575
- adapter_weights (`Union[List[float], float]`, *optional*):
576
- The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
577
- adapters.
578
-
579
- Example:
580
-
581
- ```py
582
- from diffusers import AutoPipelineForText2Image
583
- import torch
584
-
585
- pipeline = AutoPipelineForText2Image.from_pretrained(
586
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
587
- ).to("cuda")
588
- pipeline.load_lora_weights(
589
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
590
- )
591
- pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
592
- pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
593
- ```
594
- """
595
- if not USE_PEFT_BACKEND:
596
- raise ValueError("PEFT backend is required for `set_adapters()`.")
597
-
598
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
599
-
600
- if weights is None:
601
- weights = [1.0] * len(adapter_names)
602
- elif isinstance(weights, float):
603
- weights = [weights] * len(adapter_names)
604
-
605
- if len(adapter_names) != len(weights):
606
- raise ValueError(
607
- f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
608
- )
609
-
610
- set_weights_and_activate_adapters(self, adapter_names, weights)
611
-
612
- def disable_lora(self):
613
- """
614
- Disable the UNet's active LoRA layers.
615
-
616
- Example:
617
-
618
- ```py
619
- from diffusers import AutoPipelineForText2Image
620
- import torch
621
-
622
- pipeline = AutoPipelineForText2Image.from_pretrained(
623
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
624
- ).to("cuda")
625
- pipeline.load_lora_weights(
626
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
627
- )
628
- pipeline.disable_lora()
629
- ```
630
- """
631
- if not USE_PEFT_BACKEND:
632
- raise ValueError("PEFT backend is required for this method.")
633
- set_adapter_layers(self, enabled=False)
634
-
635
- def enable_lora(self):
636
- """
637
- Enable the UNet's active LoRA layers.
638
-
639
- Example:
640
-
641
- ```py
642
- from diffusers import AutoPipelineForText2Image
643
- import torch
644
-
645
- pipeline = AutoPipelineForText2Image.from_pretrained(
646
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
647
- ).to("cuda")
648
- pipeline.load_lora_weights(
649
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
504
+ def _get_custom_diffusion_state_dict(self):
505
+ from ..models.attention_processor import (
506
+ CustomDiffusionAttnProcessor,
507
+ CustomDiffusionAttnProcessor2_0,
508
+ CustomDiffusionXFormersAttnProcessor,
650
509
  )
651
- pipeline.enable_lora()
652
- ```
653
- """
654
- if not USE_PEFT_BACKEND:
655
- raise ValueError("PEFT backend is required for this method.")
656
- set_adapter_layers(self, enabled=True)
657
-
658
- def delete_adapters(self, adapter_names: Union[List[str], str]):
659
- """
660
- Delete an adapter's LoRA layers from the UNet.
661
-
662
- Args:
663
- adapter_names (`Union[List[str], str]`):
664
- The names (single string or list of strings) of the adapter to delete.
665
-
666
- Example:
667
510
 
668
- ```py
669
- from diffusers import AutoPipelineForText2Image
670
- import torch
671
-
672
- pipeline = AutoPipelineForText2Image.from_pretrained(
673
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
674
- ).to("cuda")
675
- pipeline.load_lora_weights(
676
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
511
+ model_to_save = AttnProcsLayers(
512
+ {
513
+ y: x
514
+ for (y, x) in self.attn_processors.items()
515
+ if isinstance(
516
+ x,
517
+ (
518
+ CustomDiffusionAttnProcessor,
519
+ CustomDiffusionAttnProcessor2_0,
520
+ CustomDiffusionXFormersAttnProcessor,
521
+ ),
522
+ )
523
+ }
677
524
  )
678
- pipeline.delete_adapters("cinematic")
679
- ```
680
- """
681
- if not USE_PEFT_BACKEND:
682
- raise ValueError("PEFT backend is required for this method.")
683
-
684
- if isinstance(adapter_names, str):
685
- adapter_names = [adapter_names]
525
+ state_dict = model_to_save.state_dict()
526
+ for name, attn in self.attn_processors.items():
527
+ if len(attn.state_dict()) == 0:
528
+ state_dict[name] = {}
686
529
 
687
- for adapter_name in adapter_names:
688
- delete_adapter_layers(self, adapter_name)
689
-
690
- # Pop also the corresponding adapter from the config
691
- if hasattr(self, "peft_config"):
692
- self.peft_config.pop(adapter_name, None)
530
+ return state_dict
693
531
 
694
532
  def _convert_ip_adapter_image_proj_to_diffusers(self, state_dict, low_cpu_mem_usage=False):
695
533
  if low_cpu_mem_usage:
@@ -748,13 +586,102 @@ class UNet2DConditionLoadersMixin:
748
586
  diffusers_name = diffusers_name.replace("proj.3", "norm")
749
587
  updated_state_dict[diffusers_name] = value
750
588
 
589
+ elif "perceiver_resampler.proj_in.weight" in state_dict:
590
+ # IP-Adapter Face ID Plus
591
+ id_embeddings_dim = state_dict["proj.0.weight"].shape[1]
592
+ embed_dims = state_dict["perceiver_resampler.proj_in.weight"].shape[0]
593
+ hidden_dims = state_dict["perceiver_resampler.proj_in.weight"].shape[1]
594
+ output_dims = state_dict["perceiver_resampler.proj_out.weight"].shape[0]
595
+ heads = state_dict["perceiver_resampler.layers.0.0.to_q.weight"].shape[0] // 64
596
+
597
+ with init_context():
598
+ image_projection = IPAdapterFaceIDPlusImageProjection(
599
+ embed_dims=embed_dims,
600
+ output_dims=output_dims,
601
+ hidden_dims=hidden_dims,
602
+ heads=heads,
603
+ id_embeddings_dim=id_embeddings_dim,
604
+ )
605
+
606
+ for key, value in state_dict.items():
607
+ diffusers_name = key.replace("perceiver_resampler.", "")
608
+ diffusers_name = diffusers_name.replace("0.to", "attn.to")
609
+ diffusers_name = diffusers_name.replace("0.1.0.", "0.ff.0.")
610
+ diffusers_name = diffusers_name.replace("0.1.1.weight", "0.ff.1.net.0.proj.weight")
611
+ diffusers_name = diffusers_name.replace("0.1.3.weight", "0.ff.1.net.2.weight")
612
+ diffusers_name = diffusers_name.replace("1.1.0.", "1.ff.0.")
613
+ diffusers_name = diffusers_name.replace("1.1.1.weight", "1.ff.1.net.0.proj.weight")
614
+ diffusers_name = diffusers_name.replace("1.1.3.weight", "1.ff.1.net.2.weight")
615
+ diffusers_name = diffusers_name.replace("2.1.0.", "2.ff.0.")
616
+ diffusers_name = diffusers_name.replace("2.1.1.weight", "2.ff.1.net.0.proj.weight")
617
+ diffusers_name = diffusers_name.replace("2.1.3.weight", "2.ff.1.net.2.weight")
618
+ diffusers_name = diffusers_name.replace("3.1.0.", "3.ff.0.")
619
+ diffusers_name = diffusers_name.replace("3.1.1.weight", "3.ff.1.net.0.proj.weight")
620
+ diffusers_name = diffusers_name.replace("3.1.3.weight", "3.ff.1.net.2.weight")
621
+ diffusers_name = diffusers_name.replace("layers.0.0", "layers.0.ln0")
622
+ diffusers_name = diffusers_name.replace("layers.0.1", "layers.0.ln1")
623
+ diffusers_name = diffusers_name.replace("layers.1.0", "layers.1.ln0")
624
+ diffusers_name = diffusers_name.replace("layers.1.1", "layers.1.ln1")
625
+ diffusers_name = diffusers_name.replace("layers.2.0", "layers.2.ln0")
626
+ diffusers_name = diffusers_name.replace("layers.2.1", "layers.2.ln1")
627
+ diffusers_name = diffusers_name.replace("layers.3.0", "layers.3.ln0")
628
+ diffusers_name = diffusers_name.replace("layers.3.1", "layers.3.ln1")
629
+
630
+ if "norm1" in diffusers_name:
631
+ updated_state_dict[diffusers_name.replace("0.norm1", "0")] = value
632
+ elif "norm2" in diffusers_name:
633
+ updated_state_dict[diffusers_name.replace("0.norm2", "1")] = value
634
+ elif "to_kv" in diffusers_name:
635
+ v_chunk = value.chunk(2, dim=0)
636
+ updated_state_dict[diffusers_name.replace("to_kv", "to_k")] = v_chunk[0]
637
+ updated_state_dict[diffusers_name.replace("to_kv", "to_v")] = v_chunk[1]
638
+ elif "to_out" in diffusers_name:
639
+ updated_state_dict[diffusers_name.replace("to_out", "to_out.0")] = value
640
+ elif "proj.0.weight" == diffusers_name:
641
+ updated_state_dict["proj.net.0.proj.weight"] = value
642
+ elif "proj.0.bias" == diffusers_name:
643
+ updated_state_dict["proj.net.0.proj.bias"] = value
644
+ elif "proj.2.weight" == diffusers_name:
645
+ updated_state_dict["proj.net.2.weight"] = value
646
+ elif "proj.2.bias" == diffusers_name:
647
+ updated_state_dict["proj.net.2.bias"] = value
648
+ else:
649
+ updated_state_dict[diffusers_name] = value
650
+
651
+ elif "norm.weight" in state_dict:
652
+ # IP-Adapter Face ID
653
+ id_embeddings_dim_in = state_dict["proj.0.weight"].shape[1]
654
+ id_embeddings_dim_out = state_dict["proj.0.weight"].shape[0]
655
+ multiplier = id_embeddings_dim_out // id_embeddings_dim_in
656
+ norm_layer = "norm.weight"
657
+ cross_attention_dim = state_dict[norm_layer].shape[0]
658
+ num_tokens = state_dict["proj.2.weight"].shape[0] // cross_attention_dim
659
+
660
+ with init_context():
661
+ image_projection = IPAdapterFaceIDImageProjection(
662
+ cross_attention_dim=cross_attention_dim,
663
+ image_embed_dim=id_embeddings_dim_in,
664
+ mult=multiplier,
665
+ num_tokens=num_tokens,
666
+ )
667
+
668
+ for key, value in state_dict.items():
669
+ diffusers_name = key.replace("proj.0", "ff.net.0.proj")
670
+ diffusers_name = diffusers_name.replace("proj.2", "ff.net.2")
671
+ updated_state_dict[diffusers_name] = value
672
+
751
673
  else:
752
674
  # IP-Adapter Plus
753
675
  num_image_text_embeds = state_dict["latents"].shape[1]
754
676
  embed_dims = state_dict["proj_in.weight"].shape[1]
755
677
  output_dims = state_dict["proj_out.weight"].shape[0]
756
678
  hidden_dims = state_dict["latents"].shape[2]
757
- heads = state_dict["layers.0.0.to_q.weight"].shape[0] // 64
679
+ attn_key_present = any("attn" in k for k in state_dict)
680
+ heads = (
681
+ state_dict["layers.0.attn.to_q.weight"].shape[0] // 64
682
+ if attn_key_present
683
+ else state_dict["layers.0.0.to_q.weight"].shape[0] // 64
684
+ )
758
685
 
759
686
  with init_context():
760
687
  image_projection = IPAdapterPlusImageProjection(
@@ -767,26 +694,53 @@ class UNet2DConditionLoadersMixin:
767
694
 
768
695
  for key, value in state_dict.items():
769
696
  diffusers_name = key.replace("0.to", "2.to")
770
- diffusers_name = diffusers_name.replace("1.0.weight", "3.0.weight")
771
- diffusers_name = diffusers_name.replace("1.0.bias", "3.0.bias")
772
- diffusers_name = diffusers_name.replace("1.1.weight", "3.1.net.0.proj.weight")
773
- diffusers_name = diffusers_name.replace("1.3.weight", "3.1.net.2.weight")
774
697
 
775
- if "norm1" in diffusers_name:
776
- updated_state_dict[diffusers_name.replace("0.norm1", "0")] = value
777
- elif "norm2" in diffusers_name:
778
- updated_state_dict[diffusers_name.replace("0.norm2", "1")] = value
779
- elif "to_kv" in diffusers_name:
698
+ diffusers_name = diffusers_name.replace("0.0.norm1", "0.ln0")
699
+ diffusers_name = diffusers_name.replace("0.0.norm2", "0.ln1")
700
+ diffusers_name = diffusers_name.replace("1.0.norm1", "1.ln0")
701
+ diffusers_name = diffusers_name.replace("1.0.norm2", "1.ln1")
702
+ diffusers_name = diffusers_name.replace("2.0.norm1", "2.ln0")
703
+ diffusers_name = diffusers_name.replace("2.0.norm2", "2.ln1")
704
+ diffusers_name = diffusers_name.replace("3.0.norm1", "3.ln0")
705
+ diffusers_name = diffusers_name.replace("3.0.norm2", "3.ln1")
706
+
707
+ if "to_kv" in diffusers_name:
708
+ parts = diffusers_name.split(".")
709
+ parts[2] = "attn"
710
+ diffusers_name = ".".join(parts)
780
711
  v_chunk = value.chunk(2, dim=0)
781
712
  updated_state_dict[diffusers_name.replace("to_kv", "to_k")] = v_chunk[0]
782
713
  updated_state_dict[diffusers_name.replace("to_kv", "to_v")] = v_chunk[1]
714
+ elif "to_q" in diffusers_name:
715
+ parts = diffusers_name.split(".")
716
+ parts[2] = "attn"
717
+ diffusers_name = ".".join(parts)
718
+ updated_state_dict[diffusers_name] = value
783
719
  elif "to_out" in diffusers_name:
720
+ parts = diffusers_name.split(".")
721
+ parts[2] = "attn"
722
+ diffusers_name = ".".join(parts)
784
723
  updated_state_dict[diffusers_name.replace("to_out", "to_out.0")] = value
785
724
  else:
725
+ diffusers_name = diffusers_name.replace("0.1.0", "0.ff.0")
726
+ diffusers_name = diffusers_name.replace("0.1.1", "0.ff.1.net.0.proj")
727
+ diffusers_name = diffusers_name.replace("0.1.3", "0.ff.1.net.2")
728
+
729
+ diffusers_name = diffusers_name.replace("1.1.0", "1.ff.0")
730
+ diffusers_name = diffusers_name.replace("1.1.1", "1.ff.1.net.0.proj")
731
+ diffusers_name = diffusers_name.replace("1.1.3", "1.ff.1.net.2")
732
+
733
+ diffusers_name = diffusers_name.replace("2.1.0", "2.ff.0")
734
+ diffusers_name = diffusers_name.replace("2.1.1", "2.ff.1.net.0.proj")
735
+ diffusers_name = diffusers_name.replace("2.1.3", "2.ff.1.net.2")
736
+
737
+ diffusers_name = diffusers_name.replace("3.1.0", "3.ff.0")
738
+ diffusers_name = diffusers_name.replace("3.1.1", "3.ff.1.net.0.proj")
739
+ diffusers_name = diffusers_name.replace("3.1.3", "3.ff.1.net.2")
786
740
  updated_state_dict[diffusers_name] = value
787
741
 
788
742
  if not low_cpu_mem_usage:
789
- image_projection.load_state_dict(updated_state_dict)
743
+ image_projection.load_state_dict(updated_state_dict, strict=True)
790
744
  else:
791
745
  load_model_dict_into_meta(image_projection, updated_state_dict, device=self.device, dtype=self.dtype)
792
746
 
@@ -794,10 +748,9 @@ class UNet2DConditionLoadersMixin:
794
748
 
795
749
  def _convert_ip_adapter_attn_to_diffusers(self, state_dicts, low_cpu_mem_usage=False):
796
750
  from ..models.attention_processor import (
797
- AttnProcessor,
798
- AttnProcessor2_0,
799
751
  IPAdapterAttnProcessor,
800
752
  IPAdapterAttnProcessor2_0,
753
+ IPAdapterXFormersAttnProcessor,
801
754
  )
802
755
 
803
756
  if low_cpu_mem_usage:
@@ -835,14 +788,17 @@ class UNet2DConditionLoadersMixin:
835
788
  hidden_size = self.config.block_out_channels[block_id]
836
789
 
837
790
  if cross_attention_dim is None or "motion_modules" in name:
838
- attn_processor_class = (
839
- AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
840
- )
791
+ attn_processor_class = self.attn_processors[name].__class__
841
792
  attn_procs[name] = attn_processor_class()
842
793
  else:
843
- attn_processor_class = (
844
- IPAdapterAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else IPAdapterAttnProcessor
845
- )
794
+ if "XFormers" in str(self.attn_processors[name].__class__):
795
+ attn_processor_class = IPAdapterXFormersAttnProcessor
796
+ else:
797
+ attn_processor_class = (
798
+ IPAdapterAttnProcessor2_0
799
+ if hasattr(F, "scaled_dot_product_attention")
800
+ else IPAdapterAttnProcessor
801
+ )
846
802
  num_image_text_embeds = []
847
803
  for state_dict in state_dicts:
848
804
  if "proj.weight" in state_dict["image_proj"]:
@@ -851,6 +807,12 @@ class UNet2DConditionLoadersMixin:
851
807
  elif "proj.3.weight" in state_dict["image_proj"]:
852
808
  # IP-Adapter Full Face
853
809
  num_image_text_embeds += [257] # 256 CLIP tokens + 1 CLS token
810
+ elif "perceiver_resampler.proj_in.weight" in state_dict["image_proj"]:
811
+ # IP-Adapter Face ID Plus
812
+ num_image_text_embeds += [4]
813
+ elif "norm.weight" in state_dict["image_proj"]:
814
+ # IP-Adapter Face ID
815
+ num_image_text_embeds += [4]
854
816
  else:
855
817
  # IP-Adapter Plus
856
818
  num_image_text_embeds += [state_dict["image_proj"]["latents"].shape[1]]
@@ -882,6 +844,15 @@ class UNet2DConditionLoadersMixin:
882
844
  def _load_ip_adapter_weights(self, state_dicts, low_cpu_mem_usage=False):
883
845
  if not isinstance(state_dicts, list):
884
846
  state_dicts = [state_dicts]
847
+
848
+ # Kolors Unet already has a `encoder_hid_proj`
849
+ if (
850
+ self.encoder_hid_proj is not None
851
+ and self.config.encoder_hid_dim_type == "text_proj"
852
+ and not hasattr(self, "text_encoder_hid_proj")
853
+ ):
854
+ self.text_encoder_hid_proj = self.encoder_hid_proj
855
+
885
856
  # Set encoder_hid_proj after loading ip_adapter weights,
886
857
  # because `IPAdapterPlusImageProjection` also has `attn_processors`.
887
858
  self.encoder_hid_proj = None
@@ -902,102 +873,55 @@ class UNet2DConditionLoadersMixin:
902
873
 
903
874
  self.to(dtype=self.dtype, device=self.device)
904
875
 
905
-
906
- class FromOriginalUNetMixin:
907
- """
908
- Load pretrained UNet model weights saved in the `.ckpt` or `.safetensors` format into a [`StableCascadeUNet`].
909
- """
910
-
911
- @classmethod
912
- @validate_hf_hub_args
913
- def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
914
- r"""
915
- Instantiate a [`StableCascadeUNet`] from pretrained StableCascadeUNet weights saved in the original `.ckpt` or
916
- `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
917
-
918
- Parameters:
919
- pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
920
- Can be either:
921
- - A link to the `.ckpt` file (for example
922
- `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
923
- - A path to a *file* containing all pipeline weights.
924
- config: (`dict`, *optional*):
925
- Dictionary containing the configuration of the model:
926
- torch_dtype (`str` or `torch.dtype`, *optional*):
927
- Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
928
- dtype is automatically derived from the model's weights.
929
- force_download (`bool`, *optional*, defaults to `False`):
930
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
931
- cached versions if they exist.
932
- cache_dir (`Union[str, os.PathLike]`, *optional*):
933
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
934
- is not used.
935
- resume_download (`bool`, *optional*, defaults to `False`):
936
- Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
937
- incompletely downloaded files are deleted.
938
- proxies (`Dict[str, str]`, *optional*):
939
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
940
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
941
- local_files_only (`bool`, *optional*, defaults to `False`):
942
- Whether to only load local model weights and configuration files or not. If set to True, the model
943
- won't be downloaded from the Hub.
944
- token (`str` or *bool*, *optional*):
945
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
946
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
947
- revision (`str`, *optional*, defaults to `"main"`):
948
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
949
- allowed by Git.
950
- kwargs (remaining dictionary of keyword arguments, *optional*):
951
- Can be used to overwrite load and saveable variables of the model.
952
-
953
- """
954
- class_name = cls.__name__
955
- if class_name != "StableCascadeUNet":
956
- raise ValueError("FromOriginalUNetMixin is currently only compatible with StableCascadeUNet")
957
-
958
- config = kwargs.pop("config", None)
959
- resume_download = kwargs.pop("resume_download", False)
960
- force_download = kwargs.pop("force_download", False)
961
- proxies = kwargs.pop("proxies", None)
962
- token = kwargs.pop("token", None)
963
- cache_dir = kwargs.pop("cache_dir", None)
964
- local_files_only = kwargs.pop("local_files_only", None)
965
- revision = kwargs.pop("revision", None)
966
- torch_dtype = kwargs.pop("torch_dtype", None)
967
-
968
- checkpoint = load_single_file_model_checkpoint(
969
- pretrained_model_link_or_path,
970
- resume_download=resume_download,
971
- force_download=force_download,
972
- proxies=proxies,
973
- token=token,
974
- cache_dir=cache_dir,
975
- local_files_only=local_files_only,
976
- revision=revision,
977
- )
978
-
979
- if config is None:
980
- config = infer_stable_cascade_single_file_config(checkpoint)
981
- model_config = cls.load_config(**config, **kwargs)
982
- else:
983
- model_config = config
984
-
985
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
986
- with ctx():
987
- model = cls.from_config(model_config, **kwargs)
988
-
989
- diffusers_format_checkpoint = convert_stable_cascade_unet_single_file_to_diffusers(checkpoint)
990
- if is_accelerate_available():
991
- unexpected_keys = load_model_dict_into_meta(model, diffusers_format_checkpoint, dtype=torch_dtype)
992
- if len(unexpected_keys) > 0:
993
- logger.warn(
994
- f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
995
- )
996
-
997
- else:
998
- model.load_state_dict(diffusers_format_checkpoint)
999
-
1000
- if torch_dtype is not None:
1001
- model.to(torch_dtype)
1002
-
1003
- return model
876
+ def _load_ip_adapter_loras(self, state_dicts):
877
+ lora_dicts = {}
878
+ for key_id, name in enumerate(self.attn_processors.keys()):
879
+ for i, state_dict in enumerate(state_dicts):
880
+ if f"{key_id}.to_k_lora.down.weight" in state_dict["ip_adapter"]:
881
+ if i not in lora_dicts:
882
+ lora_dicts[i] = {}
883
+ lora_dicts[i].update(
884
+ {
885
+ f"unet.{name}.to_k_lora.down.weight": state_dict["ip_adapter"][
886
+ f"{key_id}.to_k_lora.down.weight"
887
+ ]
888
+ }
889
+ )
890
+ lora_dicts[i].update(
891
+ {
892
+ f"unet.{name}.to_q_lora.down.weight": state_dict["ip_adapter"][
893
+ f"{key_id}.to_q_lora.down.weight"
894
+ ]
895
+ }
896
+ )
897
+ lora_dicts[i].update(
898
+ {
899
+ f"unet.{name}.to_v_lora.down.weight": state_dict["ip_adapter"][
900
+ f"{key_id}.to_v_lora.down.weight"
901
+ ]
902
+ }
903
+ )
904
+ lora_dicts[i].update(
905
+ {
906
+ f"unet.{name}.to_out_lora.down.weight": state_dict["ip_adapter"][
907
+ f"{key_id}.to_out_lora.down.weight"
908
+ ]
909
+ }
910
+ )
911
+ lora_dicts[i].update(
912
+ {f"unet.{name}.to_k_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.up.weight"]}
913
+ )
914
+ lora_dicts[i].update(
915
+ {f"unet.{name}.to_q_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.up.weight"]}
916
+ )
917
+ lora_dicts[i].update(
918
+ {f"unet.{name}.to_v_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.up.weight"]}
919
+ )
920
+ lora_dicts[i].update(
921
+ {
922
+ f"unet.{name}.to_out_lora.up.weight": state_dict["ip_adapter"][
923
+ f"{key_id}.to_out_lora.up.weight"
924
+ ]
925
+ }
926
+ )
927
+ return lora_dicts