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
diffusers/loaders/lora.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -13,7 +13,6 @@
13
13
  # limitations under the License.
14
14
  import inspect
15
15
  import os
16
- from contextlib import nullcontext
17
16
  from pathlib import Path
18
17
  from typing import Callable, Dict, List, Optional, Union
19
18
 
@@ -26,7 +25,7 @@ from packaging import version
26
25
  from torch import nn
27
26
 
28
27
  from .. import __version__
29
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
28
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
30
29
  from ..utils import (
31
30
  USE_PEFT_BACKEND,
32
31
  _get_model_file,
@@ -34,7 +33,6 @@ from ..utils import (
34
33
  convert_state_dict_to_peft,
35
34
  convert_unet_state_dict_to_peft,
36
35
  delete_adapter_layers,
37
- deprecate,
38
36
  get_adapter_name,
39
37
  get_peft_kwargs,
40
38
  is_accelerate_available,
@@ -51,10 +49,9 @@ from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_
51
49
  if is_transformers_available():
52
50
  from transformers import PreTrainedModel
53
51
 
54
- from ..models.lora import PatchedLoraProjection, text_encoder_attn_modules, text_encoder_mlp_modules
52
+ from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
55
53
 
56
54
  if is_accelerate_available():
57
- from accelerate import init_empty_weights
58
55
  from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
59
56
 
60
57
  logger = logging.get_logger(__name__)
@@ -106,6 +103,13 @@ class LoraLoaderMixin:
106
103
  Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
107
104
  `default_{i}` where i is the total number of adapters being loaded.
108
105
  """
106
+ if not USE_PEFT_BACKEND:
107
+ raise ValueError("PEFT backend is required for this method.")
108
+
109
+ # if a dict is passed, copy it instead of modifying it inplace
110
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
111
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
112
+
109
113
  # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
110
114
  state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
111
115
 
@@ -397,16 +401,17 @@ class LoraLoaderMixin:
397
401
  Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
398
402
  `default_{i}` where i is the total number of adapters being loaded.
399
403
  """
404
+ if not USE_PEFT_BACKEND:
405
+ raise ValueError("PEFT backend is required for this method.")
406
+
407
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
408
+
400
409
  low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
401
410
  # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
402
411
  # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
403
412
  # their prefixes.
404
413
  keys = list(state_dict.keys())
405
414
 
406
- if all(key.startswith("unet.unet") for key in keys):
407
- deprecation_message = "Keys starting with 'unet.unet' are deprecated."
408
- deprecate("unet.unet keys", "0.27", deprecation_message)
409
-
410
415
  if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
411
416
  # Load the layers corresponding to UNet.
412
417
  logger.info(f"Loading {cls.unet_name}.")
@@ -425,11 +430,9 @@ class LoraLoaderMixin:
425
430
  # contain the module names of the `unet` as its keys WITHOUT any prefix.
426
431
  if not USE_PEFT_BACKEND:
427
432
  warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
428
- logger.warn(warn_message)
429
-
430
- if USE_PEFT_BACKEND and len(state_dict.keys()) > 0:
431
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
433
+ logger.warning(warn_message)
432
434
 
435
+ if len(state_dict.keys()) > 0:
433
436
  if adapter_name in getattr(unet, "peft_config", {}):
434
437
  raise ValueError(
435
438
  f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
@@ -518,6 +521,11 @@ class LoraLoaderMixin:
518
521
  Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
519
522
  `default_{i}` where i is the total number of adapters being loaded.
520
523
  """
524
+ if not USE_PEFT_BACKEND:
525
+ raise ValueError("PEFT backend is required for this method.")
526
+
527
+ from peft import LoraConfig
528
+
521
529
  low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
522
530
 
523
531
  # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
@@ -539,34 +547,21 @@ class LoraLoaderMixin:
539
547
  rank = {}
540
548
  text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
541
549
 
542
- if USE_PEFT_BACKEND:
543
- # convert state dict
544
- text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
545
-
546
- for name, _ in text_encoder_attn_modules(text_encoder):
547
- rank_key = f"{name}.out_proj.lora_B.weight"
548
- rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
549
-
550
- patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
551
- if patch_mlp:
552
- for name, _ in text_encoder_mlp_modules(text_encoder):
553
- rank_key_fc1 = f"{name}.fc1.lora_B.weight"
554
- rank_key_fc2 = f"{name}.fc2.lora_B.weight"
555
-
556
- rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
557
- rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
558
- else:
559
- for name, _ in text_encoder_attn_modules(text_encoder):
560
- rank_key = f"{name}.out_proj.lora_linear_layer.up.weight"
561
- rank.update({rank_key: text_encoder_lora_state_dict[rank_key].shape[1]})
562
-
563
- patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
564
- if patch_mlp:
565
- for name, _ in text_encoder_mlp_modules(text_encoder):
566
- rank_key_fc1 = f"{name}.fc1.lora_linear_layer.up.weight"
567
- rank_key_fc2 = f"{name}.fc2.lora_linear_layer.up.weight"
568
- rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
569
- rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
550
+ # convert state dict
551
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
552
+
553
+ for name, _ in text_encoder_attn_modules(text_encoder):
554
+ rank_key = f"{name}.out_proj.lora_B.weight"
555
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
556
+
557
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
558
+ if patch_mlp:
559
+ for name, _ in text_encoder_mlp_modules(text_encoder):
560
+ rank_key_fc1 = f"{name}.fc1.lora_B.weight"
561
+ rank_key_fc2 = f"{name}.fc2.lora_B.weight"
562
+
563
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
564
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
570
565
 
571
566
  if network_alphas is not None:
572
567
  alpha_keys = [
@@ -576,84 +571,25 @@ class LoraLoaderMixin:
576
571
  k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
577
572
  }
578
573
 
579
- if USE_PEFT_BACKEND:
580
- from peft import LoraConfig
581
-
582
- lora_config_kwargs = get_peft_kwargs(
583
- rank, network_alphas, text_encoder_lora_state_dict, is_unet=False
584
- )
585
- lora_config = LoraConfig(**lora_config_kwargs)
586
-
587
- # adapter_name
588
- if adapter_name is None:
589
- adapter_name = get_adapter_name(text_encoder)
574
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
575
+ lora_config = LoraConfig(**lora_config_kwargs)
590
576
 
591
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
577
+ # adapter_name
578
+ if adapter_name is None:
579
+ adapter_name = get_adapter_name(text_encoder)
592
580
 
593
- # inject LoRA layers and load the state dict
594
- # in transformers we automatically check whether the adapter name is already in use or not
595
- text_encoder.load_adapter(
596
- adapter_name=adapter_name,
597
- adapter_state_dict=text_encoder_lora_state_dict,
598
- peft_config=lora_config,
599
- )
600
-
601
- # scale LoRA layers with `lora_scale`
602
- scale_lora_layers(text_encoder, weight=lora_scale)
603
- else:
604
- cls._modify_text_encoder(
605
- text_encoder,
606
- lora_scale,
607
- network_alphas,
608
- rank=rank,
609
- patch_mlp=patch_mlp,
610
- low_cpu_mem_usage=low_cpu_mem_usage,
611
- )
612
-
613
- is_pipeline_offloaded = _pipeline is not None and any(
614
- isinstance(c, torch.nn.Module) and hasattr(c, "_hf_hook")
615
- for c in _pipeline.components.values()
616
- )
617
- if is_pipeline_offloaded and low_cpu_mem_usage:
618
- low_cpu_mem_usage = True
619
- logger.info(
620
- f"Pipeline {_pipeline.__class__} is offloaded. Therefore low cpu mem usage loading is forced."
621
- )
581
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
622
582
 
623
- if low_cpu_mem_usage:
624
- device = next(iter(text_encoder_lora_state_dict.values())).device
625
- dtype = next(iter(text_encoder_lora_state_dict.values())).dtype
626
- unexpected_keys = load_model_dict_into_meta(
627
- text_encoder, text_encoder_lora_state_dict, device=device, dtype=dtype
628
- )
629
- else:
630
- load_state_dict_results = text_encoder.load_state_dict(
631
- text_encoder_lora_state_dict, strict=False
632
- )
633
- unexpected_keys = load_state_dict_results.unexpected_keys
634
-
635
- if len(unexpected_keys) != 0:
636
- raise ValueError(
637
- f"failed to load text encoder state dict, unexpected keys: {load_state_dict_results.unexpected_keys}"
638
- )
583
+ # inject LoRA layers and load the state dict
584
+ # in transformers we automatically check whether the adapter name is already in use or not
585
+ text_encoder.load_adapter(
586
+ adapter_name=adapter_name,
587
+ adapter_state_dict=text_encoder_lora_state_dict,
588
+ peft_config=lora_config,
589
+ )
639
590
 
640
- # <Unsafe code
641
- # We can be sure that the following works as all we do is change the dtype and device of the text encoder
642
- # Now we remove any existing hooks to
643
- is_model_cpu_offload = False
644
- is_sequential_cpu_offload = False
645
- if _pipeline is not None:
646
- for _, component in _pipeline.components.items():
647
- if isinstance(component, torch.nn.Module):
648
- if hasattr(component, "_hf_hook"):
649
- is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
650
- is_sequential_cpu_offload = isinstance(
651
- getattr(component, "_hf_hook"), AlignDevicesHook
652
- )
653
- logger.info(
654
- "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."
655
- )
656
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
591
+ # scale LoRA layers with `lora_scale`
592
+ scale_lora_layers(text_encoder, weight=lora_scale)
657
593
 
658
594
  text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
659
595
 
@@ -689,6 +625,8 @@ class LoraLoaderMixin:
689
625
  Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
690
626
  `default_{i}` where i is the total number of adapters being loaded.
691
627
  """
628
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
629
+
692
630
  low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
693
631
 
694
632
  keys = list(state_dict.keys())
@@ -705,8 +643,6 @@ class LoraLoaderMixin:
705
643
  }
706
644
 
707
645
  if len(state_dict.keys()) > 0:
708
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
709
-
710
646
  if adapter_name in getattr(transformer, "peft_config", {}):
711
647
  raise ValueError(
712
648
  f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
@@ -754,118 +690,20 @@ class LoraLoaderMixin:
754
690
  return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
755
691
 
756
692
  def _remove_text_encoder_monkey_patch(self):
757
- if USE_PEFT_BACKEND:
758
- remove_method = recurse_remove_peft_layers
759
- else:
760
- remove_method = self._remove_text_encoder_monkey_patch_classmethod
761
-
693
+ remove_method = recurse_remove_peft_layers
762
694
  if hasattr(self, "text_encoder"):
763
695
  remove_method(self.text_encoder)
764
-
765
696
  # In case text encoder have no Lora attached
766
- if USE_PEFT_BACKEND and getattr(self.text_encoder, "peft_config", None) is not None:
697
+ if getattr(self.text_encoder, "peft_config", None) is not None:
767
698
  del self.text_encoder.peft_config
768
699
  self.text_encoder._hf_peft_config_loaded = None
700
+
769
701
  if hasattr(self, "text_encoder_2"):
770
702
  remove_method(self.text_encoder_2)
771
- if USE_PEFT_BACKEND:
703
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
772
704
  del self.text_encoder_2.peft_config
773
705
  self.text_encoder_2._hf_peft_config_loaded = None
774
706
 
775
- @classmethod
776
- def _remove_text_encoder_monkey_patch_classmethod(cls, text_encoder):
777
- deprecate("_remove_text_encoder_monkey_patch_classmethod", "0.27", LORA_DEPRECATION_MESSAGE)
778
-
779
- for _, attn_module in text_encoder_attn_modules(text_encoder):
780
- if isinstance(attn_module.q_proj, PatchedLoraProjection):
781
- attn_module.q_proj.lora_linear_layer = None
782
- attn_module.k_proj.lora_linear_layer = None
783
- attn_module.v_proj.lora_linear_layer = None
784
- attn_module.out_proj.lora_linear_layer = None
785
-
786
- for _, mlp_module in text_encoder_mlp_modules(text_encoder):
787
- if isinstance(mlp_module.fc1, PatchedLoraProjection):
788
- mlp_module.fc1.lora_linear_layer = None
789
- mlp_module.fc2.lora_linear_layer = None
790
-
791
- @classmethod
792
- def _modify_text_encoder(
793
- cls,
794
- text_encoder,
795
- lora_scale=1,
796
- network_alphas=None,
797
- rank: Union[Dict[str, int], int] = 4,
798
- dtype=None,
799
- patch_mlp=False,
800
- low_cpu_mem_usage=False,
801
- ):
802
- r"""
803
- Monkey-patches the forward passes of attention modules of the text encoder.
804
- """
805
- deprecate("_modify_text_encoder", "0.27", LORA_DEPRECATION_MESSAGE)
806
-
807
- def create_patched_linear_lora(model, network_alpha, rank, dtype, lora_parameters):
808
- linear_layer = model.regular_linear_layer if isinstance(model, PatchedLoraProjection) else model
809
- ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
810
- with ctx():
811
- model = PatchedLoraProjection(linear_layer, lora_scale, network_alpha, rank, dtype=dtype)
812
-
813
- lora_parameters.extend(model.lora_linear_layer.parameters())
814
- return model
815
-
816
- # First, remove any monkey-patch that might have been applied before
817
- cls._remove_text_encoder_monkey_patch_classmethod(text_encoder)
818
-
819
- lora_parameters = []
820
- network_alphas = {} if network_alphas is None else network_alphas
821
- is_network_alphas_populated = len(network_alphas) > 0
822
-
823
- for name, attn_module in text_encoder_attn_modules(text_encoder):
824
- query_alpha = network_alphas.pop(name + ".to_q_lora.down.weight.alpha", None)
825
- key_alpha = network_alphas.pop(name + ".to_k_lora.down.weight.alpha", None)
826
- value_alpha = network_alphas.pop(name + ".to_v_lora.down.weight.alpha", None)
827
- out_alpha = network_alphas.pop(name + ".to_out_lora.down.weight.alpha", None)
828
-
829
- if isinstance(rank, dict):
830
- current_rank = rank.pop(f"{name}.out_proj.lora_linear_layer.up.weight")
831
- else:
832
- current_rank = rank
833
-
834
- attn_module.q_proj = create_patched_linear_lora(
835
- attn_module.q_proj, query_alpha, current_rank, dtype, lora_parameters
836
- )
837
- attn_module.k_proj = create_patched_linear_lora(
838
- attn_module.k_proj, key_alpha, current_rank, dtype, lora_parameters
839
- )
840
- attn_module.v_proj = create_patched_linear_lora(
841
- attn_module.v_proj, value_alpha, current_rank, dtype, lora_parameters
842
- )
843
- attn_module.out_proj = create_patched_linear_lora(
844
- attn_module.out_proj, out_alpha, current_rank, dtype, lora_parameters
845
- )
846
-
847
- if patch_mlp:
848
- for name, mlp_module in text_encoder_mlp_modules(text_encoder):
849
- fc1_alpha = network_alphas.pop(name + ".fc1.lora_linear_layer.down.weight.alpha", None)
850
- fc2_alpha = network_alphas.pop(name + ".fc2.lora_linear_layer.down.weight.alpha", None)
851
-
852
- current_rank_fc1 = rank.pop(f"{name}.fc1.lora_linear_layer.up.weight")
853
- current_rank_fc2 = rank.pop(f"{name}.fc2.lora_linear_layer.up.weight")
854
-
855
- mlp_module.fc1 = create_patched_linear_lora(
856
- mlp_module.fc1, fc1_alpha, current_rank_fc1, dtype, lora_parameters
857
- )
858
- mlp_module.fc2 = create_patched_linear_lora(
859
- mlp_module.fc2, fc2_alpha, current_rank_fc2, dtype, lora_parameters
860
- )
861
-
862
- if is_network_alphas_populated and len(network_alphas) > 0:
863
- raise ValueError(
864
- f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
865
- )
866
-
867
- return lora_parameters
868
-
869
707
  @classmethod
870
708
  def save_lora_weights(
871
709
  cls,
@@ -1039,10 +877,12 @@ class LoraLoaderMixin:
1039
877
  pipeline.fuse_lora(lora_scale=0.7)
1040
878
  ```
1041
879
  """
880
+ from peft.tuners.tuners_utils import BaseTunerLayer
881
+
1042
882
  if fuse_unet or fuse_text_encoder:
1043
883
  self.num_fused_loras += 1
1044
884
  if self.num_fused_loras > 1:
1045
- logger.warn(
885
+ logger.warning(
1046
886
  "The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
1047
887
  )
1048
888
 
@@ -1050,52 +890,26 @@ class LoraLoaderMixin:
1050
890
  unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1051
891
  unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
1052
892
 
1053
- if USE_PEFT_BACKEND:
1054
- from peft.tuners.tuners_utils import BaseTunerLayer
1055
-
1056
- def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
1057
- merge_kwargs = {"safe_merge": safe_fusing}
893
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
894
+ merge_kwargs = {"safe_merge": safe_fusing}
1058
895
 
1059
- for module in text_encoder.modules():
1060
- if isinstance(module, BaseTunerLayer):
1061
- if lora_scale != 1.0:
1062
- module.scale_layer(lora_scale)
896
+ for module in text_encoder.modules():
897
+ if isinstance(module, BaseTunerLayer):
898
+ if lora_scale != 1.0:
899
+ module.scale_layer(lora_scale)
1063
900
 
1064
- # For BC with previous PEFT versions, we need to check the signature
1065
- # of the `merge` method to see if it supports the `adapter_names` argument.
1066
- supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
1067
- if "adapter_names" in supported_merge_kwargs:
1068
- merge_kwargs["adapter_names"] = adapter_names
1069
- elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
1070
- raise ValueError(
1071
- "The `adapter_names` argument is not supported with your PEFT version. "
1072
- "Please upgrade to the latest version of PEFT. `pip install -U peft`"
1073
- )
1074
-
1075
- module.merge(**merge_kwargs)
1076
-
1077
- else:
1078
- deprecate("fuse_text_encoder_lora", "0.27", LORA_DEPRECATION_MESSAGE)
1079
-
1080
- def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, **kwargs):
1081
- if "adapter_names" in kwargs and kwargs["adapter_names"] is not None:
1082
- raise ValueError(
1083
- "The `adapter_names` argument is not supported in your environment. Please switch to PEFT "
1084
- "backend to use this argument by installing latest PEFT and transformers."
1085
- " `pip install -U peft transformers`"
1086
- )
1087
-
1088
- for _, attn_module in text_encoder_attn_modules(text_encoder):
1089
- if isinstance(attn_module.q_proj, PatchedLoraProjection):
1090
- attn_module.q_proj._fuse_lora(lora_scale, safe_fusing)
1091
- attn_module.k_proj._fuse_lora(lora_scale, safe_fusing)
1092
- attn_module.v_proj._fuse_lora(lora_scale, safe_fusing)
1093
- attn_module.out_proj._fuse_lora(lora_scale, safe_fusing)
901
+ # For BC with previous PEFT versions, we need to check the signature
902
+ # of the `merge` method to see if it supports the `adapter_names` argument.
903
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
904
+ if "adapter_names" in supported_merge_kwargs:
905
+ merge_kwargs["adapter_names"] = adapter_names
906
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
907
+ raise ValueError(
908
+ "The `adapter_names` argument is not supported with your PEFT version. "
909
+ "Please upgrade to the latest version of PEFT. `pip install -U peft`"
910
+ )
1094
911
 
1095
- for _, mlp_module in text_encoder_mlp_modules(text_encoder):
1096
- if isinstance(mlp_module.fc1, PatchedLoraProjection):
1097
- mlp_module.fc1._fuse_lora(lora_scale, safe_fusing)
1098
- mlp_module.fc2._fuse_lora(lora_scale, safe_fusing)
912
+ module.merge(**merge_kwargs)
1099
913
 
1100
914
  if fuse_text_encoder:
1101
915
  if hasattr(self, "text_encoder"):
@@ -1120,40 +934,18 @@ class LoraLoaderMixin:
1120
934
  Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
1121
935
  LoRA parameters then it won't have any effect.
1122
936
  """
937
+ from peft.tuners.tuners_utils import BaseTunerLayer
938
+
1123
939
  unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1124
940
  if unfuse_unet:
1125
- if not USE_PEFT_BACKEND:
1126
- unet.unfuse_lora()
1127
- else:
1128
- from peft.tuners.tuners_utils import BaseTunerLayer
1129
-
1130
- for module in unet.modules():
1131
- if isinstance(module, BaseTunerLayer):
1132
- module.unmerge()
1133
-
1134
- if USE_PEFT_BACKEND:
1135
- from peft.tuners.tuners_utils import BaseTunerLayer
1136
-
1137
- def unfuse_text_encoder_lora(text_encoder):
1138
- for module in text_encoder.modules():
1139
- if isinstance(module, BaseTunerLayer):
1140
- module.unmerge()
1141
-
1142
- else:
1143
- deprecate("unfuse_text_encoder_lora", "0.27", LORA_DEPRECATION_MESSAGE)
941
+ for module in unet.modules():
942
+ if isinstance(module, BaseTunerLayer):
943
+ module.unmerge()
1144
944
 
1145
- def unfuse_text_encoder_lora(text_encoder):
1146
- for _, attn_module in text_encoder_attn_modules(text_encoder):
1147
- if isinstance(attn_module.q_proj, PatchedLoraProjection):
1148
- attn_module.q_proj._unfuse_lora()
1149
- attn_module.k_proj._unfuse_lora()
1150
- attn_module.v_proj._unfuse_lora()
1151
- attn_module.out_proj._unfuse_lora()
1152
-
1153
- for _, mlp_module in text_encoder_mlp_modules(text_encoder):
1154
- if isinstance(mlp_module.fc1, PatchedLoraProjection):
1155
- mlp_module.fc1._unfuse_lora()
1156
- mlp_module.fc2._unfuse_lora()
945
+ def unfuse_text_encoder_lora(text_encoder):
946
+ for module in text_encoder.modules():
947
+ if isinstance(module, BaseTunerLayer):
948
+ module.unmerge()
1157
949
 
1158
950
  if unfuse_text_encoder:
1159
951
  if hasattr(self, "text_encoder"):
@@ -1404,7 +1196,7 @@ class LoraLoaderMixin:
1404
1196
  class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1405
1197
  """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1406
1198
 
1407
- # Overrride to properly handle the loading and unloading of the additional text encoder.
1199
+ # Override to properly handle the loading and unloading of the additional text encoder.
1408
1200
  def load_lora_weights(
1409
1201
  self,
1410
1202
  pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
@@ -1434,10 +1226,17 @@ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1434
1226
  kwargs (`dict`, *optional*):
1435
1227
  See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1436
1228
  """
1229
+ if not USE_PEFT_BACKEND:
1230
+ raise ValueError("PEFT backend is required for this method.")
1231
+
1437
1232
  # We could have accessed the unet config from `lora_state_dict()` too. We pass
1438
1233
  # it here explicitly to be able to tell that it's coming from an SDXL
1439
1234
  # pipeline.
1440
1235
 
1236
+ # if a dict is passed, copy it instead of modifying it inplace
1237
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
1238
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1239
+
1441
1240
  # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1442
1241
  state_dict, network_alphas = self.lora_state_dict(
1443
1242
  pretrained_model_name_or_path_or_dict,
@@ -1538,17 +1337,13 @@ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1538
1337
  )
1539
1338
 
1540
1339
  def _remove_text_encoder_monkey_patch(self):
1541
- if USE_PEFT_BACKEND:
1542
- recurse_remove_peft_layers(self.text_encoder)
1543
- # TODO: @younesbelkada handle this in transformers side
1544
- if getattr(self.text_encoder, "peft_config", None) is not None:
1545
- del self.text_encoder.peft_config
1546
- self.text_encoder._hf_peft_config_loaded = None
1547
-
1548
- recurse_remove_peft_layers(self.text_encoder_2)
1549
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
1550
- del self.text_encoder_2.peft_config
1551
- self.text_encoder_2._hf_peft_config_loaded = None
1552
- else:
1553
- self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1554
- self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
1340
+ recurse_remove_peft_layers(self.text_encoder)
1341
+ # TODO: @younesbelkada handle this in transformers side
1342
+ if getattr(self.text_encoder, "peft_config", None) is not None:
1343
+ del self.text_encoder.peft_config
1344
+ self.text_encoder._hf_peft_config_loaded = None
1345
+
1346
+ recurse_remove_peft_layers(self.text_encoder_2)
1347
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
1348
+ del self.text_encoder_2.peft_config
1349
+ self.text_encoder_2._hf_peft_config_loaded = None
@@ -1,4 +1,4 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
diffusers/loaders/peft.py CHANGED
@@ -1,5 +1,5 @@
1
1
  # coding=utf-8
2
- # Copyright 2023 The HuggingFace Inc. team.
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
3
  #
4
4
  # Licensed under the Apache License, Version 2.0 (the "License");
5
5
  # you may not use this file except in compliance with the License.