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
@@ -0,0 +1,900 @@
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
+
15
+ import copy
16
+ import inspect
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Callable, Dict, List, Optional, Union
20
+
21
+ import safetensors
22
+ import torch
23
+ import torch.nn as nn
24
+ from huggingface_hub import model_info
25
+ from huggingface_hub.constants import HF_HUB_OFFLINE
26
+
27
+ from ..models.modeling_utils import ModelMixin, load_state_dict
28
+ from ..utils import (
29
+ USE_PEFT_BACKEND,
30
+ _get_model_file,
31
+ convert_state_dict_to_diffusers,
32
+ convert_state_dict_to_peft,
33
+ delete_adapter_layers,
34
+ deprecate,
35
+ get_adapter_name,
36
+ get_peft_kwargs,
37
+ is_accelerate_available,
38
+ is_peft_available,
39
+ is_peft_version,
40
+ is_transformers_available,
41
+ is_transformers_version,
42
+ logging,
43
+ recurse_remove_peft_layers,
44
+ scale_lora_layers,
45
+ set_adapter_layers,
46
+ set_weights_and_activate_adapters,
47
+ )
48
+
49
+
50
+ if is_transformers_available():
51
+ from transformers import PreTrainedModel
52
+
53
+ from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
54
+
55
+ if is_peft_available():
56
+ from peft.tuners.tuners_utils import BaseTunerLayer
57
+
58
+ if is_accelerate_available():
59
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
64
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
65
+
66
+
67
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
68
+ """
69
+ Fuses LoRAs for the text encoder.
70
+
71
+ Args:
72
+ text_encoder (`torch.nn.Module`):
73
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
74
+ attribute.
75
+ lora_scale (`float`, defaults to 1.0):
76
+ Controls how much to influence the outputs with the LoRA parameters.
77
+ safe_fusing (`bool`, defaults to `False`):
78
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
79
+ adapter_names (`List[str]` or `str`):
80
+ The names of the adapters to use.
81
+ """
82
+ merge_kwargs = {"safe_merge": safe_fusing}
83
+
84
+ for module in text_encoder.modules():
85
+ if isinstance(module, BaseTunerLayer):
86
+ if lora_scale != 1.0:
87
+ module.scale_layer(lora_scale)
88
+
89
+ # For BC with previous PEFT versions, we need to check the signature
90
+ # of the `merge` method to see if it supports the `adapter_names` argument.
91
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
92
+ if "adapter_names" in supported_merge_kwargs:
93
+ merge_kwargs["adapter_names"] = adapter_names
94
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
95
+ raise ValueError(
96
+ "The `adapter_names` argument is not supported with your PEFT version. "
97
+ "Please upgrade to the latest version of PEFT. `pip install -U peft`"
98
+ )
99
+
100
+ module.merge(**merge_kwargs)
101
+
102
+
103
+ def unfuse_text_encoder_lora(text_encoder):
104
+ """
105
+ Unfuses LoRAs for the text encoder.
106
+
107
+ Args:
108
+ text_encoder (`torch.nn.Module`):
109
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
110
+ attribute.
111
+ """
112
+ for module in text_encoder.modules():
113
+ if isinstance(module, BaseTunerLayer):
114
+ module.unmerge()
115
+
116
+
117
+ def set_adapters_for_text_encoder(
118
+ adapter_names: Union[List[str], str],
119
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
120
+ text_encoder_weights: Optional[Union[float, List[float], List[None]]] = None,
121
+ ):
122
+ """
123
+ Sets the adapter layers for the text encoder.
124
+
125
+ Args:
126
+ adapter_names (`List[str]` or `str`):
127
+ The names of the adapters to use.
128
+ text_encoder (`torch.nn.Module`, *optional*):
129
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
130
+ attribute.
131
+ text_encoder_weights (`List[float]`, *optional*):
132
+ The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
133
+ """
134
+ if text_encoder is None:
135
+ raise ValueError(
136
+ "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
137
+ )
138
+
139
+ def process_weights(adapter_names, weights):
140
+ # Expand weights into a list, one entry per adapter
141
+ # e.g. for 2 adapters: 7 -> [7,7] ; [3, None] -> [3, None]
142
+ if not isinstance(weights, list):
143
+ weights = [weights] * len(adapter_names)
144
+
145
+ if len(adapter_names) != len(weights):
146
+ raise ValueError(
147
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
148
+ )
149
+
150
+ # Set None values to default of 1.0
151
+ # e.g. [7,7] -> [7,7] ; [3, None] -> [3,1]
152
+ weights = [w if w is not None else 1.0 for w in weights]
153
+
154
+ return weights
155
+
156
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
157
+ text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
158
+ set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
159
+
160
+
161
+ def disable_lora_for_text_encoder(text_encoder: Optional["PreTrainedModel"] = None):
162
+ """
163
+ Disables the LoRA layers for the text encoder.
164
+
165
+ Args:
166
+ text_encoder (`torch.nn.Module`, *optional*):
167
+ The text encoder module to disable the LoRA layers for. If `None`, it will try to get the `text_encoder`
168
+ attribute.
169
+ """
170
+ if text_encoder is None:
171
+ raise ValueError("Text Encoder not found.")
172
+ set_adapter_layers(text_encoder, enabled=False)
173
+
174
+
175
+ def enable_lora_for_text_encoder(text_encoder: Optional["PreTrainedModel"] = None):
176
+ """
177
+ Enables the LoRA layers for the text encoder.
178
+
179
+ Args:
180
+ text_encoder (`torch.nn.Module`, *optional*):
181
+ The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
182
+ attribute.
183
+ """
184
+ if text_encoder is None:
185
+ raise ValueError("Text Encoder not found.")
186
+ set_adapter_layers(text_encoder, enabled=True)
187
+
188
+
189
+ def _remove_text_encoder_monkey_patch(text_encoder):
190
+ recurse_remove_peft_layers(text_encoder)
191
+ if getattr(text_encoder, "peft_config", None) is not None:
192
+ del text_encoder.peft_config
193
+ text_encoder._hf_peft_config_loaded = None
194
+
195
+
196
+ def _fetch_state_dict(
197
+ pretrained_model_name_or_path_or_dict,
198
+ weight_name,
199
+ use_safetensors,
200
+ local_files_only,
201
+ cache_dir,
202
+ force_download,
203
+ proxies,
204
+ token,
205
+ revision,
206
+ subfolder,
207
+ user_agent,
208
+ allow_pickle,
209
+ ):
210
+ model_file = None
211
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
212
+ # Let's first try to load .safetensors weights
213
+ if (use_safetensors and weight_name is None) or (
214
+ weight_name is not None and weight_name.endswith(".safetensors")
215
+ ):
216
+ try:
217
+ # Here we're relaxing the loading check to enable more Inference API
218
+ # friendliness where sometimes, it's not at all possible to automatically
219
+ # determine `weight_name`.
220
+ if weight_name is None:
221
+ weight_name = _best_guess_weight_name(
222
+ pretrained_model_name_or_path_or_dict,
223
+ file_extension=".safetensors",
224
+ local_files_only=local_files_only,
225
+ )
226
+ model_file = _get_model_file(
227
+ pretrained_model_name_or_path_or_dict,
228
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
229
+ cache_dir=cache_dir,
230
+ force_download=force_download,
231
+ proxies=proxies,
232
+ local_files_only=local_files_only,
233
+ token=token,
234
+ revision=revision,
235
+ subfolder=subfolder,
236
+ user_agent=user_agent,
237
+ )
238
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
239
+ except (IOError, safetensors.SafetensorError) as e:
240
+ if not allow_pickle:
241
+ raise e
242
+ # try loading non-safetensors weights
243
+ model_file = None
244
+ pass
245
+
246
+ if model_file is None:
247
+ if weight_name is None:
248
+ weight_name = _best_guess_weight_name(
249
+ pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
250
+ )
251
+ model_file = _get_model_file(
252
+ pretrained_model_name_or_path_or_dict,
253
+ weights_name=weight_name or LORA_WEIGHT_NAME,
254
+ cache_dir=cache_dir,
255
+ force_download=force_download,
256
+ proxies=proxies,
257
+ local_files_only=local_files_only,
258
+ token=token,
259
+ revision=revision,
260
+ subfolder=subfolder,
261
+ user_agent=user_agent,
262
+ )
263
+ state_dict = load_state_dict(model_file)
264
+ else:
265
+ state_dict = pretrained_model_name_or_path_or_dict
266
+
267
+ return state_dict
268
+
269
+
270
+ def _best_guess_weight_name(
271
+ pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
272
+ ):
273
+ if local_files_only or HF_HUB_OFFLINE:
274
+ raise ValueError("When using the offline mode, you must specify a `weight_name`.")
275
+
276
+ targeted_files = []
277
+
278
+ if os.path.isfile(pretrained_model_name_or_path_or_dict):
279
+ return
280
+ elif os.path.isdir(pretrained_model_name_or_path_or_dict):
281
+ targeted_files = [f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)]
282
+ else:
283
+ files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
284
+ targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
285
+ if len(targeted_files) == 0:
286
+ return
287
+
288
+ # "scheduler" does not correspond to a LoRA checkpoint.
289
+ # "optimizer" does not correspond to a LoRA checkpoint
290
+ # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
291
+ unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
292
+ targeted_files = list(
293
+ filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
294
+ )
295
+
296
+ if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
297
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
298
+ elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
299
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
300
+
301
+ if len(targeted_files) > 1:
302
+ raise ValueError(
303
+ 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}."
304
+ )
305
+ weight_name = targeted_files[0]
306
+ return weight_name
307
+
308
+
309
+ def _load_lora_into_text_encoder(
310
+ state_dict,
311
+ network_alphas,
312
+ text_encoder,
313
+ prefix=None,
314
+ lora_scale=1.0,
315
+ text_encoder_name="text_encoder",
316
+ adapter_name=None,
317
+ _pipeline=None,
318
+ low_cpu_mem_usage=False,
319
+ ):
320
+ if not USE_PEFT_BACKEND:
321
+ raise ValueError("PEFT backend is required for this method.")
322
+
323
+ peft_kwargs = {}
324
+ if low_cpu_mem_usage:
325
+ if not is_peft_version(">=", "0.13.1"):
326
+ raise ValueError(
327
+ "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`."
328
+ )
329
+ if not is_transformers_version(">", "4.45.2"):
330
+ # Note from sayakpaul: It's not in `transformers` stable yet.
331
+ # https://github.com/huggingface/transformers/pull/33725/
332
+ raise ValueError(
333
+ "`low_cpu_mem_usage=True` is not compatible with this `transformers` version. Please update it with `pip install -U transformers`."
334
+ )
335
+ peft_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
336
+
337
+ from peft import LoraConfig
338
+
339
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
340
+ # then the `state_dict` keys should have `unet_name` and/or `text_encoder_name` as
341
+ # their prefixes.
342
+ keys = list(state_dict.keys())
343
+ prefix = text_encoder_name if prefix is None else prefix
344
+
345
+ # Safe prefix to check with.
346
+ if any(text_encoder_name in key for key in keys):
347
+ # Load the layers corresponding to text encoder and make necessary adjustments.
348
+ text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
349
+ text_encoder_lora_state_dict = {
350
+ k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
351
+ }
352
+
353
+ if len(text_encoder_lora_state_dict) > 0:
354
+ logger.info(f"Loading {prefix}.")
355
+ rank = {}
356
+ text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
357
+
358
+ # convert state dict
359
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
360
+
361
+ for name, _ in text_encoder_attn_modules(text_encoder):
362
+ for module in ("out_proj", "q_proj", "k_proj", "v_proj"):
363
+ rank_key = f"{name}.{module}.lora_B.weight"
364
+ if rank_key not in text_encoder_lora_state_dict:
365
+ continue
366
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
367
+
368
+ for name, _ in text_encoder_mlp_modules(text_encoder):
369
+ for module in ("fc1", "fc2"):
370
+ rank_key = f"{name}.{module}.lora_B.weight"
371
+ if rank_key not in text_encoder_lora_state_dict:
372
+ continue
373
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
374
+
375
+ if network_alphas is not None:
376
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix]
377
+ network_alphas = {k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys}
378
+
379
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
380
+
381
+ if "use_dora" in lora_config_kwargs:
382
+ if lora_config_kwargs["use_dora"]:
383
+ if is_peft_version("<", "0.9.0"):
384
+ raise ValueError(
385
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
386
+ )
387
+ else:
388
+ if is_peft_version("<", "0.9.0"):
389
+ lora_config_kwargs.pop("use_dora")
390
+
391
+ if "lora_bias" in lora_config_kwargs:
392
+ if lora_config_kwargs["lora_bias"]:
393
+ if is_peft_version("<=", "0.13.2"):
394
+ raise ValueError(
395
+ "You need `peft` 0.14.0 at least to use `bias` in LoRAs. Please upgrade your installation of `peft`."
396
+ )
397
+ else:
398
+ if is_peft_version("<=", "0.13.2"):
399
+ lora_config_kwargs.pop("lora_bias")
400
+
401
+ lora_config = LoraConfig(**lora_config_kwargs)
402
+
403
+ # adapter_name
404
+ if adapter_name is None:
405
+ adapter_name = get_adapter_name(text_encoder)
406
+
407
+ is_model_cpu_offload, is_sequential_cpu_offload = _func_optionally_disable_offloading(_pipeline)
408
+
409
+ # inject LoRA layers and load the state dict
410
+ # in transformers we automatically check whether the adapter name is already in use or not
411
+ text_encoder.load_adapter(
412
+ adapter_name=adapter_name,
413
+ adapter_state_dict=text_encoder_lora_state_dict,
414
+ peft_config=lora_config,
415
+ **peft_kwargs,
416
+ )
417
+
418
+ # scale LoRA layers with `lora_scale`
419
+ scale_lora_layers(text_encoder, weight=lora_scale)
420
+
421
+ text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
422
+
423
+ # Offload back.
424
+ if is_model_cpu_offload:
425
+ _pipeline.enable_model_cpu_offload()
426
+ elif is_sequential_cpu_offload:
427
+ _pipeline.enable_sequential_cpu_offload()
428
+ # Unsafe code />
429
+
430
+
431
+ def _func_optionally_disable_offloading(_pipeline):
432
+ is_model_cpu_offload = False
433
+ is_sequential_cpu_offload = False
434
+
435
+ if _pipeline is not None and _pipeline.hf_device_map is None:
436
+ for _, component in _pipeline.components.items():
437
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
438
+ if not is_model_cpu_offload:
439
+ is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
440
+ if not is_sequential_cpu_offload:
441
+ is_sequential_cpu_offload = (
442
+ isinstance(component._hf_hook, AlignDevicesHook)
443
+ or hasattr(component._hf_hook, "hooks")
444
+ and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
445
+ )
446
+
447
+ logger.info(
448
+ "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."
449
+ )
450
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
451
+
452
+ return (is_model_cpu_offload, is_sequential_cpu_offload)
453
+
454
+
455
+ class LoraBaseMixin:
456
+ """Utility class for handling LoRAs."""
457
+
458
+ _lora_loadable_modules = []
459
+ num_fused_loras = 0
460
+
461
+ def load_lora_weights(self, **kwargs):
462
+ raise NotImplementedError("`load_lora_weights()` is not implemented.")
463
+
464
+ @classmethod
465
+ def save_lora_weights(cls, **kwargs):
466
+ raise NotImplementedError("`save_lora_weights()` not implemented.")
467
+
468
+ @classmethod
469
+ def lora_state_dict(cls, **kwargs):
470
+ raise NotImplementedError("`lora_state_dict()` is not implemented.")
471
+
472
+ @classmethod
473
+ def _optionally_disable_offloading(cls, _pipeline):
474
+ """
475
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
476
+
477
+ Args:
478
+ _pipeline (`DiffusionPipeline`):
479
+ The pipeline to disable offloading for.
480
+
481
+ Returns:
482
+ tuple:
483
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
484
+ """
485
+ return _func_optionally_disable_offloading(_pipeline=_pipeline)
486
+
487
+ @classmethod
488
+ def _fetch_state_dict(cls, *args, **kwargs):
489
+ deprecation_message = f"Using the `_fetch_state_dict()` method from {cls} has been deprecated and will be removed in a future version. Please use `from diffusers.loaders.lora_base import _fetch_state_dict`."
490
+ deprecate("_fetch_state_dict", "0.35.0", deprecation_message)
491
+ return _fetch_state_dict(*args, **kwargs)
492
+
493
+ @classmethod
494
+ def _best_guess_weight_name(cls, *args, **kwargs):
495
+ deprecation_message = f"Using the `_best_guess_weight_name()` method from {cls} has been deprecated and will be removed in a future version. Please use `from diffusers.loaders.lora_base import _best_guess_weight_name`."
496
+ deprecate("_best_guess_weight_name", "0.35.0", deprecation_message)
497
+ return _best_guess_weight_name(*args, **kwargs)
498
+
499
+ def unload_lora_weights(self):
500
+ """
501
+ Unloads the LoRA parameters.
502
+
503
+ Examples:
504
+
505
+ ```python
506
+ >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
507
+ >>> pipeline.unload_lora_weights()
508
+ >>> ...
509
+ ```
510
+ """
511
+ if not USE_PEFT_BACKEND:
512
+ raise ValueError("PEFT backend is required for this method.")
513
+
514
+ for component in self._lora_loadable_modules:
515
+ model = getattr(self, component, None)
516
+ if model is not None:
517
+ if issubclass(model.__class__, ModelMixin):
518
+ model.unload_lora()
519
+ elif issubclass(model.__class__, PreTrainedModel):
520
+ _remove_text_encoder_monkey_patch(model)
521
+
522
+ def fuse_lora(
523
+ self,
524
+ components: List[str] = [],
525
+ lora_scale: float = 1.0,
526
+ safe_fusing: bool = False,
527
+ adapter_names: Optional[List[str]] = None,
528
+ **kwargs,
529
+ ):
530
+ r"""
531
+ Fuses the LoRA parameters into the original parameters of the corresponding blocks.
532
+
533
+ <Tip warning={true}>
534
+
535
+ This is an experimental API.
536
+
537
+ </Tip>
538
+
539
+ Args:
540
+ components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into.
541
+ lora_scale (`float`, defaults to 1.0):
542
+ Controls how much to influence the outputs with the LoRA parameters.
543
+ safe_fusing (`bool`, defaults to `False`):
544
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
545
+ adapter_names (`List[str]`, *optional*):
546
+ Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
547
+
548
+ Example:
549
+
550
+ ```py
551
+ from diffusers import DiffusionPipeline
552
+ import torch
553
+
554
+ pipeline = DiffusionPipeline.from_pretrained(
555
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
556
+ ).to("cuda")
557
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
558
+ pipeline.fuse_lora(lora_scale=0.7)
559
+ ```
560
+ """
561
+ if "fuse_unet" in kwargs:
562
+ depr_message = "Passing `fuse_unet` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_unet` will be removed in a future version."
563
+ deprecate(
564
+ "fuse_unet",
565
+ "1.0.0",
566
+ depr_message,
567
+ )
568
+ if "fuse_transformer" in kwargs:
569
+ depr_message = "Passing `fuse_transformer` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_transformer` will be removed in a future version."
570
+ deprecate(
571
+ "fuse_transformer",
572
+ "1.0.0",
573
+ depr_message,
574
+ )
575
+ if "fuse_text_encoder" in kwargs:
576
+ depr_message = "Passing `fuse_text_encoder` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_text_encoder` will be removed in a future version."
577
+ deprecate(
578
+ "fuse_text_encoder",
579
+ "1.0.0",
580
+ depr_message,
581
+ )
582
+
583
+ if len(components) == 0:
584
+ raise ValueError("`components` cannot be an empty list.")
585
+
586
+ for fuse_component in components:
587
+ if fuse_component not in self._lora_loadable_modules:
588
+ raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.")
589
+
590
+ model = getattr(self, fuse_component, None)
591
+ if model is not None:
592
+ # check if diffusers model
593
+ if issubclass(model.__class__, ModelMixin):
594
+ model.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
595
+ # handle transformers models.
596
+ if issubclass(model.__class__, PreTrainedModel):
597
+ fuse_text_encoder_lora(
598
+ model, lora_scale=lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names
599
+ )
600
+
601
+ self.num_fused_loras += 1
602
+
603
+ def unfuse_lora(self, components: List[str] = [], **kwargs):
604
+ r"""
605
+ Reverses the effect of
606
+ [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).
607
+
608
+ <Tip warning={true}>
609
+
610
+ This is an experimental API.
611
+
612
+ </Tip>
613
+
614
+ Args:
615
+ components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
616
+ unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
617
+ unfuse_text_encoder (`bool`, defaults to `True`):
618
+ Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
619
+ LoRA parameters then it won't have any effect.
620
+ """
621
+ if "unfuse_unet" in kwargs:
622
+ depr_message = "Passing `unfuse_unet` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_unet` will be removed in a future version."
623
+ deprecate(
624
+ "unfuse_unet",
625
+ "1.0.0",
626
+ depr_message,
627
+ )
628
+ if "unfuse_transformer" in kwargs:
629
+ depr_message = "Passing `unfuse_transformer` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_transformer` will be removed in a future version."
630
+ deprecate(
631
+ "unfuse_transformer",
632
+ "1.0.0",
633
+ depr_message,
634
+ )
635
+ if "unfuse_text_encoder" in kwargs:
636
+ depr_message = "Passing `unfuse_text_encoder` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_text_encoder` will be removed in a future version."
637
+ deprecate(
638
+ "unfuse_text_encoder",
639
+ "1.0.0",
640
+ depr_message,
641
+ )
642
+
643
+ if len(components) == 0:
644
+ raise ValueError("`components` cannot be an empty list.")
645
+
646
+ for fuse_component in components:
647
+ if fuse_component not in self._lora_loadable_modules:
648
+ raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.")
649
+
650
+ model = getattr(self, fuse_component, None)
651
+ if model is not None:
652
+ if issubclass(model.__class__, (ModelMixin, PreTrainedModel)):
653
+ for module in model.modules():
654
+ if isinstance(module, BaseTunerLayer):
655
+ module.unmerge()
656
+
657
+ self.num_fused_loras -= 1
658
+
659
+ def set_adapters(
660
+ self,
661
+ adapter_names: Union[List[str], str],
662
+ adapter_weights: Optional[Union[float, Dict, List[float], List[Dict]]] = None,
663
+ ):
664
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
665
+
666
+ adapter_weights = copy.deepcopy(adapter_weights)
667
+
668
+ # Expand weights into a list, one entry per adapter
669
+ if not isinstance(adapter_weights, list):
670
+ adapter_weights = [adapter_weights] * len(adapter_names)
671
+
672
+ if len(adapter_names) != len(adapter_weights):
673
+ raise ValueError(
674
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(adapter_weights)}"
675
+ )
676
+
677
+ list_adapters = self.get_list_adapters() # eg {"unet": ["adapter1", "adapter2"], "text_encoder": ["adapter2"]}
678
+ # eg ["adapter1", "adapter2"]
679
+ all_adapters = {adapter for adapters in list_adapters.values() for adapter in adapters}
680
+ missing_adapters = set(adapter_names) - all_adapters
681
+ if len(missing_adapters) > 0:
682
+ raise ValueError(
683
+ f"Adapter name(s) {missing_adapters} not in the list of present adapters: {all_adapters}."
684
+ )
685
+
686
+ # eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]}
687
+ invert_list_adapters = {
688
+ adapter: [part for part, adapters in list_adapters.items() if adapter in adapters]
689
+ for adapter in all_adapters
690
+ }
691
+
692
+ # Decompose weights into weights for denoiser and text encoders.
693
+ _component_adapter_weights = {}
694
+ for component in self._lora_loadable_modules:
695
+ model = getattr(self, component)
696
+
697
+ for adapter_name, weights in zip(adapter_names, adapter_weights):
698
+ if isinstance(weights, dict):
699
+ component_adapter_weights = weights.pop(component, None)
700
+
701
+ if component_adapter_weights is not None and not hasattr(self, component):
702
+ logger.warning(
703
+ f"Lora weight dict contains {component} weights but will be ignored because pipeline does not have {component}."
704
+ )
705
+
706
+ if component_adapter_weights is not None and component not in invert_list_adapters[adapter_name]:
707
+ logger.warning(
708
+ (
709
+ f"Lora weight dict for adapter '{adapter_name}' contains {component},"
710
+ f"but this will be ignored because {adapter_name} does not contain weights for {component}."
711
+ f"Valid parts for {adapter_name} are: {invert_list_adapters[adapter_name]}."
712
+ )
713
+ )
714
+
715
+ else:
716
+ component_adapter_weights = weights
717
+
718
+ _component_adapter_weights.setdefault(component, [])
719
+ _component_adapter_weights[component].append(component_adapter_weights)
720
+
721
+ if issubclass(model.__class__, ModelMixin):
722
+ model.set_adapters(adapter_names, _component_adapter_weights[component])
723
+ elif issubclass(model.__class__, PreTrainedModel):
724
+ set_adapters_for_text_encoder(adapter_names, model, _component_adapter_weights[component])
725
+
726
+ def disable_lora(self):
727
+ if not USE_PEFT_BACKEND:
728
+ raise ValueError("PEFT backend is required for this method.")
729
+
730
+ for component in self._lora_loadable_modules:
731
+ model = getattr(self, component, None)
732
+ if model is not None:
733
+ if issubclass(model.__class__, ModelMixin):
734
+ model.disable_lora()
735
+ elif issubclass(model.__class__, PreTrainedModel):
736
+ disable_lora_for_text_encoder(model)
737
+
738
+ def enable_lora(self):
739
+ if not USE_PEFT_BACKEND:
740
+ raise ValueError("PEFT backend is required for this method.")
741
+
742
+ for component in self._lora_loadable_modules:
743
+ model = getattr(self, component, None)
744
+ if model is not None:
745
+ if issubclass(model.__class__, ModelMixin):
746
+ model.enable_lora()
747
+ elif issubclass(model.__class__, PreTrainedModel):
748
+ enable_lora_for_text_encoder(model)
749
+
750
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
751
+ """
752
+ Args:
753
+ Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
754
+ adapter_names (`Union[List[str], str]`):
755
+ The names of the adapter to delete. Can be a single string or a list of strings
756
+ """
757
+ if not USE_PEFT_BACKEND:
758
+ raise ValueError("PEFT backend is required for this method.")
759
+
760
+ if isinstance(adapter_names, str):
761
+ adapter_names = [adapter_names]
762
+
763
+ for component in self._lora_loadable_modules:
764
+ model = getattr(self, component, None)
765
+ if model is not None:
766
+ if issubclass(model.__class__, ModelMixin):
767
+ model.delete_adapters(adapter_names)
768
+ elif issubclass(model.__class__, PreTrainedModel):
769
+ for adapter_name in adapter_names:
770
+ delete_adapter_layers(model, adapter_name)
771
+
772
+ def get_active_adapters(self) -> List[str]:
773
+ """
774
+ Gets the list of the current active adapters.
775
+
776
+ Example:
777
+
778
+ ```python
779
+ from diffusers import DiffusionPipeline
780
+
781
+ pipeline = DiffusionPipeline.from_pretrained(
782
+ "stabilityai/stable-diffusion-xl-base-1.0",
783
+ ).to("cuda")
784
+ pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
785
+ pipeline.get_active_adapters()
786
+ ```
787
+ """
788
+ if not USE_PEFT_BACKEND:
789
+ raise ValueError(
790
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
791
+ )
792
+
793
+ active_adapters = []
794
+
795
+ for component in self._lora_loadable_modules:
796
+ model = getattr(self, component, None)
797
+ if model is not None and issubclass(model.__class__, ModelMixin):
798
+ for module in model.modules():
799
+ if isinstance(module, BaseTunerLayer):
800
+ active_adapters = module.active_adapters
801
+ break
802
+
803
+ return active_adapters
804
+
805
+ def get_list_adapters(self) -> Dict[str, List[str]]:
806
+ """
807
+ Gets the current list of all available adapters in the pipeline.
808
+ """
809
+ if not USE_PEFT_BACKEND:
810
+ raise ValueError(
811
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
812
+ )
813
+
814
+ set_adapters = {}
815
+
816
+ for component in self._lora_loadable_modules:
817
+ model = getattr(self, component, None)
818
+ if (
819
+ model is not None
820
+ and issubclass(model.__class__, (ModelMixin, PreTrainedModel))
821
+ and hasattr(model, "peft_config")
822
+ ):
823
+ set_adapters[component] = list(model.peft_config.keys())
824
+
825
+ return set_adapters
826
+
827
+ def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
828
+ """
829
+ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
830
+ you want to load multiple adapters and free some GPU memory.
831
+
832
+ Args:
833
+ adapter_names (`List[str]`):
834
+ List of adapters to send device to.
835
+ device (`Union[torch.device, str, int]`):
836
+ Device to send the adapters to. Can be either a torch device, a str or an integer.
837
+ """
838
+ if not USE_PEFT_BACKEND:
839
+ raise ValueError("PEFT backend is required for this method.")
840
+
841
+ for component in self._lora_loadable_modules:
842
+ model = getattr(self, component, None)
843
+ if model is not None:
844
+ for module in model.modules():
845
+ if isinstance(module, BaseTunerLayer):
846
+ for adapter_name in adapter_names:
847
+ module.lora_A[adapter_name].to(device)
848
+ module.lora_B[adapter_name].to(device)
849
+ # this is a param, not a module, so device placement is not in-place -> re-assign
850
+ if hasattr(module, "lora_magnitude_vector") and module.lora_magnitude_vector is not None:
851
+ if adapter_name in module.lora_magnitude_vector:
852
+ module.lora_magnitude_vector[adapter_name] = module.lora_magnitude_vector[
853
+ adapter_name
854
+ ].to(device)
855
+
856
+ @staticmethod
857
+ def pack_weights(layers, prefix):
858
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
859
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
860
+ return layers_state_dict
861
+
862
+ @staticmethod
863
+ def write_lora_layers(
864
+ state_dict: Dict[str, torch.Tensor],
865
+ save_directory: str,
866
+ is_main_process: bool,
867
+ weight_name: str,
868
+ save_function: Callable,
869
+ safe_serialization: bool,
870
+ ):
871
+ if os.path.isfile(save_directory):
872
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
873
+ return
874
+
875
+ if save_function is None:
876
+ if safe_serialization:
877
+
878
+ def save_function(weights, filename):
879
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
880
+
881
+ else:
882
+ save_function = torch.save
883
+
884
+ os.makedirs(save_directory, exist_ok=True)
885
+
886
+ if weight_name is None:
887
+ if safe_serialization:
888
+ weight_name = LORA_WEIGHT_NAME_SAFE
889
+ else:
890
+ weight_name = LORA_WEIGHT_NAME
891
+
892
+ save_path = Path(save_directory, weight_name).as_posix()
893
+ save_function(state_dict, save_path)
894
+ logger.info(f"Model weights saved in {save_path}")
895
+
896
+ @property
897
+ def lora_scale(self) -> float:
898
+ # property function that returns the lora scale which can be set at run time by the pipeline.
899
+ # if _lora_scale has not been set, return 1
900
+ return self._lora_scale if hasattr(self, "_lora_scale") else 1.0