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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (445) hide show
  1. diffusers/__init__.py +233 -6
  2. diffusers/callbacks.py +209 -0
  3. diffusers/commands/env.py +102 -6
  4. diffusers/configuration_utils.py +45 -16
  5. diffusers/dependency_versions_table.py +4 -3
  6. diffusers/image_processor.py +434 -110
  7. diffusers/loaders/__init__.py +42 -9
  8. diffusers/loaders/ip_adapter.py +626 -36
  9. diffusers/loaders/lora_base.py +900 -0
  10. diffusers/loaders/lora_conversion_utils.py +991 -125
  11. diffusers/loaders/lora_pipeline.py +3812 -0
  12. diffusers/loaders/peft.py +571 -7
  13. diffusers/loaders/single_file.py +405 -173
  14. diffusers/loaders/single_file_model.py +385 -0
  15. diffusers/loaders/single_file_utils.py +1783 -713
  16. diffusers/loaders/textual_inversion.py +41 -23
  17. diffusers/loaders/transformer_flux.py +181 -0
  18. diffusers/loaders/transformer_sd3.py +89 -0
  19. diffusers/loaders/unet.py +464 -540
  20. diffusers/loaders/unet_loader_utils.py +163 -0
  21. diffusers/models/__init__.py +76 -7
  22. diffusers/models/activations.py +65 -10
  23. diffusers/models/adapter.py +53 -53
  24. diffusers/models/attention.py +605 -18
  25. diffusers/models/attention_flax.py +1 -1
  26. diffusers/models/attention_processor.py +4304 -687
  27. diffusers/models/autoencoders/__init__.py +8 -0
  28. diffusers/models/autoencoders/autoencoder_asym_kl.py +15 -17
  29. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  30. diffusers/models/autoencoders/autoencoder_kl.py +110 -28
  31. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  32. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1482 -0
  33. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  34. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  35. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  36. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +19 -24
  37. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  38. diffusers/models/autoencoders/autoencoder_tiny.py +21 -18
  39. diffusers/models/autoencoders/consistency_decoder_vae.py +45 -20
  40. diffusers/models/autoencoders/vae.py +41 -29
  41. diffusers/models/autoencoders/vq_model.py +182 -0
  42. diffusers/models/controlnet.py +47 -800
  43. diffusers/models/controlnet_flux.py +70 -0
  44. diffusers/models/controlnet_sd3.py +68 -0
  45. diffusers/models/controlnet_sparsectrl.py +116 -0
  46. diffusers/models/controlnets/__init__.py +23 -0
  47. diffusers/models/controlnets/controlnet.py +872 -0
  48. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +9 -9
  49. diffusers/models/controlnets/controlnet_flux.py +536 -0
  50. diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
  51. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  52. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  53. diffusers/models/controlnets/controlnet_union.py +832 -0
  54. diffusers/models/controlnets/controlnet_xs.py +1946 -0
  55. diffusers/models/controlnets/multicontrolnet.py +183 -0
  56. diffusers/models/downsampling.py +85 -18
  57. diffusers/models/embeddings.py +1856 -158
  58. diffusers/models/embeddings_flax.py +23 -9
  59. diffusers/models/model_loading_utils.py +480 -0
  60. diffusers/models/modeling_flax_pytorch_utils.py +2 -1
  61. diffusers/models/modeling_flax_utils.py +2 -7
  62. diffusers/models/modeling_outputs.py +14 -0
  63. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  64. diffusers/models/modeling_utils.py +611 -146
  65. diffusers/models/normalization.py +361 -20
  66. diffusers/models/resnet.py +18 -23
  67. diffusers/models/transformers/__init__.py +16 -0
  68. diffusers/models/transformers/auraflow_transformer_2d.py +544 -0
  69. diffusers/models/transformers/cogvideox_transformer_3d.py +542 -0
  70. diffusers/models/transformers/dit_transformer_2d.py +240 -0
  71. diffusers/models/transformers/dual_transformer_2d.py +9 -8
  72. diffusers/models/transformers/hunyuan_transformer_2d.py +578 -0
  73. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  74. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  75. diffusers/models/transformers/pixart_transformer_2d.py +445 -0
  76. diffusers/models/transformers/prior_transformer.py +13 -13
  77. diffusers/models/transformers/sana_transformer.py +488 -0
  78. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  79. diffusers/models/transformers/t5_film_transformer.py +17 -19
  80. diffusers/models/transformers/transformer_2d.py +297 -187
  81. diffusers/models/transformers/transformer_allegro.py +422 -0
  82. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  83. diffusers/models/transformers/transformer_flux.py +593 -0
  84. diffusers/models/transformers/transformer_hunyuan_video.py +791 -0
  85. diffusers/models/transformers/transformer_ltx.py +469 -0
  86. diffusers/models/transformers/transformer_mochi.py +499 -0
  87. diffusers/models/transformers/transformer_sd3.py +461 -0
  88. diffusers/models/transformers/transformer_temporal.py +21 -19
  89. diffusers/models/unets/unet_1d.py +8 -8
  90. diffusers/models/unets/unet_1d_blocks.py +31 -31
  91. diffusers/models/unets/unet_2d.py +17 -10
  92. diffusers/models/unets/unet_2d_blocks.py +225 -149
  93. diffusers/models/unets/unet_2d_condition.py +50 -53
  94. diffusers/models/unets/unet_2d_condition_flax.py +6 -5
  95. diffusers/models/unets/unet_3d_blocks.py +192 -1057
  96. diffusers/models/unets/unet_3d_condition.py +22 -27
  97. diffusers/models/unets/unet_i2vgen_xl.py +22 -18
  98. diffusers/models/unets/unet_kandinsky3.py +2 -2
  99. diffusers/models/unets/unet_motion_model.py +1413 -89
  100. diffusers/models/unets/unet_spatio_temporal_condition.py +40 -16
  101. diffusers/models/unets/unet_stable_cascade.py +19 -18
  102. diffusers/models/unets/uvit_2d.py +2 -2
  103. diffusers/models/upsampling.py +95 -26
  104. diffusers/models/vq_model.py +12 -164
  105. diffusers/optimization.py +1 -1
  106. diffusers/pipelines/__init__.py +202 -3
  107. diffusers/pipelines/allegro/__init__.py +48 -0
  108. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  109. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  110. diffusers/pipelines/amused/pipeline_amused.py +12 -12
  111. diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
  112. diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
  113. diffusers/pipelines/animatediff/__init__.py +8 -0
  114. diffusers/pipelines/animatediff/pipeline_animatediff.py +122 -109
  115. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1106 -0
  116. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1288 -0
  117. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1010 -0
  118. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +236 -180
  119. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  120. diffusers/pipelines/animatediff/pipeline_output.py +3 -2
  121. diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
  122. diffusers/pipelines/audioldm2/modeling_audioldm2.py +58 -39
  123. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +121 -36
  124. diffusers/pipelines/aura_flow/__init__.py +48 -0
  125. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +584 -0
  126. diffusers/pipelines/auto_pipeline.py +196 -28
  127. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  128. diffusers/pipelines/blip_diffusion/modeling_blip2.py +6 -6
  129. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
  130. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  131. diffusers/pipelines/cogvideo/__init__.py +54 -0
  132. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +772 -0
  133. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
  134. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +885 -0
  135. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +851 -0
  136. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  137. diffusers/pipelines/cogview3/__init__.py +47 -0
  138. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  139. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  140. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +6 -6
  141. diffusers/pipelines/controlnet/__init__.py +86 -80
  142. diffusers/pipelines/controlnet/multicontrolnet.py +7 -182
  143. diffusers/pipelines/controlnet/pipeline_controlnet.py +134 -87
  144. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  145. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +93 -77
  146. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +88 -197
  147. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +136 -90
  148. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +176 -80
  149. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +125 -89
  150. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  151. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  152. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  153. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  154. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  155. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1060 -0
  156. diffusers/pipelines/controlnet_sd3/__init__.py +57 -0
  157. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +1133 -0
  158. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  159. diffusers/pipelines/controlnet_xs/__init__.py +68 -0
  160. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +916 -0
  161. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1111 -0
  162. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  163. diffusers/pipelines/deepfloyd_if/pipeline_if.py +16 -30
  164. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +20 -35
  165. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +23 -41
  166. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +22 -38
  167. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +25 -41
  168. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +19 -34
  169. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  170. diffusers/pipelines/deepfloyd_if/watermark.py +1 -1
  171. diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
  172. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +70 -30
  173. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +48 -25
  174. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
  175. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
  176. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +21 -20
  177. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +27 -29
  178. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +33 -27
  179. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +33 -23
  180. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +36 -30
  181. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +102 -69
  182. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
  183. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
  184. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
  185. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
  186. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
  187. diffusers/pipelines/dit/pipeline_dit.py +7 -4
  188. diffusers/pipelines/flux/__init__.py +69 -0
  189. diffusers/pipelines/flux/modeling_flux.py +47 -0
  190. diffusers/pipelines/flux/pipeline_flux.py +957 -0
  191. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  192. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  193. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  194. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
  195. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
  196. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
  197. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  198. diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
  199. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
  200. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  201. diffusers/pipelines/flux/pipeline_output.py +37 -0
  202. diffusers/pipelines/free_init_utils.py +41 -38
  203. diffusers/pipelines/free_noise_utils.py +596 -0
  204. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  205. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  206. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  207. diffusers/pipelines/hunyuandit/__init__.py +48 -0
  208. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +916 -0
  209. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
  210. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
  211. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +32 -29
  212. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
  213. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
  214. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
  215. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  216. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +34 -31
  217. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
  218. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
  219. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
  220. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
  221. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
  222. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
  223. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
  224. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +22 -35
  225. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +26 -37
  226. diffusers/pipelines/kolors/__init__.py +54 -0
  227. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  228. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1250 -0
  229. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  230. diffusers/pipelines/kolors/text_encoder.py +889 -0
  231. diffusers/pipelines/kolors/tokenizer.py +338 -0
  232. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +82 -62
  233. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +77 -60
  234. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +12 -12
  235. diffusers/pipelines/latte/__init__.py +48 -0
  236. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  237. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +80 -74
  238. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +85 -76
  239. diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
  240. diffusers/pipelines/ltx/__init__.py +50 -0
  241. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  242. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  243. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  244. diffusers/pipelines/lumina/__init__.py +48 -0
  245. diffusers/pipelines/lumina/pipeline_lumina.py +890 -0
  246. diffusers/pipelines/marigold/__init__.py +50 -0
  247. diffusers/pipelines/marigold/marigold_image_processing.py +576 -0
  248. diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
  249. diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
  250. diffusers/pipelines/mochi/__init__.py +48 -0
  251. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  252. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  253. diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
  254. diffusers/pipelines/pag/__init__.py +80 -0
  255. diffusers/pipelines/pag/pag_utils.py +243 -0
  256. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1328 -0
  257. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
  258. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1610 -0
  259. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
  260. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +969 -0
  261. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  262. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +865 -0
  263. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  264. diffusers/pipelines/pag/pipeline_pag_sd.py +1062 -0
  265. diffusers/pipelines/pag/pipeline_pag_sd_3.py +994 -0
  266. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  267. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +866 -0
  268. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
  269. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  270. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1345 -0
  271. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1544 -0
  272. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1776 -0
  273. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
  274. diffusers/pipelines/pia/pipeline_pia.py +74 -164
  275. diffusers/pipelines/pipeline_flax_utils.py +5 -10
  276. diffusers/pipelines/pipeline_loading_utils.py +515 -53
  277. diffusers/pipelines/pipeline_utils.py +411 -222
  278. diffusers/pipelines/pixart_alpha/__init__.py +8 -1
  279. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +76 -93
  280. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +873 -0
  281. diffusers/pipelines/sana/__init__.py +47 -0
  282. diffusers/pipelines/sana/pipeline_output.py +21 -0
  283. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  284. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +27 -23
  285. diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
  286. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
  287. diffusers/pipelines/shap_e/renderer.py +1 -1
  288. diffusers/pipelines/stable_audio/__init__.py +50 -0
  289. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  290. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +756 -0
  291. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +71 -25
  292. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
  293. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +35 -34
  294. diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  295. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +20 -11
  296. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  297. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  298. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
  299. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +145 -79
  300. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +43 -28
  301. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
  302. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +100 -68
  303. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +109 -201
  304. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +131 -32
  305. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +247 -87
  306. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +30 -29
  307. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +35 -27
  308. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +49 -42
  309. diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
  310. diffusers/pipelines/stable_diffusion_3/__init__.py +54 -0
  311. diffusers/pipelines/stable_diffusion_3/pipeline_output.py +21 -0
  312. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1140 -0
  313. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1036 -0
  314. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1250 -0
  315. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +29 -20
  316. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +59 -58
  317. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +31 -25
  318. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +38 -22
  319. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +30 -24
  320. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -23
  321. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +107 -67
  322. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +316 -69
  323. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
  324. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  325. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +98 -30
  326. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +121 -83
  327. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +161 -105
  328. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +142 -218
  329. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -29
  330. diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
  331. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
  332. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +69 -39
  333. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +105 -74
  334. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
  335. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +29 -49
  336. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +32 -93
  337. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +37 -25
  338. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +54 -40
  339. diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
  340. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
  341. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
  342. diffusers/pipelines/unidiffuser/modeling_uvit.py +12 -12
  343. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +29 -28
  344. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
  345. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
  346. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +6 -8
  347. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
  348. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
  349. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +15 -14
  350. diffusers/{models/dual_transformer_2d.py → quantizers/__init__.py} +2 -6
  351. diffusers/quantizers/auto.py +139 -0
  352. diffusers/quantizers/base.py +233 -0
  353. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  354. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
  355. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  356. diffusers/quantizers/gguf/__init__.py +1 -0
  357. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  358. diffusers/quantizers/gguf/utils.py +456 -0
  359. diffusers/quantizers/quantization_config.py +669 -0
  360. diffusers/quantizers/torchao/__init__.py +15 -0
  361. diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
  362. diffusers/schedulers/__init__.py +12 -2
  363. diffusers/schedulers/deprecated/__init__.py +1 -1
  364. diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
  365. diffusers/schedulers/scheduling_amused.py +5 -5
  366. diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
  367. diffusers/schedulers/scheduling_consistency_models.py +23 -25
  368. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  369. diffusers/schedulers/scheduling_ddim.py +27 -26
  370. diffusers/schedulers/scheduling_ddim_cogvideox.py +452 -0
  371. diffusers/schedulers/scheduling_ddim_flax.py +2 -1
  372. diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
  373. diffusers/schedulers/scheduling_ddim_parallel.py +32 -31
  374. diffusers/schedulers/scheduling_ddpm.py +27 -30
  375. diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
  376. diffusers/schedulers/scheduling_ddpm_parallel.py +33 -36
  377. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
  378. diffusers/schedulers/scheduling_deis_multistep.py +150 -50
  379. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  380. diffusers/schedulers/scheduling_dpmsolver_multistep.py +221 -84
  381. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
  382. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +158 -52
  383. diffusers/schedulers/scheduling_dpmsolver_sde.py +153 -34
  384. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +275 -86
  385. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +81 -57
  386. diffusers/schedulers/scheduling_edm_euler.py +62 -39
  387. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +30 -29
  388. diffusers/schedulers/scheduling_euler_discrete.py +255 -74
  389. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +458 -0
  390. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +320 -0
  391. diffusers/schedulers/scheduling_heun_discrete.py +174 -46
  392. diffusers/schedulers/scheduling_ipndm.py +9 -9
  393. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +138 -29
  394. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +132 -26
  395. diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
  396. diffusers/schedulers/scheduling_lcm.py +23 -29
  397. diffusers/schedulers/scheduling_lms_discrete.py +105 -28
  398. diffusers/schedulers/scheduling_pndm.py +20 -20
  399. diffusers/schedulers/scheduling_repaint.py +21 -21
  400. diffusers/schedulers/scheduling_sasolver.py +157 -60
  401. diffusers/schedulers/scheduling_sde_ve.py +19 -19
  402. diffusers/schedulers/scheduling_tcd.py +41 -36
  403. diffusers/schedulers/scheduling_unclip.py +19 -16
  404. diffusers/schedulers/scheduling_unipc_multistep.py +243 -47
  405. diffusers/schedulers/scheduling_utils.py +12 -5
  406. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  407. diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
  408. diffusers/training_utils.py +214 -30
  409. diffusers/utils/__init__.py +17 -1
  410. diffusers/utils/constants.py +3 -0
  411. diffusers/utils/doc_utils.py +1 -0
  412. diffusers/utils/dummy_pt_objects.py +592 -7
  413. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  414. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  415. diffusers/utils/dummy_torch_and_transformers_objects.py +1001 -71
  416. diffusers/utils/dynamic_modules_utils.py +34 -29
  417. diffusers/utils/export_utils.py +50 -6
  418. diffusers/utils/hub_utils.py +131 -17
  419. diffusers/utils/import_utils.py +210 -8
  420. diffusers/utils/loading_utils.py +118 -5
  421. diffusers/utils/logging.py +4 -2
  422. diffusers/utils/peft_utils.py +37 -7
  423. diffusers/utils/state_dict_utils.py +13 -2
  424. diffusers/utils/testing_utils.py +193 -11
  425. diffusers/utils/torch_utils.py +4 -0
  426. diffusers/video_processor.py +113 -0
  427. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/METADATA +82 -91
  428. diffusers-0.32.2.dist-info/RECORD +550 -0
  429. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/WHEEL +1 -1
  430. diffusers/loaders/autoencoder.py +0 -146
  431. diffusers/loaders/controlnet.py +0 -136
  432. diffusers/loaders/lora.py +0 -1349
  433. diffusers/models/prior_transformer.py +0 -12
  434. diffusers/models/t5_film_transformer.py +0 -70
  435. diffusers/models/transformer_2d.py +0 -25
  436. diffusers/models/transformer_temporal.py +0 -34
  437. diffusers/models/unet_1d.py +0 -26
  438. diffusers/models/unet_1d_blocks.py +0 -203
  439. diffusers/models/unet_2d.py +0 -27
  440. diffusers/models/unet_2d_blocks.py +0 -375
  441. diffusers/models/unet_2d_condition.py +0 -25
  442. diffusers-0.27.0.dist-info/RECORD +0 -399
  443. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/LICENSE +0 -0
  444. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/entry_points.txt +0 -0
  445. {diffusers-0.27.0.dist-info → diffusers-0.32.2.dist-info}/top_level.txt +0 -0
diffusers/loaders/lora.py DELETED
@@ -1,1349 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import inspect
15
- import os
16
- from pathlib import Path
17
- from typing import Callable, Dict, List, Optional, Union
18
-
19
- import safetensors
20
- import torch
21
- from huggingface_hub import model_info
22
- from huggingface_hub.constants import HF_HUB_OFFLINE
23
- from huggingface_hub.utils import validate_hf_hub_args
24
- from packaging import version
25
- from torch import nn
26
-
27
- from .. import __version__
28
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
29
- from ..utils import (
30
- USE_PEFT_BACKEND,
31
- _get_model_file,
32
- convert_state_dict_to_diffusers,
33
- convert_state_dict_to_peft,
34
- convert_unet_state_dict_to_peft,
35
- delete_adapter_layers,
36
- get_adapter_name,
37
- get_peft_kwargs,
38
- is_accelerate_available,
39
- is_transformers_available,
40
- logging,
41
- recurse_remove_peft_layers,
42
- scale_lora_layers,
43
- set_adapter_layers,
44
- set_weights_and_activate_adapters,
45
- )
46
- from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
47
-
48
-
49
- if is_transformers_available():
50
- from transformers import PreTrainedModel
51
-
52
- from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
53
-
54
- if is_accelerate_available():
55
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
56
-
57
- logger = logging.get_logger(__name__)
58
-
59
- TEXT_ENCODER_NAME = "text_encoder"
60
- UNET_NAME = "unet"
61
- TRANSFORMER_NAME = "transformer"
62
-
63
- LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
64
- LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
65
-
66
- LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
67
-
68
-
69
- class LoraLoaderMixin:
70
- r"""
71
- Load LoRA layers into [`UNet2DConditionModel`] and
72
- [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
73
- """
74
-
75
- text_encoder_name = TEXT_ENCODER_NAME
76
- unet_name = UNET_NAME
77
- transformer_name = TRANSFORMER_NAME
78
- num_fused_loras = 0
79
-
80
- def load_lora_weights(
81
- self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
82
- ):
83
- """
84
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
85
- `self.text_encoder`.
86
-
87
- All kwargs are forwarded to `self.lora_state_dict`.
88
-
89
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
90
-
91
- See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
92
- `self.unet`.
93
-
94
- See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
95
- into `self.text_encoder`.
96
-
97
- Parameters:
98
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
99
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
100
- kwargs (`dict`, *optional*):
101
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
102
- adapter_name (`str`, *optional*):
103
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
104
- `default_{i}` where i is the total number of adapters being loaded.
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
-
113
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
114
- state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
115
-
116
- is_correct_format = all("lora" in key for key in state_dict.keys())
117
- if not is_correct_format:
118
- raise ValueError("Invalid LoRA checkpoint.")
119
-
120
- low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
121
-
122
- self.load_lora_into_unet(
123
- state_dict,
124
- network_alphas=network_alphas,
125
- unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
126
- low_cpu_mem_usage=low_cpu_mem_usage,
127
- adapter_name=adapter_name,
128
- _pipeline=self,
129
- )
130
- self.load_lora_into_text_encoder(
131
- state_dict,
132
- network_alphas=network_alphas,
133
- text_encoder=getattr(self, self.text_encoder_name)
134
- if not hasattr(self, "text_encoder")
135
- else self.text_encoder,
136
- lora_scale=self.lora_scale,
137
- low_cpu_mem_usage=low_cpu_mem_usage,
138
- adapter_name=adapter_name,
139
- _pipeline=self,
140
- )
141
-
142
- @classmethod
143
- @validate_hf_hub_args
144
- def lora_state_dict(
145
- cls,
146
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
147
- **kwargs,
148
- ):
149
- r"""
150
- Return state dict for lora weights and the network alphas.
151
-
152
- <Tip warning={true}>
153
-
154
- We support loading A1111 formatted LoRA checkpoints in a limited capacity.
155
-
156
- This function is experimental and might change in the future.
157
-
158
- </Tip>
159
-
160
- Parameters:
161
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
162
- Can be either:
163
-
164
- - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
165
- the Hub.
166
- - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
167
- with [`ModelMixin.save_pretrained`].
168
- - A [torch state
169
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
170
-
171
- cache_dir (`Union[str, os.PathLike]`, *optional*):
172
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
173
- is not used.
174
- force_download (`bool`, *optional*, defaults to `False`):
175
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
176
- cached versions if they exist.
177
- resume_download (`bool`, *optional*, defaults to `False`):
178
- Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
179
- incompletely downloaded files are deleted.
180
- proxies (`Dict[str, str]`, *optional*):
181
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
182
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
183
- local_files_only (`bool`, *optional*, defaults to `False`):
184
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
185
- won't be downloaded from the Hub.
186
- token (`str` or *bool*, *optional*):
187
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
188
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
189
- revision (`str`, *optional*, defaults to `"main"`):
190
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
191
- allowed by Git.
192
- subfolder (`str`, *optional*, defaults to `""`):
193
- The subfolder location of a model file within a larger model repository on the Hub or locally.
194
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
195
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
196
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
197
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
198
- argument to `True` will raise an error.
199
- mirror (`str`, *optional*):
200
- Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
201
- guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
202
- information.
203
-
204
- """
205
- # Load the main state dict first which has the LoRA layers for either of
206
- # UNet and text encoder or both.
207
- cache_dir = kwargs.pop("cache_dir", None)
208
- force_download = kwargs.pop("force_download", False)
209
- resume_download = kwargs.pop("resume_download", False)
210
- proxies = kwargs.pop("proxies", None)
211
- local_files_only = kwargs.pop("local_files_only", None)
212
- token = kwargs.pop("token", None)
213
- revision = kwargs.pop("revision", None)
214
- subfolder = kwargs.pop("subfolder", None)
215
- weight_name = kwargs.pop("weight_name", None)
216
- unet_config = kwargs.pop("unet_config", None)
217
- use_safetensors = kwargs.pop("use_safetensors", None)
218
-
219
- allow_pickle = False
220
- if use_safetensors is None:
221
- use_safetensors = True
222
- allow_pickle = True
223
-
224
- user_agent = {
225
- "file_type": "attn_procs_weights",
226
- "framework": "pytorch",
227
- }
228
-
229
- model_file = None
230
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
231
- # Let's first try to load .safetensors weights
232
- if (use_safetensors and weight_name is None) or (
233
- weight_name is not None and weight_name.endswith(".safetensors")
234
- ):
235
- try:
236
- # Here we're relaxing the loading check to enable more Inference API
237
- # friendliness where sometimes, it's not at all possible to automatically
238
- # determine `weight_name`.
239
- if weight_name is None:
240
- weight_name = cls._best_guess_weight_name(
241
- pretrained_model_name_or_path_or_dict,
242
- file_extension=".safetensors",
243
- local_files_only=local_files_only,
244
- )
245
- model_file = _get_model_file(
246
- pretrained_model_name_or_path_or_dict,
247
- weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
248
- cache_dir=cache_dir,
249
- force_download=force_download,
250
- resume_download=resume_download,
251
- proxies=proxies,
252
- local_files_only=local_files_only,
253
- token=token,
254
- revision=revision,
255
- subfolder=subfolder,
256
- user_agent=user_agent,
257
- )
258
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
259
- except (IOError, safetensors.SafetensorError) as e:
260
- if not allow_pickle:
261
- raise e
262
- # try loading non-safetensors weights
263
- model_file = None
264
- pass
265
-
266
- if model_file is None:
267
- if weight_name is None:
268
- weight_name = cls._best_guess_weight_name(
269
- pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
270
- )
271
- model_file = _get_model_file(
272
- pretrained_model_name_or_path_or_dict,
273
- weights_name=weight_name or LORA_WEIGHT_NAME,
274
- cache_dir=cache_dir,
275
- force_download=force_download,
276
- resume_download=resume_download,
277
- proxies=proxies,
278
- local_files_only=local_files_only,
279
- token=token,
280
- revision=revision,
281
- subfolder=subfolder,
282
- user_agent=user_agent,
283
- )
284
- state_dict = torch.load(model_file, map_location="cpu")
285
- else:
286
- state_dict = pretrained_model_name_or_path_or_dict
287
-
288
- network_alphas = None
289
- # TODO: replace it with a method from `state_dict_utils`
290
- if all(
291
- (
292
- k.startswith("lora_te_")
293
- or k.startswith("lora_unet_")
294
- or k.startswith("lora_te1_")
295
- or k.startswith("lora_te2_")
296
- )
297
- for k in state_dict.keys()
298
- ):
299
- # Map SDXL blocks correctly.
300
- if unet_config is not None:
301
- # use unet config to remap block numbers
302
- state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
303
- state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
304
-
305
- return state_dict, network_alphas
306
-
307
- @classmethod
308
- def _best_guess_weight_name(
309
- cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
310
- ):
311
- if local_files_only or HF_HUB_OFFLINE:
312
- raise ValueError("When using the offline mode, you must specify a `weight_name`.")
313
-
314
- targeted_files = []
315
-
316
- if os.path.isfile(pretrained_model_name_or_path_or_dict):
317
- return
318
- elif os.path.isdir(pretrained_model_name_or_path_or_dict):
319
- targeted_files = [
320
- f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
321
- ]
322
- else:
323
- files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
324
- targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
325
- if len(targeted_files) == 0:
326
- return
327
-
328
- # "scheduler" does not correspond to a LoRA checkpoint.
329
- # "optimizer" does not correspond to a LoRA checkpoint
330
- # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
331
- unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
332
- targeted_files = list(
333
- filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
334
- )
335
-
336
- if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
337
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
338
- elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
339
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
340
-
341
- if len(targeted_files) > 1:
342
- raise ValueError(
343
- f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
344
- )
345
- weight_name = targeted_files[0]
346
- return weight_name
347
-
348
- @classmethod
349
- def _optionally_disable_offloading(cls, _pipeline):
350
- """
351
- Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
352
-
353
- Args:
354
- _pipeline (`DiffusionPipeline`):
355
- The pipeline to disable offloading for.
356
-
357
- Returns:
358
- tuple:
359
- A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
360
- """
361
- is_model_cpu_offload = False
362
- is_sequential_cpu_offload = False
363
-
364
- if _pipeline is not None:
365
- for _, component in _pipeline.components.items():
366
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
367
- if not is_model_cpu_offload:
368
- is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
369
- if not is_sequential_cpu_offload:
370
- is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
371
-
372
- logger.info(
373
- "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."
374
- )
375
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
376
-
377
- return (is_model_cpu_offload, is_sequential_cpu_offload)
378
-
379
- @classmethod
380
- def load_lora_into_unet(
381
- cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
382
- ):
383
- """
384
- This will load the LoRA layers specified in `state_dict` into `unet`.
385
-
386
- Parameters:
387
- state_dict (`dict`):
388
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
389
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
390
- encoder lora layers.
391
- network_alphas (`Dict[str, float]`):
392
- See `LoRALinearLayer` for more details.
393
- unet (`UNet2DConditionModel`):
394
- The UNet model to load the LoRA layers into.
395
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
396
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
397
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
398
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
399
- argument to `True` will raise an error.
400
- adapter_name (`str`, *optional*):
401
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
402
- `default_{i}` where i is the total number of adapters being loaded.
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
-
409
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
410
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
411
- # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
412
- # their prefixes.
413
- keys = list(state_dict.keys())
414
-
415
- if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
416
- # Load the layers corresponding to UNet.
417
- logger.info(f"Loading {cls.unet_name}.")
418
-
419
- unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
420
- state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
421
-
422
- if network_alphas is not None:
423
- alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
424
- network_alphas = {
425
- k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
426
- }
427
-
428
- else:
429
- # Otherwise, we're dealing with the old format. This means the `state_dict` should only
430
- # contain the module names of the `unet` as its keys WITHOUT any prefix.
431
- if not USE_PEFT_BACKEND:
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()}`."
433
- logger.warning(warn_message)
434
-
435
- if len(state_dict.keys()) > 0:
436
- if adapter_name in getattr(unet, "peft_config", {}):
437
- raise ValueError(
438
- f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
439
- )
440
-
441
- state_dict = convert_unet_state_dict_to_peft(state_dict)
442
-
443
- if network_alphas is not None:
444
- # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
445
- # `convert_unet_state_dict_to_peft` method.
446
- network_alphas = convert_unet_state_dict_to_peft(network_alphas)
447
-
448
- rank = {}
449
- for key, val in state_dict.items():
450
- if "lora_B" in key:
451
- rank[key] = val.shape[1]
452
-
453
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
454
- lora_config = LoraConfig(**lora_config_kwargs)
455
-
456
- # adapter_name
457
- if adapter_name is None:
458
- adapter_name = get_adapter_name(unet)
459
-
460
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
461
- # otherwise loading LoRA weights will lead to an error
462
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
463
-
464
- inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
465
- incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
466
-
467
- if incompatible_keys is not None:
468
- # check only for unexpected keys
469
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
470
- if unexpected_keys:
471
- logger.warning(
472
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
473
- f" {unexpected_keys}. "
474
- )
475
-
476
- # Offload back.
477
- if is_model_cpu_offload:
478
- _pipeline.enable_model_cpu_offload()
479
- elif is_sequential_cpu_offload:
480
- _pipeline.enable_sequential_cpu_offload()
481
- # Unsafe code />
482
-
483
- unet.load_attn_procs(
484
- state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
485
- )
486
-
487
- @classmethod
488
- def load_lora_into_text_encoder(
489
- cls,
490
- state_dict,
491
- network_alphas,
492
- text_encoder,
493
- prefix=None,
494
- lora_scale=1.0,
495
- low_cpu_mem_usage=None,
496
- adapter_name=None,
497
- _pipeline=None,
498
- ):
499
- """
500
- This will load the LoRA layers specified in `state_dict` into `text_encoder`
501
-
502
- Parameters:
503
- state_dict (`dict`):
504
- A standard state dict containing the lora layer parameters. The key should be prefixed with an
505
- additional `text_encoder` to distinguish between unet lora layers.
506
- network_alphas (`Dict[str, float]`):
507
- See `LoRALinearLayer` for more details.
508
- text_encoder (`CLIPTextModel`):
509
- The text encoder model to load the LoRA layers into.
510
- prefix (`str`):
511
- Expected prefix of the `text_encoder` in the `state_dict`.
512
- lora_scale (`float`):
513
- How much to scale the output of the lora linear layer before it is added with the output of the regular
514
- lora layer.
515
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
516
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
517
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
518
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
519
- argument to `True` will raise an error.
520
- adapter_name (`str`, *optional*):
521
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
522
- `default_{i}` where i is the total number of adapters being loaded.
523
- """
524
- if not USE_PEFT_BACKEND:
525
- raise ValueError("PEFT backend is required for this method.")
526
-
527
- from peft import LoraConfig
528
-
529
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
530
-
531
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
532
- # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
533
- # their prefixes.
534
- keys = list(state_dict.keys())
535
- prefix = cls.text_encoder_name if prefix is None else prefix
536
-
537
- # Safe prefix to check with.
538
- if any(cls.text_encoder_name in key for key in keys):
539
- # Load the layers corresponding to text encoder and make necessary adjustments.
540
- text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
541
- text_encoder_lora_state_dict = {
542
- k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
543
- }
544
-
545
- if len(text_encoder_lora_state_dict) > 0:
546
- logger.info(f"Loading {prefix}.")
547
- rank = {}
548
- text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
549
-
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]
565
-
566
- if network_alphas is not None:
567
- alpha_keys = [
568
- k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
569
- ]
570
- network_alphas = {
571
- k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
572
- }
573
-
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)
576
-
577
- # adapter_name
578
- if adapter_name is None:
579
- adapter_name = get_adapter_name(text_encoder)
580
-
581
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
582
-
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
- )
590
-
591
- # scale LoRA layers with `lora_scale`
592
- scale_lora_layers(text_encoder, weight=lora_scale)
593
-
594
- text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
595
-
596
- # Offload back.
597
- if is_model_cpu_offload:
598
- _pipeline.enable_model_cpu_offload()
599
- elif is_sequential_cpu_offload:
600
- _pipeline.enable_sequential_cpu_offload()
601
- # Unsafe code />
602
-
603
- @classmethod
604
- def load_lora_into_transformer(
605
- cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
606
- ):
607
- """
608
- This will load the LoRA layers specified in `state_dict` into `transformer`.
609
-
610
- Parameters:
611
- state_dict (`dict`):
612
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
613
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
614
- encoder lora layers.
615
- network_alphas (`Dict[str, float]`):
616
- See `LoRALinearLayer` for more details.
617
- unet (`UNet2DConditionModel`):
618
- The UNet model to load the LoRA layers into.
619
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
620
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
621
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
622
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
623
- argument to `True` will raise an error.
624
- adapter_name (`str`, *optional*):
625
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
626
- `default_{i}` where i is the total number of adapters being loaded.
627
- """
628
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
629
-
630
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
631
-
632
- keys = list(state_dict.keys())
633
-
634
- transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
635
- state_dict = {
636
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
637
- }
638
-
639
- if network_alphas is not None:
640
- alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
641
- network_alphas = {
642
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
643
- }
644
-
645
- if len(state_dict.keys()) > 0:
646
- if adapter_name in getattr(transformer, "peft_config", {}):
647
- raise ValueError(
648
- f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
649
- )
650
-
651
- rank = {}
652
- for key, val in state_dict.items():
653
- if "lora_B" in key:
654
- rank[key] = val.shape[1]
655
-
656
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
657
- lora_config = LoraConfig(**lora_config_kwargs)
658
-
659
- # adapter_name
660
- if adapter_name is None:
661
- adapter_name = get_adapter_name(transformer)
662
-
663
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
664
- # otherwise loading LoRA weights will lead to an error
665
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
666
-
667
- inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
668
- incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
669
-
670
- if incompatible_keys is not None:
671
- # check only for unexpected keys
672
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
673
- if unexpected_keys:
674
- logger.warning(
675
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
676
- f" {unexpected_keys}. "
677
- )
678
-
679
- # Offload back.
680
- if is_model_cpu_offload:
681
- _pipeline.enable_model_cpu_offload()
682
- elif is_sequential_cpu_offload:
683
- _pipeline.enable_sequential_cpu_offload()
684
- # Unsafe code />
685
-
686
- @property
687
- def lora_scale(self) -> float:
688
- # property function that returns the lora scale which can be set at run time by the pipeline.
689
- # if _lora_scale has not been set, return 1
690
- return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
691
-
692
- def _remove_text_encoder_monkey_patch(self):
693
- remove_method = recurse_remove_peft_layers
694
- if hasattr(self, "text_encoder"):
695
- remove_method(self.text_encoder)
696
- # In case text encoder have no Lora attached
697
- if getattr(self.text_encoder, "peft_config", None) is not None:
698
- del self.text_encoder.peft_config
699
- self.text_encoder._hf_peft_config_loaded = None
700
-
701
- if hasattr(self, "text_encoder_2"):
702
- remove_method(self.text_encoder_2)
703
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
704
- del self.text_encoder_2.peft_config
705
- self.text_encoder_2._hf_peft_config_loaded = None
706
-
707
- @classmethod
708
- def save_lora_weights(
709
- cls,
710
- save_directory: Union[str, os.PathLike],
711
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
712
- text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
713
- transformer_lora_layers: Dict[str, torch.nn.Module] = None,
714
- is_main_process: bool = True,
715
- weight_name: str = None,
716
- save_function: Callable = None,
717
- safe_serialization: bool = True,
718
- ):
719
- r"""
720
- Save the LoRA parameters corresponding to the UNet and text encoder.
721
-
722
- Arguments:
723
- save_directory (`str` or `os.PathLike`):
724
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
725
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
726
- State dict of the LoRA layers corresponding to the `unet`.
727
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
728
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
729
- encoder LoRA state dict because it comes from 🤗 Transformers.
730
- is_main_process (`bool`, *optional*, defaults to `True`):
731
- Whether the process calling this is the main process or not. Useful during distributed training and you
732
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
733
- process to avoid race conditions.
734
- save_function (`Callable`):
735
- The function to use to save the state dictionary. Useful during distributed training when you need to
736
- replace `torch.save` with another method. Can be configured with the environment variable
737
- `DIFFUSERS_SAVE_MODE`.
738
- safe_serialization (`bool`, *optional*, defaults to `True`):
739
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
740
- """
741
- state_dict = {}
742
-
743
- def pack_weights(layers, prefix):
744
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
745
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
746
- return layers_state_dict
747
-
748
- if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
749
- raise ValueError(
750
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
751
- )
752
-
753
- if unet_lora_layers:
754
- state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
755
-
756
- if text_encoder_lora_layers:
757
- state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
758
-
759
- if transformer_lora_layers:
760
- state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
761
-
762
- # Save the model
763
- cls.write_lora_layers(
764
- state_dict=state_dict,
765
- save_directory=save_directory,
766
- is_main_process=is_main_process,
767
- weight_name=weight_name,
768
- save_function=save_function,
769
- safe_serialization=safe_serialization,
770
- )
771
-
772
- @staticmethod
773
- def write_lora_layers(
774
- state_dict: Dict[str, torch.Tensor],
775
- save_directory: str,
776
- is_main_process: bool,
777
- weight_name: str,
778
- save_function: Callable,
779
- safe_serialization: bool,
780
- ):
781
- if os.path.isfile(save_directory):
782
- logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
783
- return
784
-
785
- if save_function is None:
786
- if safe_serialization:
787
-
788
- def save_function(weights, filename):
789
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
790
-
791
- else:
792
- save_function = torch.save
793
-
794
- os.makedirs(save_directory, exist_ok=True)
795
-
796
- if weight_name is None:
797
- if safe_serialization:
798
- weight_name = LORA_WEIGHT_NAME_SAFE
799
- else:
800
- weight_name = LORA_WEIGHT_NAME
801
-
802
- save_path = Path(save_directory, weight_name).as_posix()
803
- save_function(state_dict, save_path)
804
- logger.info(f"Model weights saved in {save_path}")
805
-
806
- def unload_lora_weights(self):
807
- """
808
- Unloads the LoRA parameters.
809
-
810
- Examples:
811
-
812
- ```python
813
- >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
814
- >>> pipeline.unload_lora_weights()
815
- >>> ...
816
- ```
817
- """
818
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
819
-
820
- if not USE_PEFT_BACKEND:
821
- if version.parse(__version__) > version.parse("0.23"):
822
- logger.warning(
823
- "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
824
- "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
825
- )
826
-
827
- for _, module in unet.named_modules():
828
- if hasattr(module, "set_lora_layer"):
829
- module.set_lora_layer(None)
830
- else:
831
- recurse_remove_peft_layers(unet)
832
- if hasattr(unet, "peft_config"):
833
- del unet.peft_config
834
-
835
- # Safe to call the following regardless of LoRA.
836
- self._remove_text_encoder_monkey_patch()
837
-
838
- def fuse_lora(
839
- self,
840
- fuse_unet: bool = True,
841
- fuse_text_encoder: bool = True,
842
- lora_scale: float = 1.0,
843
- safe_fusing: bool = False,
844
- adapter_names: Optional[List[str]] = None,
845
- ):
846
- r"""
847
- Fuses the LoRA parameters into the original parameters of the corresponding blocks.
848
-
849
- <Tip warning={true}>
850
-
851
- This is an experimental API.
852
-
853
- </Tip>
854
-
855
- Args:
856
- fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
857
- fuse_text_encoder (`bool`, defaults to `True`):
858
- Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
859
- LoRA parameters then it won't have any effect.
860
- lora_scale (`float`, defaults to 1.0):
861
- Controls how much to influence the outputs with the LoRA parameters.
862
- safe_fusing (`bool`, defaults to `False`):
863
- Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
864
- adapter_names (`List[str]`, *optional*):
865
- Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
866
-
867
- Example:
868
-
869
- ```py
870
- from diffusers import DiffusionPipeline
871
- import torch
872
-
873
- pipeline = DiffusionPipeline.from_pretrained(
874
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
875
- ).to("cuda")
876
- pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
877
- pipeline.fuse_lora(lora_scale=0.7)
878
- ```
879
- """
880
- from peft.tuners.tuners_utils import BaseTunerLayer
881
-
882
- if fuse_unet or fuse_text_encoder:
883
- self.num_fused_loras += 1
884
- if self.num_fused_loras > 1:
885
- logger.warning(
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.",
887
- )
888
-
889
- if fuse_unet:
890
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
891
- unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
892
-
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}
895
-
896
- for module in text_encoder.modules():
897
- if isinstance(module, BaseTunerLayer):
898
- if lora_scale != 1.0:
899
- module.scale_layer(lora_scale)
900
-
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
- )
911
-
912
- module.merge(**merge_kwargs)
913
-
914
- if fuse_text_encoder:
915
- if hasattr(self, "text_encoder"):
916
- fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
917
- if hasattr(self, "text_encoder_2"):
918
- fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
919
-
920
- def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
921
- r"""
922
- Reverses the effect of
923
- [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
924
-
925
- <Tip warning={true}>
926
-
927
- This is an experimental API.
928
-
929
- </Tip>
930
-
931
- Args:
932
- unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
933
- unfuse_text_encoder (`bool`, defaults to `True`):
934
- Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
935
- LoRA parameters then it won't have any effect.
936
- """
937
- from peft.tuners.tuners_utils import BaseTunerLayer
938
-
939
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
940
- if unfuse_unet:
941
- for module in unet.modules():
942
- if isinstance(module, BaseTunerLayer):
943
- module.unmerge()
944
-
945
- def unfuse_text_encoder_lora(text_encoder):
946
- for module in text_encoder.modules():
947
- if isinstance(module, BaseTunerLayer):
948
- module.unmerge()
949
-
950
- if unfuse_text_encoder:
951
- if hasattr(self, "text_encoder"):
952
- unfuse_text_encoder_lora(self.text_encoder)
953
- if hasattr(self, "text_encoder_2"):
954
- unfuse_text_encoder_lora(self.text_encoder_2)
955
-
956
- self.num_fused_loras -= 1
957
-
958
- def set_adapters_for_text_encoder(
959
- self,
960
- adapter_names: Union[List[str], str],
961
- text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
962
- text_encoder_weights: List[float] = None,
963
- ):
964
- """
965
- Sets the adapter layers for the text encoder.
966
-
967
- Args:
968
- adapter_names (`List[str]` or `str`):
969
- The names of the adapters to use.
970
- text_encoder (`torch.nn.Module`, *optional*):
971
- The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
972
- attribute.
973
- text_encoder_weights (`List[float]`, *optional*):
974
- The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
975
- """
976
- if not USE_PEFT_BACKEND:
977
- raise ValueError("PEFT backend is required for this method.")
978
-
979
- def process_weights(adapter_names, weights):
980
- if weights is None:
981
- weights = [1.0] * len(adapter_names)
982
- elif isinstance(weights, float):
983
- weights = [weights]
984
-
985
- if len(adapter_names) != len(weights):
986
- raise ValueError(
987
- f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
988
- )
989
- return weights
990
-
991
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
992
- text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
993
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
994
- if text_encoder is None:
995
- raise ValueError(
996
- "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
997
- )
998
- set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
999
-
1000
- def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1001
- """
1002
- Disables the LoRA layers for the text encoder.
1003
-
1004
- Args:
1005
- text_encoder (`torch.nn.Module`, *optional*):
1006
- The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1007
- `text_encoder` attribute.
1008
- """
1009
- if not USE_PEFT_BACKEND:
1010
- raise ValueError("PEFT backend is required for this method.")
1011
-
1012
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
1013
- if text_encoder is None:
1014
- raise ValueError("Text Encoder not found.")
1015
- set_adapter_layers(text_encoder, enabled=False)
1016
-
1017
- def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1018
- """
1019
- Enables the LoRA layers for the text encoder.
1020
-
1021
- Args:
1022
- text_encoder (`torch.nn.Module`, *optional*):
1023
- The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1024
- attribute.
1025
- """
1026
- if not USE_PEFT_BACKEND:
1027
- raise ValueError("PEFT backend is required for this method.")
1028
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
1029
- if text_encoder is None:
1030
- raise ValueError("Text Encoder not found.")
1031
- set_adapter_layers(self.text_encoder, enabled=True)
1032
-
1033
- def set_adapters(
1034
- self,
1035
- adapter_names: Union[List[str], str],
1036
- adapter_weights: Optional[List[float]] = None,
1037
- ):
1038
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1039
- # Handle the UNET
1040
- unet.set_adapters(adapter_names, adapter_weights)
1041
-
1042
- # Handle the Text Encoder
1043
- if hasattr(self, "text_encoder"):
1044
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
1045
- if hasattr(self, "text_encoder_2"):
1046
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
1047
-
1048
- def disable_lora(self):
1049
- if not USE_PEFT_BACKEND:
1050
- raise ValueError("PEFT backend is required for this method.")
1051
-
1052
- # Disable unet adapters
1053
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1054
- unet.disable_lora()
1055
-
1056
- # Disable text encoder adapters
1057
- if hasattr(self, "text_encoder"):
1058
- self.disable_lora_for_text_encoder(self.text_encoder)
1059
- if hasattr(self, "text_encoder_2"):
1060
- self.disable_lora_for_text_encoder(self.text_encoder_2)
1061
-
1062
- def enable_lora(self):
1063
- if not USE_PEFT_BACKEND:
1064
- raise ValueError("PEFT backend is required for this method.")
1065
-
1066
- # Enable unet adapters
1067
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1068
- unet.enable_lora()
1069
-
1070
- # Enable text encoder adapters
1071
- if hasattr(self, "text_encoder"):
1072
- self.enable_lora_for_text_encoder(self.text_encoder)
1073
- if hasattr(self, "text_encoder_2"):
1074
- self.enable_lora_for_text_encoder(self.text_encoder_2)
1075
-
1076
- def delete_adapters(self, adapter_names: Union[List[str], str]):
1077
- """
1078
- Args:
1079
- Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1080
- adapter_names (`Union[List[str], str]`):
1081
- The names of the adapter to delete. Can be a single string or a list of strings
1082
- """
1083
- if not USE_PEFT_BACKEND:
1084
- raise ValueError("PEFT backend is required for this method.")
1085
-
1086
- if isinstance(adapter_names, str):
1087
- adapter_names = [adapter_names]
1088
-
1089
- # Delete unet adapters
1090
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1091
- unet.delete_adapters(adapter_names)
1092
-
1093
- for adapter_name in adapter_names:
1094
- # Delete text encoder adapters
1095
- if hasattr(self, "text_encoder"):
1096
- delete_adapter_layers(self.text_encoder, adapter_name)
1097
- if hasattr(self, "text_encoder_2"):
1098
- delete_adapter_layers(self.text_encoder_2, adapter_name)
1099
-
1100
- def get_active_adapters(self) -> List[str]:
1101
- """
1102
- Gets the list of the current active adapters.
1103
-
1104
- Example:
1105
-
1106
- ```python
1107
- from diffusers import DiffusionPipeline
1108
-
1109
- pipeline = DiffusionPipeline.from_pretrained(
1110
- "stabilityai/stable-diffusion-xl-base-1.0",
1111
- ).to("cuda")
1112
- pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1113
- pipeline.get_active_adapters()
1114
- ```
1115
- """
1116
- if not USE_PEFT_BACKEND:
1117
- raise ValueError(
1118
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1119
- )
1120
-
1121
- from peft.tuners.tuners_utils import BaseTunerLayer
1122
-
1123
- active_adapters = []
1124
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1125
- for module in unet.modules():
1126
- if isinstance(module, BaseTunerLayer):
1127
- active_adapters = module.active_adapters
1128
- break
1129
-
1130
- return active_adapters
1131
-
1132
- def get_list_adapters(self) -> Dict[str, List[str]]:
1133
- """
1134
- Gets the current list of all available adapters in the pipeline.
1135
- """
1136
- if not USE_PEFT_BACKEND:
1137
- raise ValueError(
1138
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1139
- )
1140
-
1141
- set_adapters = {}
1142
-
1143
- if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1144
- set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1145
-
1146
- if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1147
- set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1148
-
1149
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1150
- if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1151
- set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1152
-
1153
- return set_adapters
1154
-
1155
- def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1156
- """
1157
- Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1158
- you want to load multiple adapters and free some GPU memory.
1159
-
1160
- Args:
1161
- adapter_names (`List[str]`):
1162
- List of adapters to send device to.
1163
- device (`Union[torch.device, str, int]`):
1164
- Device to send the adapters to. Can be either a torch device, a str or an integer.
1165
- """
1166
- if not USE_PEFT_BACKEND:
1167
- raise ValueError("PEFT backend is required for this method.")
1168
-
1169
- from peft.tuners.tuners_utils import BaseTunerLayer
1170
-
1171
- # Handle the UNET
1172
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1173
- for unet_module in unet.modules():
1174
- if isinstance(unet_module, BaseTunerLayer):
1175
- for adapter_name in adapter_names:
1176
- unet_module.lora_A[adapter_name].to(device)
1177
- unet_module.lora_B[adapter_name].to(device)
1178
-
1179
- # Handle the text encoder
1180
- modules_to_process = []
1181
- if hasattr(self, "text_encoder"):
1182
- modules_to_process.append(self.text_encoder)
1183
-
1184
- if hasattr(self, "text_encoder_2"):
1185
- modules_to_process.append(self.text_encoder_2)
1186
-
1187
- for text_encoder in modules_to_process:
1188
- # loop over submodules
1189
- for text_encoder_module in text_encoder.modules():
1190
- if isinstance(text_encoder_module, BaseTunerLayer):
1191
- for adapter_name in adapter_names:
1192
- text_encoder_module.lora_A[adapter_name].to(device)
1193
- text_encoder_module.lora_B[adapter_name].to(device)
1194
-
1195
-
1196
- class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1197
- """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1198
-
1199
- # Override to properly handle the loading and unloading of the additional text encoder.
1200
- def load_lora_weights(
1201
- self,
1202
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1203
- adapter_name: Optional[str] = None,
1204
- **kwargs,
1205
- ):
1206
- """
1207
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1208
- `self.text_encoder`.
1209
-
1210
- All kwargs are forwarded to `self.lora_state_dict`.
1211
-
1212
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1213
-
1214
- See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1215
- `self.unet`.
1216
-
1217
- See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1218
- into `self.text_encoder`.
1219
-
1220
- Parameters:
1221
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1222
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1223
- adapter_name (`str`, *optional*):
1224
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1225
- `default_{i}` where i is the total number of adapters being loaded.
1226
- kwargs (`dict`, *optional*):
1227
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1228
- """
1229
- if not USE_PEFT_BACKEND:
1230
- raise ValueError("PEFT backend is required for this method.")
1231
-
1232
- # We could have accessed the unet config from `lora_state_dict()` too. We pass
1233
- # it here explicitly to be able to tell that it's coming from an SDXL
1234
- # pipeline.
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
-
1240
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1241
- state_dict, network_alphas = self.lora_state_dict(
1242
- pretrained_model_name_or_path_or_dict,
1243
- unet_config=self.unet.config,
1244
- **kwargs,
1245
- )
1246
- is_correct_format = all("lora" in key for key in state_dict.keys())
1247
- if not is_correct_format:
1248
- raise ValueError("Invalid LoRA checkpoint.")
1249
-
1250
- self.load_lora_into_unet(
1251
- state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1252
- )
1253
- text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1254
- if len(text_encoder_state_dict) > 0:
1255
- self.load_lora_into_text_encoder(
1256
- text_encoder_state_dict,
1257
- network_alphas=network_alphas,
1258
- text_encoder=self.text_encoder,
1259
- prefix="text_encoder",
1260
- lora_scale=self.lora_scale,
1261
- adapter_name=adapter_name,
1262
- _pipeline=self,
1263
- )
1264
-
1265
- text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1266
- if len(text_encoder_2_state_dict) > 0:
1267
- self.load_lora_into_text_encoder(
1268
- text_encoder_2_state_dict,
1269
- network_alphas=network_alphas,
1270
- text_encoder=self.text_encoder_2,
1271
- prefix="text_encoder_2",
1272
- lora_scale=self.lora_scale,
1273
- adapter_name=adapter_name,
1274
- _pipeline=self,
1275
- )
1276
-
1277
- @classmethod
1278
- def save_lora_weights(
1279
- cls,
1280
- save_directory: Union[str, os.PathLike],
1281
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1282
- text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1283
- text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1284
- is_main_process: bool = True,
1285
- weight_name: str = None,
1286
- save_function: Callable = None,
1287
- safe_serialization: bool = True,
1288
- ):
1289
- r"""
1290
- Save the LoRA parameters corresponding to the UNet and text encoder.
1291
-
1292
- Arguments:
1293
- save_directory (`str` or `os.PathLike`):
1294
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
1295
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1296
- State dict of the LoRA layers corresponding to the `unet`.
1297
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1298
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1299
- encoder LoRA state dict because it comes from 🤗 Transformers.
1300
- is_main_process (`bool`, *optional*, defaults to `True`):
1301
- Whether the process calling this is the main process or not. Useful during distributed training and you
1302
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1303
- process to avoid race conditions.
1304
- save_function (`Callable`):
1305
- The function to use to save the state dictionary. Useful during distributed training when you need to
1306
- replace `torch.save` with another method. Can be configured with the environment variable
1307
- `DIFFUSERS_SAVE_MODE`.
1308
- safe_serialization (`bool`, *optional*, defaults to `True`):
1309
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1310
- """
1311
- state_dict = {}
1312
-
1313
- def pack_weights(layers, prefix):
1314
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1315
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1316
- return layers_state_dict
1317
-
1318
- if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1319
- raise ValueError(
1320
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1321
- )
1322
-
1323
- if unet_lora_layers:
1324
- state_dict.update(pack_weights(unet_lora_layers, "unet"))
1325
-
1326
- if text_encoder_lora_layers and text_encoder_2_lora_layers:
1327
- state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1328
- state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1329
-
1330
- cls.write_lora_layers(
1331
- state_dict=state_dict,
1332
- save_directory=save_directory,
1333
- is_main_process=is_main_process,
1334
- weight_name=weight_name,
1335
- save_function=save_function,
1336
- safe_serialization=safe_serialization,
1337
- )
1338
-
1339
- def _remove_text_encoder_monkey_patch(self):
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