diffusers 0.23.1__py3-none-any.whl → 0.25.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (238) hide show
  1. diffusers/__init__.py +26 -2
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +13 -8
  4. diffusers/dependency_versions_check.py +0 -1
  5. diffusers/dependency_versions_table.py +5 -5
  6. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  7. diffusers/image_processor.py +463 -51
  8. diffusers/loaders/__init__.py +82 -0
  9. diffusers/loaders/ip_adapter.py +159 -0
  10. diffusers/loaders/lora.py +1553 -0
  11. diffusers/loaders/lora_conversion_utils.py +284 -0
  12. diffusers/loaders/single_file.py +637 -0
  13. diffusers/loaders/textual_inversion.py +455 -0
  14. diffusers/loaders/unet.py +828 -0
  15. diffusers/loaders/utils.py +59 -0
  16. diffusers/models/__init__.py +26 -9
  17. diffusers/models/activations.py +9 -6
  18. diffusers/models/attention.py +301 -29
  19. diffusers/models/attention_flax.py +9 -1
  20. diffusers/models/attention_processor.py +378 -6
  21. diffusers/models/autoencoders/__init__.py +5 -0
  22. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
  23. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
  24. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
  25. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
  26. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
  27. diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
  28. diffusers/models/controlnet.py +59 -39
  29. diffusers/models/controlnet_flax.py +19 -18
  30. diffusers/models/downsampling.py +338 -0
  31. diffusers/models/embeddings.py +112 -29
  32. diffusers/models/embeddings_flax.py +2 -0
  33. diffusers/models/lora.py +131 -1
  34. diffusers/models/modeling_flax_utils.py +14 -8
  35. diffusers/models/modeling_outputs.py +17 -0
  36. diffusers/models/modeling_utils.py +37 -29
  37. diffusers/models/normalization.py +110 -4
  38. diffusers/models/resnet.py +299 -652
  39. diffusers/models/transformer_2d.py +22 -5
  40. diffusers/models/transformer_temporal.py +183 -1
  41. diffusers/models/unet_2d_blocks_flax.py +5 -0
  42. diffusers/models/unet_2d_condition.py +46 -0
  43. diffusers/models/unet_2d_condition_flax.py +13 -13
  44. diffusers/models/unet_3d_blocks.py +957 -173
  45. diffusers/models/unet_3d_condition.py +16 -8
  46. diffusers/models/unet_kandinsky3.py +535 -0
  47. diffusers/models/unet_motion_model.py +48 -33
  48. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  49. diffusers/models/upsampling.py +454 -0
  50. diffusers/models/uvit_2d.py +471 -0
  51. diffusers/models/vae_flax.py +7 -0
  52. diffusers/models/vq_model.py +12 -3
  53. diffusers/optimization.py +16 -9
  54. diffusers/pipelines/__init__.py +137 -76
  55. diffusers/pipelines/amused/__init__.py +62 -0
  56. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  57. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  58. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  59. diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
  60. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  61. diffusers/pipelines/auto_pipeline.py +23 -13
  62. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  63. diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
  64. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
  65. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
  66. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
  67. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
  68. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
  69. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  70. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  71. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  72. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  73. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  74. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  75. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  76. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  77. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  78. diffusers/pipelines/deprecated/__init__.py +153 -0
  79. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  80. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
  81. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
  82. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  83. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  84. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  85. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  86. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  87. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  88. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  89. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  90. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  91. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  92. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  93. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
  94. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  95. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  96. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  97. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  98. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  100. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
  101. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
  102. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
  103. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
  104. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
  105. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
  106. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  107. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  108. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  109. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
  110. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  111. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
  112. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
  113. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
  114. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  115. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  116. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  117. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  118. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  119. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  120. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  122. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  123. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  124. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
  125. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
  126. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
  127. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
  128. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  129. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  130. diffusers/pipelines/onnx_utils.py +8 -5
  131. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  132. diffusers/pipelines/pipeline_flax_utils.py +11 -8
  133. diffusers/pipelines/pipeline_utils.py +63 -42
  134. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
  135. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  136. diffusers/pipelines/stable_diffusion/__init__.py +37 -65
  137. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
  138. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  139. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  140. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  141. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
  142. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  143. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  144. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
  145. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
  146. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
  147. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  151. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  152. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
  153. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  154. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
  155. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  156. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
  157. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  158. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  159. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
  160. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  161. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
  162. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  163. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
  164. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  165. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  166. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
  171. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  172. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
  175. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
  179. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
  180. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  181. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  182. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  183. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  184. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  185. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  186. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  187. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
  188. diffusers/schedulers/__init__.py +4 -4
  189. diffusers/schedulers/deprecated/__init__.py +50 -0
  190. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  191. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  192. diffusers/schedulers/scheduling_amused.py +162 -0
  193. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  194. diffusers/schedulers/scheduling_ddim.py +1 -3
  195. diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
  196. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  197. diffusers/schedulers/scheduling_ddpm.py +47 -3
  198. diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
  199. diffusers/schedulers/scheduling_deis_multistep.py +28 -6
  200. diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
  201. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
  202. diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
  203. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
  204. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
  205. diffusers/schedulers/scheduling_euler_discrete.py +102 -16
  206. diffusers/schedulers/scheduling_heun_discrete.py +17 -5
  207. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
  208. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
  209. diffusers/schedulers/scheduling_lcm.py +123 -29
  210. diffusers/schedulers/scheduling_lms_discrete.py +3 -3
  211. diffusers/schedulers/scheduling_pndm.py +1 -3
  212. diffusers/schedulers/scheduling_repaint.py +1 -3
  213. diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
  214. diffusers/schedulers/scheduling_utils.py +3 -1
  215. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  216. diffusers/training_utils.py +1 -1
  217. diffusers/utils/__init__.py +1 -2
  218. diffusers/utils/constants.py +10 -12
  219. diffusers/utils/dummy_pt_objects.py +75 -0
  220. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  221. diffusers/utils/dynamic_modules_utils.py +18 -22
  222. diffusers/utils/export_utils.py +8 -3
  223. diffusers/utils/hub_utils.py +24 -36
  224. diffusers/utils/logging.py +11 -11
  225. diffusers/utils/outputs.py +5 -5
  226. diffusers/utils/peft_utils.py +88 -44
  227. diffusers/utils/state_dict_utils.py +8 -0
  228. diffusers/utils/testing_utils.py +199 -1
  229. diffusers/utils/torch_utils.py +4 -4
  230. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
  231. diffusers-0.25.0.dist-info/RECORD +360 -0
  232. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  233. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  234. diffusers/loaders.py +0 -3336
  235. diffusers-0.23.1.dist-info/RECORD +0 -323
  236. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  237. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  238. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1553 @@
1
+ # Copyright 2023 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 contextlib import nullcontext
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, load_model_dict_into_meta
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
+ deprecate,
37
+ get_adapter_name,
38
+ get_peft_kwargs,
39
+ is_accelerate_available,
40
+ is_transformers_available,
41
+ logging,
42
+ recurse_remove_peft_layers,
43
+ scale_lora_layers,
44
+ set_adapter_layers,
45
+ set_weights_and_activate_adapters,
46
+ )
47
+ from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
48
+
49
+
50
+ if is_transformers_available():
51
+ from transformers import PreTrainedModel
52
+
53
+ from ..models.lora import PatchedLoraProjection, text_encoder_attn_modules, text_encoder_mlp_modules
54
+
55
+ if is_accelerate_available():
56
+ from accelerate import init_empty_weights
57
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ TEXT_ENCODER_NAME = "text_encoder"
62
+ UNET_NAME = "unet"
63
+ TRANSFORMER_NAME = "transformer"
64
+
65
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
66
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
67
+
68
+ 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."
69
+
70
+
71
+ class LoraLoaderMixin:
72
+ r"""
73
+ Load LoRA layers into [`UNet2DConditionModel`] and
74
+ [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
75
+ """
76
+
77
+ text_encoder_name = TEXT_ENCODER_NAME
78
+ unet_name = UNET_NAME
79
+ transformer_name = TRANSFORMER_NAME
80
+ num_fused_loras = 0
81
+
82
+ def load_lora_weights(
83
+ self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
84
+ ):
85
+ """
86
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
87
+ `self.text_encoder`.
88
+
89
+ All kwargs are forwarded to `self.lora_state_dict`.
90
+
91
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
92
+
93
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
94
+ `self.unet`.
95
+
96
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
97
+ into `self.text_encoder`.
98
+
99
+ Parameters:
100
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
101
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
102
+ kwargs (`dict`, *optional*):
103
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
104
+ adapter_name (`str`, *optional*):
105
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
106
+ `default_{i}` where i is the total number of adapters being loaded.
107
+ """
108
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
109
+ state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
110
+
111
+ is_correct_format = all("lora" in key for key in state_dict.keys())
112
+ if not is_correct_format:
113
+ raise ValueError("Invalid LoRA checkpoint.")
114
+
115
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
116
+
117
+ self.load_lora_into_unet(
118
+ state_dict,
119
+ network_alphas=network_alphas,
120
+ unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
121
+ low_cpu_mem_usage=low_cpu_mem_usage,
122
+ adapter_name=adapter_name,
123
+ _pipeline=self,
124
+ )
125
+ self.load_lora_into_text_encoder(
126
+ state_dict,
127
+ network_alphas=network_alphas,
128
+ text_encoder=getattr(self, self.text_encoder_name)
129
+ if not hasattr(self, "text_encoder")
130
+ else self.text_encoder,
131
+ lora_scale=self.lora_scale,
132
+ low_cpu_mem_usage=low_cpu_mem_usage,
133
+ adapter_name=adapter_name,
134
+ _pipeline=self,
135
+ )
136
+
137
+ @classmethod
138
+ @validate_hf_hub_args
139
+ def lora_state_dict(
140
+ cls,
141
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
142
+ **kwargs,
143
+ ):
144
+ r"""
145
+ Return state dict for lora weights and the network alphas.
146
+
147
+ <Tip warning={true}>
148
+
149
+ We support loading A1111 formatted LoRA checkpoints in a limited capacity.
150
+
151
+ This function is experimental and might change in the future.
152
+
153
+ </Tip>
154
+
155
+ Parameters:
156
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
157
+ Can be either:
158
+
159
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
160
+ the Hub.
161
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
162
+ with [`ModelMixin.save_pretrained`].
163
+ - A [torch state
164
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
165
+
166
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
167
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
168
+ is not used.
169
+ force_download (`bool`, *optional*, defaults to `False`):
170
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
171
+ cached versions if they exist.
172
+ resume_download (`bool`, *optional*, defaults to `False`):
173
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
174
+ incompletely downloaded files are deleted.
175
+ proxies (`Dict[str, str]`, *optional*):
176
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
177
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
178
+ local_files_only (`bool`, *optional*, defaults to `False`):
179
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
180
+ won't be downloaded from the Hub.
181
+ token (`str` or *bool*, *optional*):
182
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
183
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
184
+ revision (`str`, *optional*, defaults to `"main"`):
185
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
186
+ allowed by Git.
187
+ subfolder (`str`, *optional*, defaults to `""`):
188
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
189
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
190
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
191
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
192
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
193
+ argument to `True` will raise an error.
194
+ mirror (`str`, *optional*):
195
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
196
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
197
+ information.
198
+
199
+ """
200
+ # Load the main state dict first which has the LoRA layers for either of
201
+ # UNet and text encoder or both.
202
+ cache_dir = kwargs.pop("cache_dir", None)
203
+ force_download = kwargs.pop("force_download", False)
204
+ resume_download = kwargs.pop("resume_download", False)
205
+ proxies = kwargs.pop("proxies", None)
206
+ local_files_only = kwargs.pop("local_files_only", None)
207
+ token = kwargs.pop("token", None)
208
+ revision = kwargs.pop("revision", None)
209
+ subfolder = kwargs.pop("subfolder", None)
210
+ weight_name = kwargs.pop("weight_name", None)
211
+ unet_config = kwargs.pop("unet_config", None)
212
+ use_safetensors = kwargs.pop("use_safetensors", None)
213
+
214
+ allow_pickle = False
215
+ if use_safetensors is None:
216
+ use_safetensors = True
217
+ allow_pickle = True
218
+
219
+ user_agent = {
220
+ "file_type": "attn_procs_weights",
221
+ "framework": "pytorch",
222
+ }
223
+
224
+ model_file = None
225
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
226
+ # Let's first try to load .safetensors weights
227
+ if (use_safetensors and weight_name is None) or (
228
+ weight_name is not None and weight_name.endswith(".safetensors")
229
+ ):
230
+ try:
231
+ # Here we're relaxing the loading check to enable more Inference API
232
+ # friendliness where sometimes, it's not at all possible to automatically
233
+ # determine `weight_name`.
234
+ if weight_name is None:
235
+ weight_name = cls._best_guess_weight_name(
236
+ pretrained_model_name_or_path_or_dict,
237
+ file_extension=".safetensors",
238
+ local_files_only=local_files_only,
239
+ )
240
+ model_file = _get_model_file(
241
+ pretrained_model_name_or_path_or_dict,
242
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
243
+ cache_dir=cache_dir,
244
+ force_download=force_download,
245
+ resume_download=resume_download,
246
+ proxies=proxies,
247
+ local_files_only=local_files_only,
248
+ token=token,
249
+ revision=revision,
250
+ subfolder=subfolder,
251
+ user_agent=user_agent,
252
+ )
253
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
254
+ except (IOError, safetensors.SafetensorError) as e:
255
+ if not allow_pickle:
256
+ raise e
257
+ # try loading non-safetensors weights
258
+ model_file = None
259
+ pass
260
+
261
+ if model_file is None:
262
+ if weight_name is None:
263
+ weight_name = cls._best_guess_weight_name(
264
+ pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
265
+ )
266
+ model_file = _get_model_file(
267
+ pretrained_model_name_or_path_or_dict,
268
+ weights_name=weight_name or LORA_WEIGHT_NAME,
269
+ cache_dir=cache_dir,
270
+ force_download=force_download,
271
+ resume_download=resume_download,
272
+ proxies=proxies,
273
+ local_files_only=local_files_only,
274
+ token=token,
275
+ revision=revision,
276
+ subfolder=subfolder,
277
+ user_agent=user_agent,
278
+ )
279
+ state_dict = torch.load(model_file, map_location="cpu")
280
+ else:
281
+ state_dict = pretrained_model_name_or_path_or_dict
282
+
283
+ network_alphas = None
284
+ # TODO: replace it with a method from `state_dict_utils`
285
+ if all(
286
+ (
287
+ k.startswith("lora_te_")
288
+ or k.startswith("lora_unet_")
289
+ or k.startswith("lora_te1_")
290
+ or k.startswith("lora_te2_")
291
+ )
292
+ for k in state_dict.keys()
293
+ ):
294
+ # Map SDXL blocks correctly.
295
+ if unet_config is not None:
296
+ # use unet config to remap block numbers
297
+ state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
298
+ state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
299
+
300
+ return state_dict, network_alphas
301
+
302
+ @classmethod
303
+ def _best_guess_weight_name(
304
+ cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
305
+ ):
306
+ if local_files_only or HF_HUB_OFFLINE:
307
+ raise ValueError("When using the offline mode, you must specify a `weight_name`.")
308
+
309
+ targeted_files = []
310
+
311
+ if os.path.isfile(pretrained_model_name_or_path_or_dict):
312
+ return
313
+ elif os.path.isdir(pretrained_model_name_or_path_or_dict):
314
+ targeted_files = [
315
+ f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
316
+ ]
317
+ else:
318
+ files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
319
+ targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
320
+ if len(targeted_files) == 0:
321
+ return
322
+
323
+ # "scheduler" does not correspond to a LoRA checkpoint.
324
+ # "optimizer" does not correspond to a LoRA checkpoint
325
+ # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
326
+ unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
327
+ targeted_files = list(
328
+ filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
329
+ )
330
+
331
+ if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
332
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
333
+ elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
334
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
335
+
336
+ if len(targeted_files) > 1:
337
+ raise ValueError(
338
+ 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}."
339
+ )
340
+ weight_name = targeted_files[0]
341
+ return weight_name
342
+
343
+ @classmethod
344
+ def _optionally_disable_offloading(cls, _pipeline):
345
+ """
346
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
347
+
348
+ Args:
349
+ _pipeline (`DiffusionPipeline`):
350
+ The pipeline to disable offloading for.
351
+
352
+ Returns:
353
+ tuple:
354
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
355
+ """
356
+ is_model_cpu_offload = False
357
+ is_sequential_cpu_offload = False
358
+
359
+ if _pipeline is not None:
360
+ for _, component in _pipeline.components.items():
361
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
362
+ if not is_model_cpu_offload:
363
+ is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
364
+ if not is_sequential_cpu_offload:
365
+ is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
366
+
367
+ logger.info(
368
+ "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."
369
+ )
370
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
371
+
372
+ return (is_model_cpu_offload, is_sequential_cpu_offload)
373
+
374
+ @classmethod
375
+ def load_lora_into_unet(
376
+ cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
377
+ ):
378
+ """
379
+ This will load the LoRA layers specified in `state_dict` into `unet`.
380
+
381
+ Parameters:
382
+ state_dict (`dict`):
383
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
384
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
385
+ encoder lora layers.
386
+ network_alphas (`Dict[str, float]`):
387
+ See `LoRALinearLayer` for more details.
388
+ unet (`UNet2DConditionModel`):
389
+ The UNet model to load the LoRA layers into.
390
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
391
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
392
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
393
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
394
+ argument to `True` will raise an error.
395
+ adapter_name (`str`, *optional*):
396
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
397
+ `default_{i}` where i is the total number of adapters being loaded.
398
+ """
399
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
400
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
401
+ # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
402
+ # their prefixes.
403
+ keys = list(state_dict.keys())
404
+
405
+ if all(key.startswith("unet.unet") for key in keys):
406
+ deprecation_message = "Keys starting with 'unet.unet' are deprecated."
407
+ deprecate("unet.unet keys", "0.27", deprecation_message)
408
+
409
+ if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
410
+ # Load the layers corresponding to UNet.
411
+ logger.info(f"Loading {cls.unet_name}.")
412
+
413
+ unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
414
+ state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
415
+
416
+ if network_alphas is not None:
417
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
418
+ network_alphas = {
419
+ k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
420
+ }
421
+
422
+ else:
423
+ # Otherwise, we're dealing with the old format. This means the `state_dict` should only
424
+ # contain the module names of the `unet` as its keys WITHOUT any prefix.
425
+ if not USE_PEFT_BACKEND:
426
+ 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()}`."
427
+ logger.warn(warn_message)
428
+
429
+ if USE_PEFT_BACKEND and len(state_dict.keys()) > 0:
430
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
431
+
432
+ if adapter_name in getattr(unet, "peft_config", {}):
433
+ raise ValueError(
434
+ f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
435
+ )
436
+
437
+ state_dict = convert_unet_state_dict_to_peft(state_dict)
438
+
439
+ if network_alphas is not None:
440
+ # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
441
+ # `convert_unet_state_dict_to_peft` method.
442
+ network_alphas = convert_unet_state_dict_to_peft(network_alphas)
443
+
444
+ rank = {}
445
+ for key, val in state_dict.items():
446
+ if "lora_B" in key:
447
+ rank[key] = val.shape[1]
448
+
449
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
450
+ lora_config = LoraConfig(**lora_config_kwargs)
451
+
452
+ # adapter_name
453
+ if adapter_name is None:
454
+ adapter_name = get_adapter_name(unet)
455
+
456
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
457
+ # otherwise loading LoRA weights will lead to an error
458
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
459
+
460
+ inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
461
+ incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
462
+
463
+ if incompatible_keys is not None:
464
+ # check only for unexpected keys
465
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
466
+ if unexpected_keys:
467
+ logger.warning(
468
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
469
+ f" {unexpected_keys}. "
470
+ )
471
+
472
+ # Offload back.
473
+ if is_model_cpu_offload:
474
+ _pipeline.enable_model_cpu_offload()
475
+ elif is_sequential_cpu_offload:
476
+ _pipeline.enable_sequential_cpu_offload()
477
+ # Unsafe code />
478
+
479
+ unet.load_attn_procs(
480
+ state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
481
+ )
482
+
483
+ @classmethod
484
+ def load_lora_into_text_encoder(
485
+ cls,
486
+ state_dict,
487
+ network_alphas,
488
+ text_encoder,
489
+ prefix=None,
490
+ lora_scale=1.0,
491
+ low_cpu_mem_usage=None,
492
+ adapter_name=None,
493
+ _pipeline=None,
494
+ ):
495
+ """
496
+ This will load the LoRA layers specified in `state_dict` into `text_encoder`
497
+
498
+ Parameters:
499
+ state_dict (`dict`):
500
+ A standard state dict containing the lora layer parameters. The key should be prefixed with an
501
+ additional `text_encoder` to distinguish between unet lora layers.
502
+ network_alphas (`Dict[str, float]`):
503
+ See `LoRALinearLayer` for more details.
504
+ text_encoder (`CLIPTextModel`):
505
+ The text encoder model to load the LoRA layers into.
506
+ prefix (`str`):
507
+ Expected prefix of the `text_encoder` in the `state_dict`.
508
+ lora_scale (`float`):
509
+ How much to scale the output of the lora linear layer before it is added with the output of the regular
510
+ lora layer.
511
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
512
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
513
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
514
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
515
+ argument to `True` will raise an error.
516
+ adapter_name (`str`, *optional*):
517
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
518
+ `default_{i}` where i is the total number of adapters being loaded.
519
+ """
520
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
521
+
522
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
523
+ # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
524
+ # their prefixes.
525
+ keys = list(state_dict.keys())
526
+ prefix = cls.text_encoder_name if prefix is None else prefix
527
+
528
+ # Safe prefix to check with.
529
+ if any(cls.text_encoder_name in key for key in keys):
530
+ # Load the layers corresponding to text encoder and make necessary adjustments.
531
+ text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
532
+ text_encoder_lora_state_dict = {
533
+ k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
534
+ }
535
+
536
+ if len(text_encoder_lora_state_dict) > 0:
537
+ logger.info(f"Loading {prefix}.")
538
+ rank = {}
539
+ text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
540
+
541
+ if USE_PEFT_BACKEND:
542
+ # convert state dict
543
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
544
+
545
+ for name, _ in text_encoder_attn_modules(text_encoder):
546
+ rank_key = f"{name}.out_proj.lora_B.weight"
547
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
548
+
549
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
550
+ if patch_mlp:
551
+ for name, _ in text_encoder_mlp_modules(text_encoder):
552
+ rank_key_fc1 = f"{name}.fc1.lora_B.weight"
553
+ rank_key_fc2 = f"{name}.fc2.lora_B.weight"
554
+
555
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
556
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
557
+ else:
558
+ for name, _ in text_encoder_attn_modules(text_encoder):
559
+ rank_key = f"{name}.out_proj.lora_linear_layer.up.weight"
560
+ rank.update({rank_key: text_encoder_lora_state_dict[rank_key].shape[1]})
561
+
562
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
563
+ if patch_mlp:
564
+ for name, _ in text_encoder_mlp_modules(text_encoder):
565
+ rank_key_fc1 = f"{name}.fc1.lora_linear_layer.up.weight"
566
+ rank_key_fc2 = f"{name}.fc2.lora_linear_layer.up.weight"
567
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
568
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
569
+
570
+ if network_alphas is not None:
571
+ alpha_keys = [
572
+ k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
573
+ ]
574
+ network_alphas = {
575
+ k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
576
+ }
577
+
578
+ if USE_PEFT_BACKEND:
579
+ from peft import LoraConfig
580
+
581
+ lora_config_kwargs = get_peft_kwargs(
582
+ rank, network_alphas, text_encoder_lora_state_dict, is_unet=False
583
+ )
584
+
585
+ lora_config = LoraConfig(**lora_config_kwargs)
586
+
587
+ # adapter_name
588
+ if adapter_name is None:
589
+ adapter_name = get_adapter_name(text_encoder)
590
+
591
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
592
+
593
+ # inject LoRA layers and load the state dict
594
+ # in transformers we automatically check whether the adapter name is already in use or not
595
+ text_encoder.load_adapter(
596
+ adapter_name=adapter_name,
597
+ adapter_state_dict=text_encoder_lora_state_dict,
598
+ peft_config=lora_config,
599
+ )
600
+
601
+ # scale LoRA layers with `lora_scale`
602
+ scale_lora_layers(text_encoder, weight=lora_scale)
603
+ else:
604
+ cls._modify_text_encoder(
605
+ text_encoder,
606
+ lora_scale,
607
+ network_alphas,
608
+ rank=rank,
609
+ patch_mlp=patch_mlp,
610
+ low_cpu_mem_usage=low_cpu_mem_usage,
611
+ )
612
+
613
+ is_pipeline_offloaded = _pipeline is not None and any(
614
+ isinstance(c, torch.nn.Module) and hasattr(c, "_hf_hook")
615
+ for c in _pipeline.components.values()
616
+ )
617
+ if is_pipeline_offloaded and low_cpu_mem_usage:
618
+ low_cpu_mem_usage = True
619
+ logger.info(
620
+ f"Pipeline {_pipeline.__class__} is offloaded. Therefore low cpu mem usage loading is forced."
621
+ )
622
+
623
+ if low_cpu_mem_usage:
624
+ device = next(iter(text_encoder_lora_state_dict.values())).device
625
+ dtype = next(iter(text_encoder_lora_state_dict.values())).dtype
626
+ unexpected_keys = load_model_dict_into_meta(
627
+ text_encoder, text_encoder_lora_state_dict, device=device, dtype=dtype
628
+ )
629
+ else:
630
+ load_state_dict_results = text_encoder.load_state_dict(
631
+ text_encoder_lora_state_dict, strict=False
632
+ )
633
+ unexpected_keys = load_state_dict_results.unexpected_keys
634
+
635
+ if len(unexpected_keys) != 0:
636
+ raise ValueError(
637
+ f"failed to load text encoder state dict, unexpected keys: {load_state_dict_results.unexpected_keys}"
638
+ )
639
+
640
+ # <Unsafe code
641
+ # We can be sure that the following works as all we do is change the dtype and device of the text encoder
642
+ # Now we remove any existing hooks to
643
+ is_model_cpu_offload = False
644
+ is_sequential_cpu_offload = False
645
+ if _pipeline is not None:
646
+ for _, component in _pipeline.components.items():
647
+ if isinstance(component, torch.nn.Module):
648
+ if hasattr(component, "_hf_hook"):
649
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
650
+ is_sequential_cpu_offload = isinstance(
651
+ getattr(component, "_hf_hook"), AlignDevicesHook
652
+ )
653
+ logger.info(
654
+ "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
655
+ )
656
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
657
+
658
+ text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
659
+
660
+ # Offload back.
661
+ if is_model_cpu_offload:
662
+ _pipeline.enable_model_cpu_offload()
663
+ elif is_sequential_cpu_offload:
664
+ _pipeline.enable_sequential_cpu_offload()
665
+ # Unsafe code />
666
+
667
+ @classmethod
668
+ def load_lora_into_transformer(
669
+ cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
670
+ ):
671
+ """
672
+ This will load the LoRA layers specified in `state_dict` into `transformer`.
673
+
674
+ Parameters:
675
+ state_dict (`dict`):
676
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
677
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
678
+ encoder lora layers.
679
+ network_alphas (`Dict[str, float]`):
680
+ See `LoRALinearLayer` for more details.
681
+ unet (`UNet2DConditionModel`):
682
+ The UNet model to load the LoRA layers into.
683
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
684
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
685
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
686
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
687
+ argument to `True` will raise an error.
688
+ adapter_name (`str`, *optional*):
689
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
690
+ `default_{i}` where i is the total number of adapters being loaded.
691
+ """
692
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
693
+
694
+ keys = list(state_dict.keys())
695
+
696
+ transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
697
+ state_dict = {
698
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
699
+ }
700
+
701
+ if network_alphas is not None:
702
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
703
+ network_alphas = {
704
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
705
+ }
706
+
707
+ if len(state_dict.keys()) > 0:
708
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
709
+
710
+ if adapter_name in getattr(transformer, "peft_config", {}):
711
+ raise ValueError(
712
+ f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
713
+ )
714
+
715
+ rank = {}
716
+ for key, val in state_dict.items():
717
+ if "lora_B" in key:
718
+ rank[key] = val.shape[1]
719
+
720
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
721
+ lora_config = LoraConfig(**lora_config_kwargs)
722
+
723
+ # adapter_name
724
+ if adapter_name is None:
725
+ adapter_name = get_adapter_name(transformer)
726
+
727
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
728
+ # otherwise loading LoRA weights will lead to an error
729
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
730
+
731
+ inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
732
+ incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
733
+
734
+ if incompatible_keys is not None:
735
+ # check only for unexpected keys
736
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
737
+ if unexpected_keys:
738
+ logger.warning(
739
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
740
+ f" {unexpected_keys}. "
741
+ )
742
+
743
+ # Offload back.
744
+ if is_model_cpu_offload:
745
+ _pipeline.enable_model_cpu_offload()
746
+ elif is_sequential_cpu_offload:
747
+ _pipeline.enable_sequential_cpu_offload()
748
+ # Unsafe code />
749
+
750
+ @property
751
+ def lora_scale(self) -> float:
752
+ # property function that returns the lora scale which can be set at run time by the pipeline.
753
+ # if _lora_scale has not been set, return 1
754
+ return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
755
+
756
+ def _remove_text_encoder_monkey_patch(self):
757
+ if USE_PEFT_BACKEND:
758
+ remove_method = recurse_remove_peft_layers
759
+ else:
760
+ remove_method = self._remove_text_encoder_monkey_patch_classmethod
761
+
762
+ if hasattr(self, "text_encoder"):
763
+ remove_method(self.text_encoder)
764
+
765
+ # In case text encoder have no Lora attached
766
+ if USE_PEFT_BACKEND and getattr(self.text_encoder, "peft_config", None) is not None:
767
+ del self.text_encoder.peft_config
768
+ self.text_encoder._hf_peft_config_loaded = None
769
+ if hasattr(self, "text_encoder_2"):
770
+ remove_method(self.text_encoder_2)
771
+ if USE_PEFT_BACKEND:
772
+ del self.text_encoder_2.peft_config
773
+ self.text_encoder_2._hf_peft_config_loaded = None
774
+
775
+ @classmethod
776
+ def _remove_text_encoder_monkey_patch_classmethod(cls, text_encoder):
777
+ deprecate("_remove_text_encoder_monkey_patch_classmethod", "0.27", LORA_DEPRECATION_MESSAGE)
778
+
779
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
780
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
781
+ attn_module.q_proj.lora_linear_layer = None
782
+ attn_module.k_proj.lora_linear_layer = None
783
+ attn_module.v_proj.lora_linear_layer = None
784
+ attn_module.out_proj.lora_linear_layer = None
785
+
786
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
787
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
788
+ mlp_module.fc1.lora_linear_layer = None
789
+ mlp_module.fc2.lora_linear_layer = None
790
+
791
+ @classmethod
792
+ def _modify_text_encoder(
793
+ cls,
794
+ text_encoder,
795
+ lora_scale=1,
796
+ network_alphas=None,
797
+ rank: Union[Dict[str, int], int] = 4,
798
+ dtype=None,
799
+ patch_mlp=False,
800
+ low_cpu_mem_usage=False,
801
+ ):
802
+ r"""
803
+ Monkey-patches the forward passes of attention modules of the text encoder.
804
+ """
805
+ deprecate("_modify_text_encoder", "0.27", LORA_DEPRECATION_MESSAGE)
806
+
807
+ def create_patched_linear_lora(model, network_alpha, rank, dtype, lora_parameters):
808
+ linear_layer = model.regular_linear_layer if isinstance(model, PatchedLoraProjection) else model
809
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
810
+ with ctx():
811
+ model = PatchedLoraProjection(linear_layer, lora_scale, network_alpha, rank, dtype=dtype)
812
+
813
+ lora_parameters.extend(model.lora_linear_layer.parameters())
814
+ return model
815
+
816
+ # First, remove any monkey-patch that might have been applied before
817
+ cls._remove_text_encoder_monkey_patch_classmethod(text_encoder)
818
+
819
+ lora_parameters = []
820
+ network_alphas = {} if network_alphas is None else network_alphas
821
+ is_network_alphas_populated = len(network_alphas) > 0
822
+
823
+ for name, attn_module in text_encoder_attn_modules(text_encoder):
824
+ query_alpha = network_alphas.pop(name + ".to_q_lora.down.weight.alpha", None)
825
+ key_alpha = network_alphas.pop(name + ".to_k_lora.down.weight.alpha", None)
826
+ value_alpha = network_alphas.pop(name + ".to_v_lora.down.weight.alpha", None)
827
+ out_alpha = network_alphas.pop(name + ".to_out_lora.down.weight.alpha", None)
828
+
829
+ if isinstance(rank, dict):
830
+ current_rank = rank.pop(f"{name}.out_proj.lora_linear_layer.up.weight")
831
+ else:
832
+ current_rank = rank
833
+
834
+ attn_module.q_proj = create_patched_linear_lora(
835
+ attn_module.q_proj, query_alpha, current_rank, dtype, lora_parameters
836
+ )
837
+ attn_module.k_proj = create_patched_linear_lora(
838
+ attn_module.k_proj, key_alpha, current_rank, dtype, lora_parameters
839
+ )
840
+ attn_module.v_proj = create_patched_linear_lora(
841
+ attn_module.v_proj, value_alpha, current_rank, dtype, lora_parameters
842
+ )
843
+ attn_module.out_proj = create_patched_linear_lora(
844
+ attn_module.out_proj, out_alpha, current_rank, dtype, lora_parameters
845
+ )
846
+
847
+ if patch_mlp:
848
+ for name, mlp_module in text_encoder_mlp_modules(text_encoder):
849
+ fc1_alpha = network_alphas.pop(name + ".fc1.lora_linear_layer.down.weight.alpha", None)
850
+ fc2_alpha = network_alphas.pop(name + ".fc2.lora_linear_layer.down.weight.alpha", None)
851
+
852
+ current_rank_fc1 = rank.pop(f"{name}.fc1.lora_linear_layer.up.weight")
853
+ current_rank_fc2 = rank.pop(f"{name}.fc2.lora_linear_layer.up.weight")
854
+
855
+ mlp_module.fc1 = create_patched_linear_lora(
856
+ mlp_module.fc1, fc1_alpha, current_rank_fc1, dtype, lora_parameters
857
+ )
858
+ mlp_module.fc2 = create_patched_linear_lora(
859
+ mlp_module.fc2, fc2_alpha, current_rank_fc2, dtype, lora_parameters
860
+ )
861
+
862
+ if is_network_alphas_populated and len(network_alphas) > 0:
863
+ raise ValueError(
864
+ f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
865
+ )
866
+
867
+ return lora_parameters
868
+
869
+ @classmethod
870
+ def save_lora_weights(
871
+ cls,
872
+ save_directory: Union[str, os.PathLike],
873
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
874
+ text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
875
+ transformer_lora_layers: Dict[str, torch.nn.Module] = None,
876
+ is_main_process: bool = True,
877
+ weight_name: str = None,
878
+ save_function: Callable = None,
879
+ safe_serialization: bool = True,
880
+ ):
881
+ r"""
882
+ Save the LoRA parameters corresponding to the UNet and text encoder.
883
+
884
+ Arguments:
885
+ save_directory (`str` or `os.PathLike`):
886
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
887
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
888
+ State dict of the LoRA layers corresponding to the `unet`.
889
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
890
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
891
+ encoder LoRA state dict because it comes from 🤗 Transformers.
892
+ is_main_process (`bool`, *optional*, defaults to `True`):
893
+ Whether the process calling this is the main process or not. Useful during distributed training and you
894
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
895
+ process to avoid race conditions.
896
+ save_function (`Callable`):
897
+ The function to use to save the state dictionary. Useful during distributed training when you need to
898
+ replace `torch.save` with another method. Can be configured with the environment variable
899
+ `DIFFUSERS_SAVE_MODE`.
900
+ safe_serialization (`bool`, *optional*, defaults to `True`):
901
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
902
+ """
903
+ state_dict = {}
904
+
905
+ def pack_weights(layers, prefix):
906
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
907
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
908
+ return layers_state_dict
909
+
910
+ if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
911
+ raise ValueError(
912
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
913
+ )
914
+
915
+ if unet_lora_layers:
916
+ state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
917
+
918
+ if text_encoder_lora_layers:
919
+ state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
920
+
921
+ if transformer_lora_layers:
922
+ state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
923
+
924
+ # Save the model
925
+ cls.write_lora_layers(
926
+ state_dict=state_dict,
927
+ save_directory=save_directory,
928
+ is_main_process=is_main_process,
929
+ weight_name=weight_name,
930
+ save_function=save_function,
931
+ safe_serialization=safe_serialization,
932
+ )
933
+
934
+ @staticmethod
935
+ def write_lora_layers(
936
+ state_dict: Dict[str, torch.Tensor],
937
+ save_directory: str,
938
+ is_main_process: bool,
939
+ weight_name: str,
940
+ save_function: Callable,
941
+ safe_serialization: bool,
942
+ ):
943
+ if os.path.isfile(save_directory):
944
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
945
+ return
946
+
947
+ if save_function is None:
948
+ if safe_serialization:
949
+
950
+ def save_function(weights, filename):
951
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
952
+
953
+ else:
954
+ save_function = torch.save
955
+
956
+ os.makedirs(save_directory, exist_ok=True)
957
+
958
+ if weight_name is None:
959
+ if safe_serialization:
960
+ weight_name = LORA_WEIGHT_NAME_SAFE
961
+ else:
962
+ weight_name = LORA_WEIGHT_NAME
963
+
964
+ save_function(state_dict, os.path.join(save_directory, weight_name))
965
+ logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
966
+
967
+ def unload_lora_weights(self):
968
+ """
969
+ Unloads the LoRA parameters.
970
+
971
+ Examples:
972
+
973
+ ```python
974
+ >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
975
+ >>> pipeline.unload_lora_weights()
976
+ >>> ...
977
+ ```
978
+ """
979
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
980
+
981
+ if not USE_PEFT_BACKEND:
982
+ if version.parse(__version__) > version.parse("0.23"):
983
+ logger.warn(
984
+ "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
985
+ "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
986
+ )
987
+
988
+ for _, module in unet.named_modules():
989
+ if hasattr(module, "set_lora_layer"):
990
+ module.set_lora_layer(None)
991
+ else:
992
+ recurse_remove_peft_layers(unet)
993
+ if hasattr(unet, "peft_config"):
994
+ del unet.peft_config
995
+
996
+ # Safe to call the following regardless of LoRA.
997
+ self._remove_text_encoder_monkey_patch()
998
+
999
+ def fuse_lora(
1000
+ self,
1001
+ fuse_unet: bool = True,
1002
+ fuse_text_encoder: bool = True,
1003
+ lora_scale: float = 1.0,
1004
+ safe_fusing: bool = False,
1005
+ adapter_names: Optional[List[str]] = None,
1006
+ ):
1007
+ r"""
1008
+ Fuses the LoRA parameters into the original parameters of the corresponding blocks.
1009
+
1010
+ <Tip warning={true}>
1011
+
1012
+ This is an experimental API.
1013
+
1014
+ </Tip>
1015
+
1016
+ Args:
1017
+ fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
1018
+ fuse_text_encoder (`bool`, defaults to `True`):
1019
+ Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
1020
+ LoRA parameters then it won't have any effect.
1021
+ lora_scale (`float`, defaults to 1.0):
1022
+ Controls how much to influence the outputs with the LoRA parameters.
1023
+ safe_fusing (`bool`, defaults to `False`):
1024
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
1025
+ adapter_names (`List[str]`, *optional*):
1026
+ Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
1027
+
1028
+ Example:
1029
+
1030
+ ```py
1031
+ from diffusers import DiffusionPipeline
1032
+ import torch
1033
+
1034
+ pipeline = DiffusionPipeline.from_pretrained(
1035
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
1036
+ ).to("cuda")
1037
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
1038
+ pipeline.fuse_lora(lora_scale=0.7)
1039
+ ```
1040
+ """
1041
+ if fuse_unet or fuse_text_encoder:
1042
+ self.num_fused_loras += 1
1043
+ if self.num_fused_loras > 1:
1044
+ logger.warn(
1045
+ "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.",
1046
+ )
1047
+
1048
+ if fuse_unet:
1049
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1050
+ unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
1051
+
1052
+ if USE_PEFT_BACKEND:
1053
+ from peft.tuners.tuners_utils import BaseTunerLayer
1054
+
1055
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
1056
+ merge_kwargs = {"safe_merge": safe_fusing}
1057
+
1058
+ for module in text_encoder.modules():
1059
+ if isinstance(module, BaseTunerLayer):
1060
+ if lora_scale != 1.0:
1061
+ module.scale_layer(lora_scale)
1062
+
1063
+ # For BC with previous PEFT versions, we need to check the signature
1064
+ # of the `merge` method to see if it supports the `adapter_names` argument.
1065
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
1066
+ if "adapter_names" in supported_merge_kwargs:
1067
+ merge_kwargs["adapter_names"] = adapter_names
1068
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
1069
+ raise ValueError(
1070
+ "The `adapter_names` argument is not supported with your PEFT version. "
1071
+ "Please upgrade to the latest version of PEFT. `pip install -U peft`"
1072
+ )
1073
+
1074
+ module.merge(**merge_kwargs)
1075
+
1076
+ else:
1077
+ deprecate("fuse_text_encoder_lora", "0.27", LORA_DEPRECATION_MESSAGE)
1078
+
1079
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, **kwargs):
1080
+ if "adapter_names" in kwargs and kwargs["adapter_names"] is not None:
1081
+ raise ValueError(
1082
+ "The `adapter_names` argument is not supported in your environment. Please switch to PEFT "
1083
+ "backend to use this argument by installing latest PEFT and transformers."
1084
+ " `pip install -U peft transformers`"
1085
+ )
1086
+
1087
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
1088
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
1089
+ attn_module.q_proj._fuse_lora(lora_scale, safe_fusing)
1090
+ attn_module.k_proj._fuse_lora(lora_scale, safe_fusing)
1091
+ attn_module.v_proj._fuse_lora(lora_scale, safe_fusing)
1092
+ attn_module.out_proj._fuse_lora(lora_scale, safe_fusing)
1093
+
1094
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
1095
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
1096
+ mlp_module.fc1._fuse_lora(lora_scale, safe_fusing)
1097
+ mlp_module.fc2._fuse_lora(lora_scale, safe_fusing)
1098
+
1099
+ if fuse_text_encoder:
1100
+ if hasattr(self, "text_encoder"):
1101
+ fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
1102
+ if hasattr(self, "text_encoder_2"):
1103
+ fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
1104
+
1105
+ def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
1106
+ r"""
1107
+ Reverses the effect of
1108
+ [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
1109
+
1110
+ <Tip warning={true}>
1111
+
1112
+ This is an experimental API.
1113
+
1114
+ </Tip>
1115
+
1116
+ Args:
1117
+ unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
1118
+ unfuse_text_encoder (`bool`, defaults to `True`):
1119
+ Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
1120
+ LoRA parameters then it won't have any effect.
1121
+ """
1122
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1123
+ if unfuse_unet:
1124
+ if not USE_PEFT_BACKEND:
1125
+ unet.unfuse_lora()
1126
+ else:
1127
+ from peft.tuners.tuners_utils import BaseTunerLayer
1128
+
1129
+ for module in unet.modules():
1130
+ if isinstance(module, BaseTunerLayer):
1131
+ module.unmerge()
1132
+
1133
+ if USE_PEFT_BACKEND:
1134
+ from peft.tuners.tuners_utils import BaseTunerLayer
1135
+
1136
+ def unfuse_text_encoder_lora(text_encoder):
1137
+ for module in text_encoder.modules():
1138
+ if isinstance(module, BaseTunerLayer):
1139
+ module.unmerge()
1140
+
1141
+ else:
1142
+ deprecate("unfuse_text_encoder_lora", "0.27", LORA_DEPRECATION_MESSAGE)
1143
+
1144
+ def unfuse_text_encoder_lora(text_encoder):
1145
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
1146
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
1147
+ attn_module.q_proj._unfuse_lora()
1148
+ attn_module.k_proj._unfuse_lora()
1149
+ attn_module.v_proj._unfuse_lora()
1150
+ attn_module.out_proj._unfuse_lora()
1151
+
1152
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
1153
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
1154
+ mlp_module.fc1._unfuse_lora()
1155
+ mlp_module.fc2._unfuse_lora()
1156
+
1157
+ if unfuse_text_encoder:
1158
+ if hasattr(self, "text_encoder"):
1159
+ unfuse_text_encoder_lora(self.text_encoder)
1160
+ if hasattr(self, "text_encoder_2"):
1161
+ unfuse_text_encoder_lora(self.text_encoder_2)
1162
+
1163
+ self.num_fused_loras -= 1
1164
+
1165
+ def set_adapters_for_text_encoder(
1166
+ self,
1167
+ adapter_names: Union[List[str], str],
1168
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
1169
+ text_encoder_weights: List[float] = None,
1170
+ ):
1171
+ """
1172
+ Sets the adapter layers for the text encoder.
1173
+
1174
+ Args:
1175
+ adapter_names (`List[str]` or `str`):
1176
+ The names of the adapters to use.
1177
+ text_encoder (`torch.nn.Module`, *optional*):
1178
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
1179
+ attribute.
1180
+ text_encoder_weights (`List[float]`, *optional*):
1181
+ The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
1182
+ """
1183
+ if not USE_PEFT_BACKEND:
1184
+ raise ValueError("PEFT backend is required for this method.")
1185
+
1186
+ def process_weights(adapter_names, weights):
1187
+ if weights is None:
1188
+ weights = [1.0] * len(adapter_names)
1189
+ elif isinstance(weights, float):
1190
+ weights = [weights]
1191
+
1192
+ if len(adapter_names) != len(weights):
1193
+ raise ValueError(
1194
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
1195
+ )
1196
+ return weights
1197
+
1198
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1199
+ text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
1200
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1201
+ if text_encoder is None:
1202
+ raise ValueError(
1203
+ "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
1204
+ )
1205
+ set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
1206
+
1207
+ def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1208
+ """
1209
+ Disables the LoRA layers for the text encoder.
1210
+
1211
+ Args:
1212
+ text_encoder (`torch.nn.Module`, *optional*):
1213
+ The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1214
+ `text_encoder` attribute.
1215
+ """
1216
+ if not USE_PEFT_BACKEND:
1217
+ raise ValueError("PEFT backend is required for this method.")
1218
+
1219
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1220
+ if text_encoder is None:
1221
+ raise ValueError("Text Encoder not found.")
1222
+ set_adapter_layers(text_encoder, enabled=False)
1223
+
1224
+ def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1225
+ """
1226
+ Enables the LoRA layers for the text encoder.
1227
+
1228
+ Args:
1229
+ text_encoder (`torch.nn.Module`, *optional*):
1230
+ The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1231
+ attribute.
1232
+ """
1233
+ if not USE_PEFT_BACKEND:
1234
+ raise ValueError("PEFT backend is required for this method.")
1235
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1236
+ if text_encoder is None:
1237
+ raise ValueError("Text Encoder not found.")
1238
+ set_adapter_layers(self.text_encoder, enabled=True)
1239
+
1240
+ def set_adapters(
1241
+ self,
1242
+ adapter_names: Union[List[str], str],
1243
+ adapter_weights: Optional[List[float]] = None,
1244
+ ):
1245
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1246
+ # Handle the UNET
1247
+ unet.set_adapters(adapter_names, adapter_weights)
1248
+
1249
+ # Handle the Text Encoder
1250
+ if hasattr(self, "text_encoder"):
1251
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
1252
+ if hasattr(self, "text_encoder_2"):
1253
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
1254
+
1255
+ def disable_lora(self):
1256
+ if not USE_PEFT_BACKEND:
1257
+ raise ValueError("PEFT backend is required for this method.")
1258
+
1259
+ # Disable unet adapters
1260
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1261
+ unet.disable_lora()
1262
+
1263
+ # Disable text encoder adapters
1264
+ if hasattr(self, "text_encoder"):
1265
+ self.disable_lora_for_text_encoder(self.text_encoder)
1266
+ if hasattr(self, "text_encoder_2"):
1267
+ self.disable_lora_for_text_encoder(self.text_encoder_2)
1268
+
1269
+ def enable_lora(self):
1270
+ if not USE_PEFT_BACKEND:
1271
+ raise ValueError("PEFT backend is required for this method.")
1272
+
1273
+ # Enable unet adapters
1274
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1275
+ unet.enable_lora()
1276
+
1277
+ # Enable text encoder adapters
1278
+ if hasattr(self, "text_encoder"):
1279
+ self.enable_lora_for_text_encoder(self.text_encoder)
1280
+ if hasattr(self, "text_encoder_2"):
1281
+ self.enable_lora_for_text_encoder(self.text_encoder_2)
1282
+
1283
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
1284
+ """
1285
+ Args:
1286
+ Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1287
+ adapter_names (`Union[List[str], str]`):
1288
+ The names of the adapter to delete. Can be a single string or a list of strings
1289
+ """
1290
+ if not USE_PEFT_BACKEND:
1291
+ raise ValueError("PEFT backend is required for this method.")
1292
+
1293
+ if isinstance(adapter_names, str):
1294
+ adapter_names = [adapter_names]
1295
+
1296
+ # Delete unet adapters
1297
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1298
+ unet.delete_adapters(adapter_names)
1299
+
1300
+ for adapter_name in adapter_names:
1301
+ # Delete text encoder adapters
1302
+ if hasattr(self, "text_encoder"):
1303
+ delete_adapter_layers(self.text_encoder, adapter_name)
1304
+ if hasattr(self, "text_encoder_2"):
1305
+ delete_adapter_layers(self.text_encoder_2, adapter_name)
1306
+
1307
+ def get_active_adapters(self) -> List[str]:
1308
+ """
1309
+ Gets the list of the current active adapters.
1310
+
1311
+ Example:
1312
+
1313
+ ```python
1314
+ from diffusers import DiffusionPipeline
1315
+
1316
+ pipeline = DiffusionPipeline.from_pretrained(
1317
+ "stabilityai/stable-diffusion-xl-base-1.0",
1318
+ ).to("cuda")
1319
+ pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1320
+ pipeline.get_active_adapters()
1321
+ ```
1322
+ """
1323
+ if not USE_PEFT_BACKEND:
1324
+ raise ValueError(
1325
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1326
+ )
1327
+
1328
+ from peft.tuners.tuners_utils import BaseTunerLayer
1329
+
1330
+ active_adapters = []
1331
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1332
+ for module in unet.modules():
1333
+ if isinstance(module, BaseTunerLayer):
1334
+ active_adapters = module.active_adapters
1335
+ break
1336
+
1337
+ return active_adapters
1338
+
1339
+ def get_list_adapters(self) -> Dict[str, List[str]]:
1340
+ """
1341
+ Gets the current list of all available adapters in the pipeline.
1342
+ """
1343
+ if not USE_PEFT_BACKEND:
1344
+ raise ValueError(
1345
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1346
+ )
1347
+
1348
+ set_adapters = {}
1349
+
1350
+ if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1351
+ set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1352
+
1353
+ if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1354
+ set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1355
+
1356
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1357
+ if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1358
+ set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1359
+
1360
+ return set_adapters
1361
+
1362
+ def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1363
+ """
1364
+ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1365
+ you want to load multiple adapters and free some GPU memory.
1366
+
1367
+ Args:
1368
+ adapter_names (`List[str]`):
1369
+ List of adapters to send device to.
1370
+ device (`Union[torch.device, str, int]`):
1371
+ Device to send the adapters to. Can be either a torch device, a str or an integer.
1372
+ """
1373
+ if not USE_PEFT_BACKEND:
1374
+ raise ValueError("PEFT backend is required for this method.")
1375
+
1376
+ from peft.tuners.tuners_utils import BaseTunerLayer
1377
+
1378
+ # Handle the UNET
1379
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1380
+ for unet_module in unet.modules():
1381
+ if isinstance(unet_module, BaseTunerLayer):
1382
+ for adapter_name in adapter_names:
1383
+ unet_module.lora_A[adapter_name].to(device)
1384
+ unet_module.lora_B[adapter_name].to(device)
1385
+
1386
+ # Handle the text encoder
1387
+ modules_to_process = []
1388
+ if hasattr(self, "text_encoder"):
1389
+ modules_to_process.append(self.text_encoder)
1390
+
1391
+ if hasattr(self, "text_encoder_2"):
1392
+ modules_to_process.append(self.text_encoder_2)
1393
+
1394
+ for text_encoder in modules_to_process:
1395
+ # loop over submodules
1396
+ for text_encoder_module in text_encoder.modules():
1397
+ if isinstance(text_encoder_module, BaseTunerLayer):
1398
+ for adapter_name in adapter_names:
1399
+ text_encoder_module.lora_A[adapter_name].to(device)
1400
+ text_encoder_module.lora_B[adapter_name].to(device)
1401
+
1402
+
1403
+ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1404
+ """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1405
+
1406
+ # Overrride to properly handle the loading and unloading of the additional text encoder.
1407
+ def load_lora_weights(
1408
+ self,
1409
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1410
+ adapter_name: Optional[str] = None,
1411
+ **kwargs,
1412
+ ):
1413
+ """
1414
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1415
+ `self.text_encoder`.
1416
+
1417
+ All kwargs are forwarded to `self.lora_state_dict`.
1418
+
1419
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1420
+
1421
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1422
+ `self.unet`.
1423
+
1424
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1425
+ into `self.text_encoder`.
1426
+
1427
+ Parameters:
1428
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1429
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1430
+ adapter_name (`str`, *optional*):
1431
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1432
+ `default_{i}` where i is the total number of adapters being loaded.
1433
+ kwargs (`dict`, *optional*):
1434
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1435
+ """
1436
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1437
+ # it here explicitly to be able to tell that it's coming from an SDXL
1438
+ # pipeline.
1439
+
1440
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1441
+ state_dict, network_alphas = self.lora_state_dict(
1442
+ pretrained_model_name_or_path_or_dict,
1443
+ unet_config=self.unet.config,
1444
+ **kwargs,
1445
+ )
1446
+ is_correct_format = all("lora" in key for key in state_dict.keys())
1447
+ if not is_correct_format:
1448
+ raise ValueError("Invalid LoRA checkpoint.")
1449
+
1450
+ self.load_lora_into_unet(
1451
+ state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1452
+ )
1453
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1454
+ if len(text_encoder_state_dict) > 0:
1455
+ self.load_lora_into_text_encoder(
1456
+ text_encoder_state_dict,
1457
+ network_alphas=network_alphas,
1458
+ text_encoder=self.text_encoder,
1459
+ prefix="text_encoder",
1460
+ lora_scale=self.lora_scale,
1461
+ adapter_name=adapter_name,
1462
+ _pipeline=self,
1463
+ )
1464
+
1465
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1466
+ if len(text_encoder_2_state_dict) > 0:
1467
+ self.load_lora_into_text_encoder(
1468
+ text_encoder_2_state_dict,
1469
+ network_alphas=network_alphas,
1470
+ text_encoder=self.text_encoder_2,
1471
+ prefix="text_encoder_2",
1472
+ lora_scale=self.lora_scale,
1473
+ adapter_name=adapter_name,
1474
+ _pipeline=self,
1475
+ )
1476
+
1477
+ @classmethod
1478
+ def save_lora_weights(
1479
+ cls,
1480
+ save_directory: Union[str, os.PathLike],
1481
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1482
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1483
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1484
+ is_main_process: bool = True,
1485
+ weight_name: str = None,
1486
+ save_function: Callable = None,
1487
+ safe_serialization: bool = True,
1488
+ ):
1489
+ r"""
1490
+ Save the LoRA parameters corresponding to the UNet and text encoder.
1491
+
1492
+ Arguments:
1493
+ save_directory (`str` or `os.PathLike`):
1494
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
1495
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1496
+ State dict of the LoRA layers corresponding to the `unet`.
1497
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1498
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1499
+ encoder LoRA state dict because it comes from 🤗 Transformers.
1500
+ is_main_process (`bool`, *optional*, defaults to `True`):
1501
+ Whether the process calling this is the main process or not. Useful during distributed training and you
1502
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1503
+ process to avoid race conditions.
1504
+ save_function (`Callable`):
1505
+ The function to use to save the state dictionary. Useful during distributed training when you need to
1506
+ replace `torch.save` with another method. Can be configured with the environment variable
1507
+ `DIFFUSERS_SAVE_MODE`.
1508
+ safe_serialization (`bool`, *optional*, defaults to `True`):
1509
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1510
+ """
1511
+ state_dict = {}
1512
+
1513
+ def pack_weights(layers, prefix):
1514
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1515
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1516
+ return layers_state_dict
1517
+
1518
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1519
+ raise ValueError(
1520
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1521
+ )
1522
+
1523
+ if unet_lora_layers:
1524
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1525
+
1526
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1527
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1528
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1529
+
1530
+ cls.write_lora_layers(
1531
+ state_dict=state_dict,
1532
+ save_directory=save_directory,
1533
+ is_main_process=is_main_process,
1534
+ weight_name=weight_name,
1535
+ save_function=save_function,
1536
+ safe_serialization=safe_serialization,
1537
+ )
1538
+
1539
+ def _remove_text_encoder_monkey_patch(self):
1540
+ if USE_PEFT_BACKEND:
1541
+ recurse_remove_peft_layers(self.text_encoder)
1542
+ # TODO: @younesbelkada handle this in transformers side
1543
+ if getattr(self.text_encoder, "peft_config", None) is not None:
1544
+ del self.text_encoder.peft_config
1545
+ self.text_encoder._hf_peft_config_loaded = None
1546
+
1547
+ recurse_remove_peft_layers(self.text_encoder_2)
1548
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
1549
+ del self.text_encoder_2.peft_config
1550
+ self.text_encoder_2._hf_peft_config_loaded = None
1551
+ else:
1552
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1553
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)