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

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