diffusers 0.29.2__py3-none-any.whl → 0.30.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. diffusers/__init__.py +94 -3
  2. diffusers/commands/env.py +1 -5
  3. diffusers/configuration_utils.py +4 -9
  4. diffusers/dependency_versions_table.py +2 -2
  5. diffusers/image_processor.py +1 -2
  6. diffusers/loaders/__init__.py +17 -2
  7. diffusers/loaders/ip_adapter.py +10 -7
  8. diffusers/loaders/lora_base.py +752 -0
  9. diffusers/loaders/lora_pipeline.py +2252 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +3 -14
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +293 -8
  14. diffusers/loaders/textual_inversion.py +1 -6
  15. diffusers/loaders/unet.py +23 -208
  16. diffusers/models/__init__.py +20 -0
  17. diffusers/models/activations.py +22 -0
  18. diffusers/models/attention.py +386 -7
  19. diffusers/models/attention_processor.py +1937 -629
  20. diffusers/models/autoencoders/__init__.py +2 -0
  21. diffusers/models/autoencoders/autoencoder_kl.py +14 -3
  22. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1271 -0
  23. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  24. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  25. diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
  26. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  27. diffusers/models/autoencoders/vq_model.py +4 -4
  28. diffusers/models/controlnet.py +2 -3
  29. diffusers/models/controlnet_hunyuan.py +401 -0
  30. diffusers/models/controlnet_sd3.py +11 -11
  31. diffusers/models/controlnet_sparsectrl.py +789 -0
  32. diffusers/models/controlnet_xs.py +40 -10
  33. diffusers/models/downsampling.py +68 -0
  34. diffusers/models/embeddings.py +403 -36
  35. diffusers/models/model_loading_utils.py +1 -3
  36. diffusers/models/modeling_flax_utils.py +1 -6
  37. diffusers/models/modeling_utils.py +4 -16
  38. diffusers/models/normalization.py +203 -12
  39. diffusers/models/transformers/__init__.py +6 -0
  40. diffusers/models/transformers/auraflow_transformer_2d.py +543 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +485 -0
  42. diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
  43. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  44. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  45. diffusers/models/transformers/pixart_transformer_2d.py +102 -1
  46. diffusers/models/transformers/prior_transformer.py +1 -1
  47. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  48. diffusers/models/transformers/transformer_flux.py +455 -0
  49. diffusers/models/transformers/transformer_sd3.py +18 -4
  50. diffusers/models/unets/unet_1d_blocks.py +1 -1
  51. diffusers/models/unets/unet_2d_condition.py +8 -1
  52. diffusers/models/unets/unet_3d_blocks.py +51 -920
  53. diffusers/models/unets/unet_3d_condition.py +4 -1
  54. diffusers/models/unets/unet_i2vgen_xl.py +4 -1
  55. diffusers/models/unets/unet_kandinsky3.py +1 -1
  56. diffusers/models/unets/unet_motion_model.py +1330 -84
  57. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  58. diffusers/models/unets/unet_stable_cascade.py +1 -3
  59. diffusers/models/unets/uvit_2d.py +1 -1
  60. diffusers/models/upsampling.py +64 -0
  61. diffusers/models/vq_model.py +8 -4
  62. diffusers/optimization.py +1 -1
  63. diffusers/pipelines/__init__.py +100 -3
  64. diffusers/pipelines/animatediff/__init__.py +4 -0
  65. diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
  66. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
  70. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  71. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
  72. diffusers/pipelines/aura_flow/__init__.py +48 -0
  73. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
  74. diffusers/pipelines/auto_pipeline.py +97 -19
  75. diffusers/pipelines/cogvideo/__init__.py +48 -0
  76. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +746 -0
  77. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  78. diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
  79. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
  80. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
  81. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
  82. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
  83. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
  84. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  85. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  86. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
  87. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
  88. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
  90. diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
  91. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
  96. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
  97. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
  98. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  100. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
  101. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
  103. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  104. diffusers/pipelines/flux/__init__.py +47 -0
  105. diffusers/pipelines/flux/pipeline_flux.py +749 -0
  106. diffusers/pipelines/flux/pipeline_output.py +21 -0
  107. diffusers/pipelines/free_init_utils.py +2 -0
  108. diffusers/pipelines/free_noise_utils.py +236 -0
  109. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
  110. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
  111. diffusers/pipelines/kolors/__init__.py +54 -0
  112. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  113. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
  114. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  115. diffusers/pipelines/kolors/text_encoder.py +889 -0
  116. diffusers/pipelines/kolors/tokenizer.py +334 -0
  117. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
  118. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
  119. diffusers/pipelines/latte/__init__.py +48 -0
  120. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  121. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
  122. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
  123. diffusers/pipelines/lumina/__init__.py +48 -0
  124. diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
  125. diffusers/pipelines/pag/__init__.py +67 -0
  126. diffusers/pipelines/pag/pag_utils.py +237 -0
  127. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
  128. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
  129. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
  130. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  131. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
  132. diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
  133. diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
  134. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
  135. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
  136. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
  137. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
  138. diffusers/pipelines/pia/pipeline_pia.py +30 -37
  139. diffusers/pipelines/pipeline_flax_utils.py +4 -9
  140. diffusers/pipelines/pipeline_loading_utils.py +0 -3
  141. diffusers/pipelines/pipeline_utils.py +2 -14
  142. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
  143. diffusers/pipelines/stable_audio/__init__.py +50 -0
  144. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  145. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
  146. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
  147. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
  151. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
  152. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
  153. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
  154. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
  155. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
  156. diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
  157. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
  158. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
  160. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
  161. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
  162. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
  163. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
  164. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
  165. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
  166. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
  167. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
  168. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
  171. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
  172. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
  175. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
  179. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  180. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  181. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
  182. diffusers/schedulers/__init__.py +8 -0
  183. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  184. diffusers/schedulers/scheduling_ddim.py +1 -1
  185. diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
  186. diffusers/schedulers/scheduling_ddpm.py +1 -1
  187. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
  188. diffusers/schedulers/scheduling_deis_multistep.py +2 -2
  189. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  190. diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
  191. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
  192. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
  193. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
  194. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
  195. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
  196. diffusers/schedulers/scheduling_ipndm.py +1 -1
  197. diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
  198. diffusers/schedulers/scheduling_utils.py +1 -3
  199. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  200. diffusers/training_utils.py +99 -14
  201. diffusers/utils/__init__.py +2 -2
  202. diffusers/utils/dummy_pt_objects.py +210 -0
  203. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  204. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  205. diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
  206. diffusers/utils/dynamic_modules_utils.py +1 -11
  207. diffusers/utils/export_utils.py +50 -6
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +37 -15
  210. diffusers/utils/loading_utils.py +80 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/WHEEL +1 -1
  215. diffusers/loaders/autoencoder.py +0 -146
  216. diffusers/loaders/controlnet.py +0 -136
  217. diffusers/loaders/lora.py +0 -1728
  218. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
diffusers/loaders/lora.py DELETED
@@ -1,1728 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import copy
15
- import inspect
16
- import os
17
- from pathlib import Path
18
- from typing import Callable, Dict, List, Optional, Union
19
-
20
- import safetensors
21
- import torch
22
- from huggingface_hub import model_info
23
- from huggingface_hub.constants import HF_HUB_OFFLINE
24
- from huggingface_hub.utils import validate_hf_hub_args
25
- from torch import nn
26
-
27
- from ..models.modeling_utils import load_state_dict
28
- from ..utils import (
29
- USE_PEFT_BACKEND,
30
- _get_model_file,
31
- convert_state_dict_to_diffusers,
32
- convert_state_dict_to_peft,
33
- delete_adapter_layers,
34
- get_adapter_name,
35
- get_peft_kwargs,
36
- is_accelerate_available,
37
- is_peft_version,
38
- is_transformers_available,
39
- logging,
40
- recurse_remove_peft_layers,
41
- scale_lora_layers,
42
- set_adapter_layers,
43
- set_weights_and_activate_adapters,
44
- )
45
- from .lora_conversion_utils import _convert_non_diffusers_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
46
-
47
-
48
- if is_transformers_available():
49
- from transformers import PreTrainedModel
50
-
51
- from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
52
-
53
- if is_accelerate_available():
54
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
55
-
56
- logger = logging.get_logger(__name__)
57
-
58
- TEXT_ENCODER_NAME = "text_encoder"
59
- UNET_NAME = "unet"
60
- TRANSFORMER_NAME = "transformer"
61
-
62
- LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
63
- LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
64
-
65
- 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."
66
-
67
-
68
- class LoraLoaderMixin:
69
- r"""
70
- Load LoRA layers into [`UNet2DConditionModel`] and
71
- [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
72
- """
73
-
74
- text_encoder_name = TEXT_ENCODER_NAME
75
- unet_name = UNET_NAME
76
- transformer_name = TRANSFORMER_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
- if not USE_PEFT_BACKEND:
106
- raise ValueError("PEFT backend is required for this method.")
107
-
108
- # if a dict is passed, copy it instead of modifying it inplace
109
- if isinstance(pretrained_model_name_or_path_or_dict, dict):
110
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
111
-
112
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
113
- state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
114
-
115
- is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
116
- if not is_correct_format:
117
- raise ValueError("Invalid LoRA checkpoint.")
118
-
119
- self.load_lora_into_unet(
120
- state_dict,
121
- network_alphas=network_alphas,
122
- unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
123
- adapter_name=adapter_name,
124
- _pipeline=self,
125
- )
126
- self.load_lora_into_text_encoder(
127
- state_dict,
128
- network_alphas=network_alphas,
129
- text_encoder=getattr(self, self.text_encoder_name)
130
- if not hasattr(self, "text_encoder")
131
- else self.text_encoder,
132
- lora_scale=self.lora_scale,
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:
173
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
174
- of Diffusers.
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
- weight_name (`str`, *optional*, defaults to None):
190
- Name of the serialized state dict file.
191
- """
192
- # Load the main state dict first which has the LoRA layers for either of
193
- # UNet and text encoder or both.
194
- cache_dir = kwargs.pop("cache_dir", None)
195
- force_download = kwargs.pop("force_download", False)
196
- resume_download = kwargs.pop("resume_download", None)
197
- proxies = kwargs.pop("proxies", None)
198
- local_files_only = kwargs.pop("local_files_only", None)
199
- token = kwargs.pop("token", None)
200
- revision = kwargs.pop("revision", None)
201
- subfolder = kwargs.pop("subfolder", None)
202
- weight_name = kwargs.pop("weight_name", None)
203
- unet_config = kwargs.pop("unet_config", None)
204
- use_safetensors = kwargs.pop("use_safetensors", None)
205
-
206
- allow_pickle = False
207
- if use_safetensors is None:
208
- use_safetensors = True
209
- allow_pickle = True
210
-
211
- user_agent = {
212
- "file_type": "attn_procs_weights",
213
- "framework": "pytorch",
214
- }
215
-
216
- model_file = None
217
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
218
- # Let's first try to load .safetensors weights
219
- if (use_safetensors and weight_name is None) or (
220
- weight_name is not None and weight_name.endswith(".safetensors")
221
- ):
222
- try:
223
- # Here we're relaxing the loading check to enable more Inference API
224
- # friendliness where sometimes, it's not at all possible to automatically
225
- # determine `weight_name`.
226
- if weight_name is None:
227
- weight_name = cls._best_guess_weight_name(
228
- pretrained_model_name_or_path_or_dict,
229
- file_extension=".safetensors",
230
- local_files_only=local_files_only,
231
- )
232
- model_file = _get_model_file(
233
- pretrained_model_name_or_path_or_dict,
234
- weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
235
- cache_dir=cache_dir,
236
- force_download=force_download,
237
- resume_download=resume_download,
238
- proxies=proxies,
239
- local_files_only=local_files_only,
240
- token=token,
241
- revision=revision,
242
- subfolder=subfolder,
243
- user_agent=user_agent,
244
- )
245
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
246
- except (IOError, safetensors.SafetensorError) as e:
247
- if not allow_pickle:
248
- raise e
249
- # try loading non-safetensors weights
250
- model_file = None
251
- pass
252
-
253
- if model_file is None:
254
- if weight_name is None:
255
- weight_name = cls._best_guess_weight_name(
256
- pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
257
- )
258
- model_file = _get_model_file(
259
- pretrained_model_name_or_path_or_dict,
260
- weights_name=weight_name or LORA_WEIGHT_NAME,
261
- cache_dir=cache_dir,
262
- force_download=force_download,
263
- resume_download=resume_download,
264
- proxies=proxies,
265
- local_files_only=local_files_only,
266
- token=token,
267
- revision=revision,
268
- subfolder=subfolder,
269
- user_agent=user_agent,
270
- )
271
- state_dict = load_state_dict(model_file)
272
- else:
273
- state_dict = pretrained_model_name_or_path_or_dict
274
-
275
- network_alphas = None
276
- # TODO: replace it with a method from `state_dict_utils`
277
- if all(
278
- (
279
- k.startswith("lora_te_")
280
- or k.startswith("lora_unet_")
281
- or k.startswith("lora_te1_")
282
- or k.startswith("lora_te2_")
283
- )
284
- for k in state_dict.keys()
285
- ):
286
- # Map SDXL blocks correctly.
287
- if unet_config is not None:
288
- # use unet config to remap block numbers
289
- state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
290
- state_dict, network_alphas = _convert_non_diffusers_lora_to_diffusers(state_dict)
291
-
292
- return state_dict, network_alphas
293
-
294
- @classmethod
295
- def _best_guess_weight_name(
296
- cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
297
- ):
298
- if local_files_only or HF_HUB_OFFLINE:
299
- raise ValueError("When using the offline mode, you must specify a `weight_name`.")
300
-
301
- targeted_files = []
302
-
303
- if os.path.isfile(pretrained_model_name_or_path_or_dict):
304
- return
305
- elif os.path.isdir(pretrained_model_name_or_path_or_dict):
306
- targeted_files = [
307
- f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
308
- ]
309
- else:
310
- files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
311
- targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
312
- if len(targeted_files) == 0:
313
- return
314
-
315
- # "scheduler" does not correspond to a LoRA checkpoint.
316
- # "optimizer" does not correspond to a LoRA checkpoint
317
- # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
318
- unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
319
- targeted_files = list(
320
- filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
321
- )
322
-
323
- if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
324
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
325
- elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
326
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
327
-
328
- if len(targeted_files) > 1:
329
- raise ValueError(
330
- 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}."
331
- )
332
- weight_name = targeted_files[0]
333
- return weight_name
334
-
335
- @classmethod
336
- def _optionally_disable_offloading(cls, _pipeline):
337
- """
338
- Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
339
-
340
- Args:
341
- _pipeline (`DiffusionPipeline`):
342
- The pipeline to disable offloading for.
343
-
344
- Returns:
345
- tuple:
346
- A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
347
- """
348
- is_model_cpu_offload = False
349
- is_sequential_cpu_offload = False
350
-
351
- if _pipeline is not None and _pipeline.hf_device_map is None:
352
- for _, component in _pipeline.components.items():
353
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
354
- if not is_model_cpu_offload:
355
- is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
356
- if not is_sequential_cpu_offload:
357
- is_sequential_cpu_offload = (
358
- isinstance(component._hf_hook, AlignDevicesHook)
359
- or hasattr(component._hf_hook, "hooks")
360
- and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
361
- )
362
-
363
- logger.info(
364
- "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."
365
- )
366
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
367
-
368
- return (is_model_cpu_offload, is_sequential_cpu_offload)
369
-
370
- @classmethod
371
- def load_lora_into_unet(cls, state_dict, network_alphas, unet, adapter_name=None, _pipeline=None):
372
- """
373
- This will load the LoRA layers specified in `state_dict` into `unet`.
374
-
375
- Parameters:
376
- state_dict (`dict`):
377
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
378
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
379
- encoder lora layers.
380
- network_alphas (`Dict[str, float]`):
381
- The value of the network alpha used for stable learning and preventing underflow. This value has the
382
- same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
383
- link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
384
- unet (`UNet2DConditionModel`):
385
- The UNet model to load the LoRA layers into.
386
- adapter_name (`str`, *optional*):
387
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
388
- `default_{i}` where i is the total number of adapters being loaded.
389
- """
390
- if not USE_PEFT_BACKEND:
391
- raise ValueError("PEFT backend is required for this method.")
392
-
393
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
394
- # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
395
- # their prefixes.
396
- keys = list(state_dict.keys())
397
- only_text_encoder = all(key.startswith(cls.text_encoder_name) for key in keys)
398
- if not only_text_encoder:
399
- # Load the layers corresponding to UNet.
400
- logger.info(f"Loading {cls.unet_name}.")
401
- unet.load_attn_procs(
402
- state_dict, network_alphas=network_alphas, adapter_name=adapter_name, _pipeline=_pipeline
403
- )
404
-
405
- @classmethod
406
- def load_lora_into_text_encoder(
407
- cls,
408
- state_dict,
409
- network_alphas,
410
- text_encoder,
411
- prefix=None,
412
- lora_scale=1.0,
413
- adapter_name=None,
414
- _pipeline=None,
415
- ):
416
- """
417
- This will load the LoRA layers specified in `state_dict` into `text_encoder`
418
-
419
- Parameters:
420
- state_dict (`dict`):
421
- A standard state dict containing the lora layer parameters. The key should be prefixed with an
422
- additional `text_encoder` to distinguish between unet lora layers.
423
- network_alphas (`Dict[str, float]`):
424
- See `LoRALinearLayer` for more details.
425
- text_encoder (`CLIPTextModel`):
426
- The text encoder model to load the LoRA layers into.
427
- prefix (`str`):
428
- Expected prefix of the `text_encoder` in the `state_dict`.
429
- lora_scale (`float`):
430
- How much to scale the output of the lora linear layer before it is added with the output of the regular
431
- lora layer.
432
- adapter_name (`str`, *optional*):
433
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
434
- `default_{i}` where i is the total number of adapters being loaded.
435
- """
436
- if not USE_PEFT_BACKEND:
437
- raise ValueError("PEFT backend is required for this method.")
438
-
439
- from peft import LoraConfig
440
-
441
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
442
- # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
443
- # their prefixes.
444
- keys = list(state_dict.keys())
445
- prefix = cls.text_encoder_name if prefix is None else prefix
446
-
447
- # Safe prefix to check with.
448
- if any(cls.text_encoder_name in key for key in keys):
449
- # Load the layers corresponding to text encoder and make necessary adjustments.
450
- text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
451
- text_encoder_lora_state_dict = {
452
- k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
453
- }
454
-
455
- if len(text_encoder_lora_state_dict) > 0:
456
- logger.info(f"Loading {prefix}.")
457
- rank = {}
458
- text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
459
-
460
- # convert state dict
461
- text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
462
-
463
- for name, _ in text_encoder_attn_modules(text_encoder):
464
- rank_key = f"{name}.out_proj.lora_B.weight"
465
- rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
466
-
467
- patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
468
- if patch_mlp:
469
- for name, _ in text_encoder_mlp_modules(text_encoder):
470
- rank_key_fc1 = f"{name}.fc1.lora_B.weight"
471
- rank_key_fc2 = f"{name}.fc2.lora_B.weight"
472
-
473
- rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
474
- rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
475
-
476
- if network_alphas is not None:
477
- alpha_keys = [
478
- k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
479
- ]
480
- network_alphas = {
481
- k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
482
- }
483
-
484
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
485
- if "use_dora" in lora_config_kwargs:
486
- if lora_config_kwargs["use_dora"]:
487
- if is_peft_version("<", "0.9.0"):
488
- raise ValueError(
489
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
490
- )
491
- else:
492
- if is_peft_version("<", "0.9.0"):
493
- lora_config_kwargs.pop("use_dora")
494
- lora_config = LoraConfig(**lora_config_kwargs)
495
-
496
- # adapter_name
497
- if adapter_name is None:
498
- adapter_name = get_adapter_name(text_encoder)
499
-
500
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
501
-
502
- # inject LoRA layers and load the state dict
503
- # in transformers we automatically check whether the adapter name is already in use or not
504
- text_encoder.load_adapter(
505
- adapter_name=adapter_name,
506
- adapter_state_dict=text_encoder_lora_state_dict,
507
- peft_config=lora_config,
508
- )
509
-
510
- # scale LoRA layers with `lora_scale`
511
- scale_lora_layers(text_encoder, weight=lora_scale)
512
-
513
- text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
514
-
515
- # Offload back.
516
- if is_model_cpu_offload:
517
- _pipeline.enable_model_cpu_offload()
518
- elif is_sequential_cpu_offload:
519
- _pipeline.enable_sequential_cpu_offload()
520
- # Unsafe code />
521
-
522
- @classmethod
523
- def load_lora_into_transformer(cls, state_dict, network_alphas, transformer, adapter_name=None, _pipeline=None):
524
- """
525
- This will load the LoRA layers specified in `state_dict` into `transformer`.
526
-
527
- Parameters:
528
- state_dict (`dict`):
529
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
530
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
531
- encoder lora layers.
532
- network_alphas (`Dict[str, float]`):
533
- See `LoRALinearLayer` for more details.
534
- unet (`UNet2DConditionModel`):
535
- The UNet model to load the LoRA layers into.
536
- adapter_name (`str`, *optional*):
537
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
538
- `default_{i}` where i is the total number of adapters being loaded.
539
- """
540
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
541
-
542
- keys = list(state_dict.keys())
543
-
544
- transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
545
- state_dict = {
546
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
547
- }
548
-
549
- if network_alphas is not None:
550
- alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
551
- network_alphas = {
552
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
553
- }
554
-
555
- if len(state_dict.keys()) > 0:
556
- if adapter_name in getattr(transformer, "peft_config", {}):
557
- raise ValueError(
558
- f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
559
- )
560
-
561
- rank = {}
562
- for key, val in state_dict.items():
563
- if "lora_B" in key:
564
- rank[key] = val.shape[1]
565
-
566
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
567
- if "use_dora" in lora_config_kwargs:
568
- if lora_config_kwargs["use_dora"] and is_peft_version("<", "0.9.0"):
569
- raise ValueError(
570
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
571
- )
572
- else:
573
- lora_config_kwargs.pop("use_dora")
574
- lora_config = LoraConfig(**lora_config_kwargs)
575
-
576
- # adapter_name
577
- if adapter_name is None:
578
- adapter_name = get_adapter_name(transformer)
579
-
580
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
581
- # otherwise loading LoRA weights will lead to an error
582
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
583
-
584
- inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
585
- incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
586
-
587
- if incompatible_keys is not None:
588
- # check only for unexpected keys
589
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
590
- if unexpected_keys:
591
- logger.warning(
592
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
593
- f" {unexpected_keys}. "
594
- )
595
-
596
- # Offload back.
597
- if is_model_cpu_offload:
598
- _pipeline.enable_model_cpu_offload()
599
- elif is_sequential_cpu_offload:
600
- _pipeline.enable_sequential_cpu_offload()
601
- # Unsafe code />
602
-
603
- @property
604
- def lora_scale(self) -> float:
605
- # property function that returns the lora scale which can be set at run time by the pipeline.
606
- # if _lora_scale has not been set, return 1
607
- return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
608
-
609
- def _remove_text_encoder_monkey_patch(self):
610
- remove_method = recurse_remove_peft_layers
611
- if hasattr(self, "text_encoder"):
612
- remove_method(self.text_encoder)
613
- # In case text encoder have no Lora attached
614
- if getattr(self.text_encoder, "peft_config", None) is not None:
615
- del self.text_encoder.peft_config
616
- self.text_encoder._hf_peft_config_loaded = None
617
-
618
- if hasattr(self, "text_encoder_2"):
619
- remove_method(self.text_encoder_2)
620
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
621
- del self.text_encoder_2.peft_config
622
- self.text_encoder_2._hf_peft_config_loaded = None
623
-
624
- @classmethod
625
- def save_lora_weights(
626
- cls,
627
- save_directory: Union[str, os.PathLike],
628
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
629
- text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
630
- transformer_lora_layers: Dict[str, torch.nn.Module] = None,
631
- is_main_process: bool = True,
632
- weight_name: str = None,
633
- save_function: Callable = None,
634
- safe_serialization: bool = True,
635
- ):
636
- r"""
637
- Save the LoRA parameters corresponding to the UNet and text encoder.
638
-
639
- Arguments:
640
- save_directory (`str` or `os.PathLike`):
641
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
642
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
643
- State dict of the LoRA layers corresponding to the `unet`.
644
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
645
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
646
- encoder LoRA state dict because it comes from 🤗 Transformers.
647
- is_main_process (`bool`, *optional*, defaults to `True`):
648
- Whether the process calling this is the main process or not. Useful during distributed training and you
649
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
650
- process to avoid race conditions.
651
- save_function (`Callable`):
652
- The function to use to save the state dictionary. Useful during distributed training when you need to
653
- replace `torch.save` with another method. Can be configured with the environment variable
654
- `DIFFUSERS_SAVE_MODE`.
655
- safe_serialization (`bool`, *optional*, defaults to `True`):
656
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
657
- """
658
- state_dict = {}
659
-
660
- def pack_weights(layers, prefix):
661
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
662
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
663
- return layers_state_dict
664
-
665
- if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
666
- raise ValueError(
667
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
668
- )
669
-
670
- if unet_lora_layers:
671
- state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
672
-
673
- if text_encoder_lora_layers:
674
- state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
675
-
676
- if transformer_lora_layers:
677
- state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
678
-
679
- # Save the model
680
- cls.write_lora_layers(
681
- state_dict=state_dict,
682
- save_directory=save_directory,
683
- is_main_process=is_main_process,
684
- weight_name=weight_name,
685
- save_function=save_function,
686
- safe_serialization=safe_serialization,
687
- )
688
-
689
- @staticmethod
690
- def write_lora_layers(
691
- state_dict: Dict[str, torch.Tensor],
692
- save_directory: str,
693
- is_main_process: bool,
694
- weight_name: str,
695
- save_function: Callable,
696
- safe_serialization: bool,
697
- ):
698
- if os.path.isfile(save_directory):
699
- logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
700
- return
701
-
702
- if save_function is None:
703
- if safe_serialization:
704
-
705
- def save_function(weights, filename):
706
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
707
-
708
- else:
709
- save_function = torch.save
710
-
711
- os.makedirs(save_directory, exist_ok=True)
712
-
713
- if weight_name is None:
714
- if safe_serialization:
715
- weight_name = LORA_WEIGHT_NAME_SAFE
716
- else:
717
- weight_name = LORA_WEIGHT_NAME
718
-
719
- save_path = Path(save_directory, weight_name).as_posix()
720
- save_function(state_dict, save_path)
721
- logger.info(f"Model weights saved in {save_path}")
722
-
723
- def unload_lora_weights(self):
724
- """
725
- Unloads the LoRA parameters.
726
-
727
- Examples:
728
-
729
- ```python
730
- >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
731
- >>> pipeline.unload_lora_weights()
732
- >>> ...
733
- ```
734
- """
735
- if not USE_PEFT_BACKEND:
736
- raise ValueError("PEFT backend is required for this method.")
737
-
738
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
739
- unet.unload_lora()
740
-
741
- # Safe to call the following regardless of LoRA.
742
- self._remove_text_encoder_monkey_patch()
743
-
744
- def fuse_lora(
745
- self,
746
- fuse_unet: bool = True,
747
- fuse_text_encoder: bool = True,
748
- lora_scale: float = 1.0,
749
- safe_fusing: bool = False,
750
- adapter_names: Optional[List[str]] = None,
751
- ):
752
- r"""
753
- Fuses the LoRA parameters into the original parameters of the corresponding blocks.
754
-
755
- <Tip warning={true}>
756
-
757
- This is an experimental API.
758
-
759
- </Tip>
760
-
761
- Args:
762
- fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
763
- fuse_text_encoder (`bool`, defaults to `True`):
764
- Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
765
- LoRA parameters then it won't have any effect.
766
- lora_scale (`float`, defaults to 1.0):
767
- Controls how much to influence the outputs with the LoRA parameters.
768
- safe_fusing (`bool`, defaults to `False`):
769
- Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
770
- adapter_names (`List[str]`, *optional*):
771
- Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
772
-
773
- Example:
774
-
775
- ```py
776
- from diffusers import DiffusionPipeline
777
- import torch
778
-
779
- pipeline = DiffusionPipeline.from_pretrained(
780
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
781
- ).to("cuda")
782
- pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
783
- pipeline.fuse_lora(lora_scale=0.7)
784
- ```
785
- """
786
- from peft.tuners.tuners_utils import BaseTunerLayer
787
-
788
- if fuse_unet or fuse_text_encoder:
789
- self.num_fused_loras += 1
790
- if self.num_fused_loras > 1:
791
- logger.warning(
792
- "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.",
793
- )
794
-
795
- if fuse_unet:
796
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
797
- unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
798
-
799
- def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
800
- merge_kwargs = {"safe_merge": safe_fusing}
801
-
802
- for module in text_encoder.modules():
803
- if isinstance(module, BaseTunerLayer):
804
- if lora_scale != 1.0:
805
- module.scale_layer(lora_scale)
806
-
807
- # For BC with previous PEFT versions, we need to check the signature
808
- # of the `merge` method to see if it supports the `adapter_names` argument.
809
- supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
810
- if "adapter_names" in supported_merge_kwargs:
811
- merge_kwargs["adapter_names"] = adapter_names
812
- elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
813
- raise ValueError(
814
- "The `adapter_names` argument is not supported with your PEFT version. "
815
- "Please upgrade to the latest version of PEFT. `pip install -U peft`"
816
- )
817
-
818
- module.merge(**merge_kwargs)
819
-
820
- if fuse_text_encoder:
821
- if hasattr(self, "text_encoder"):
822
- fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
823
- if hasattr(self, "text_encoder_2"):
824
- fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
825
-
826
- def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
827
- r"""
828
- Reverses the effect of
829
- [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
830
-
831
- <Tip warning={true}>
832
-
833
- This is an experimental API.
834
-
835
- </Tip>
836
-
837
- Args:
838
- unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
839
- unfuse_text_encoder (`bool`, defaults to `True`):
840
- Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
841
- LoRA parameters then it won't have any effect.
842
- """
843
- from peft.tuners.tuners_utils import BaseTunerLayer
844
-
845
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
846
- if unfuse_unet:
847
- for module in unet.modules():
848
- if isinstance(module, BaseTunerLayer):
849
- module.unmerge()
850
-
851
- def unfuse_text_encoder_lora(text_encoder):
852
- for module in text_encoder.modules():
853
- if isinstance(module, BaseTunerLayer):
854
- module.unmerge()
855
-
856
- if unfuse_text_encoder:
857
- if hasattr(self, "text_encoder"):
858
- unfuse_text_encoder_lora(self.text_encoder)
859
- if hasattr(self, "text_encoder_2"):
860
- unfuse_text_encoder_lora(self.text_encoder_2)
861
-
862
- self.num_fused_loras -= 1
863
-
864
- def set_adapters_for_text_encoder(
865
- self,
866
- adapter_names: Union[List[str], str],
867
- text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
868
- text_encoder_weights: Optional[Union[float, List[float], List[None]]] = None,
869
- ):
870
- """
871
- Sets the adapter layers for the text encoder.
872
-
873
- Args:
874
- adapter_names (`List[str]` or `str`):
875
- The names of the adapters to use.
876
- text_encoder (`torch.nn.Module`, *optional*):
877
- The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
878
- attribute.
879
- text_encoder_weights (`List[float]`, *optional*):
880
- The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
881
- """
882
- if not USE_PEFT_BACKEND:
883
- raise ValueError("PEFT backend is required for this method.")
884
-
885
- def process_weights(adapter_names, weights):
886
- # Expand weights into a list, one entry per adapter
887
- # e.g. for 2 adapters: 7 -> [7,7] ; [3, None] -> [3, None]
888
- if not isinstance(weights, list):
889
- weights = [weights] * len(adapter_names)
890
-
891
- if len(adapter_names) != len(weights):
892
- raise ValueError(
893
- f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
894
- )
895
-
896
- # Set None values to default of 1.0
897
- # e.g. [7,7] -> [7,7] ; [3, None] -> [3,1]
898
- weights = [w if w is not None else 1.0 for w in weights]
899
-
900
- return weights
901
-
902
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
903
- text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
904
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
905
- if text_encoder is None:
906
- raise ValueError(
907
- "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
908
- )
909
- set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
910
-
911
- def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
912
- """
913
- Disables the LoRA layers for the text encoder.
914
-
915
- Args:
916
- text_encoder (`torch.nn.Module`, *optional*):
917
- The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
918
- `text_encoder` attribute.
919
- """
920
- if not USE_PEFT_BACKEND:
921
- raise ValueError("PEFT backend is required for this method.")
922
-
923
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
924
- if text_encoder is None:
925
- raise ValueError("Text Encoder not found.")
926
- set_adapter_layers(text_encoder, enabled=False)
927
-
928
- def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
929
- """
930
- Enables the LoRA layers for the text encoder.
931
-
932
- Args:
933
- text_encoder (`torch.nn.Module`, *optional*):
934
- The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
935
- attribute.
936
- """
937
- if not USE_PEFT_BACKEND:
938
- raise ValueError("PEFT backend is required for this method.")
939
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
940
- if text_encoder is None:
941
- raise ValueError("Text Encoder not found.")
942
- set_adapter_layers(self.text_encoder, enabled=True)
943
-
944
- def set_adapters(
945
- self,
946
- adapter_names: Union[List[str], str],
947
- adapter_weights: Optional[Union[float, Dict, List[float], List[Dict]]] = None,
948
- ):
949
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
950
-
951
- adapter_weights = copy.deepcopy(adapter_weights)
952
-
953
- # Expand weights into a list, one entry per adapter
954
- if not isinstance(adapter_weights, list):
955
- adapter_weights = [adapter_weights] * len(adapter_names)
956
-
957
- if len(adapter_names) != len(adapter_weights):
958
- raise ValueError(
959
- f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(adapter_weights)}"
960
- )
961
-
962
- # Decompose weights into weights for unet, text_encoder and text_encoder_2
963
- unet_lora_weights, text_encoder_lora_weights, text_encoder_2_lora_weights = [], [], []
964
-
965
- list_adapters = self.get_list_adapters() # eg {"unet": ["adapter1", "adapter2"], "text_encoder": ["adapter2"]}
966
- all_adapters = {
967
- adapter for adapters in list_adapters.values() for adapter in adapters
968
- } # eg ["adapter1", "adapter2"]
969
- invert_list_adapters = {
970
- adapter: [part for part, adapters in list_adapters.items() if adapter in adapters]
971
- for adapter in all_adapters
972
- } # eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]}
973
-
974
- for adapter_name, weights in zip(adapter_names, adapter_weights):
975
- if isinstance(weights, dict):
976
- unet_lora_weight = weights.pop("unet", None)
977
- text_encoder_lora_weight = weights.pop("text_encoder", None)
978
- text_encoder_2_lora_weight = weights.pop("text_encoder_2", None)
979
-
980
- if len(weights) > 0:
981
- raise ValueError(
982
- f"Got invalid key '{weights.keys()}' in lora weight dict for adapter {adapter_name}."
983
- )
984
-
985
- if text_encoder_2_lora_weight is not None and not hasattr(self, "text_encoder_2"):
986
- logger.warning(
987
- "Lora weight dict contains text_encoder_2 weights but will be ignored because pipeline does not have text_encoder_2."
988
- )
989
-
990
- # warn if adapter doesn't have parts specified by adapter_weights
991
- for part_weight, part_name in zip(
992
- [unet_lora_weight, text_encoder_lora_weight, text_encoder_2_lora_weight],
993
- ["unet", "text_encoder", "text_encoder_2"],
994
- ):
995
- if part_weight is not None and part_name not in invert_list_adapters[adapter_name]:
996
- logger.warning(
997
- f"Lora weight dict for adapter '{adapter_name}' contains {part_name}, but this will be ignored because {adapter_name} does not contain weights for {part_name}. Valid parts for {adapter_name} are: {invert_list_adapters[adapter_name]}."
998
- )
999
-
1000
- else:
1001
- unet_lora_weight = weights
1002
- text_encoder_lora_weight = weights
1003
- text_encoder_2_lora_weight = weights
1004
-
1005
- unet_lora_weights.append(unet_lora_weight)
1006
- text_encoder_lora_weights.append(text_encoder_lora_weight)
1007
- text_encoder_2_lora_weights.append(text_encoder_2_lora_weight)
1008
-
1009
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1010
- # Handle the UNET
1011
- unet.set_adapters(adapter_names, unet_lora_weights)
1012
-
1013
- # Handle the Text Encoder
1014
- if hasattr(self, "text_encoder"):
1015
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, text_encoder_lora_weights)
1016
- if hasattr(self, "text_encoder_2"):
1017
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, text_encoder_2_lora_weights)
1018
-
1019
- def disable_lora(self):
1020
- if not USE_PEFT_BACKEND:
1021
- raise ValueError("PEFT backend is required for this method.")
1022
-
1023
- # Disable unet adapters
1024
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1025
- unet.disable_lora()
1026
-
1027
- # Disable text encoder adapters
1028
- if hasattr(self, "text_encoder"):
1029
- self.disable_lora_for_text_encoder(self.text_encoder)
1030
- if hasattr(self, "text_encoder_2"):
1031
- self.disable_lora_for_text_encoder(self.text_encoder_2)
1032
-
1033
- def enable_lora(self):
1034
- if not USE_PEFT_BACKEND:
1035
- raise ValueError("PEFT backend is required for this method.")
1036
-
1037
- # Enable unet adapters
1038
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1039
- unet.enable_lora()
1040
-
1041
- # Enable text encoder adapters
1042
- if hasattr(self, "text_encoder"):
1043
- self.enable_lora_for_text_encoder(self.text_encoder)
1044
- if hasattr(self, "text_encoder_2"):
1045
- self.enable_lora_for_text_encoder(self.text_encoder_2)
1046
-
1047
- def delete_adapters(self, adapter_names: Union[List[str], str]):
1048
- """
1049
- Args:
1050
- Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1051
- adapter_names (`Union[List[str], str]`):
1052
- The names of the adapter to delete. Can be a single string or a list of strings
1053
- """
1054
- if not USE_PEFT_BACKEND:
1055
- raise ValueError("PEFT backend is required for this method.")
1056
-
1057
- if isinstance(adapter_names, str):
1058
- adapter_names = [adapter_names]
1059
-
1060
- # Delete unet adapters
1061
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1062
- unet.delete_adapters(adapter_names)
1063
-
1064
- for adapter_name in adapter_names:
1065
- # Delete text encoder adapters
1066
- if hasattr(self, "text_encoder"):
1067
- delete_adapter_layers(self.text_encoder, adapter_name)
1068
- if hasattr(self, "text_encoder_2"):
1069
- delete_adapter_layers(self.text_encoder_2, adapter_name)
1070
-
1071
- def get_active_adapters(self) -> List[str]:
1072
- """
1073
- Gets the list of the current active adapters.
1074
-
1075
- Example:
1076
-
1077
- ```python
1078
- from diffusers import DiffusionPipeline
1079
-
1080
- pipeline = DiffusionPipeline.from_pretrained(
1081
- "stabilityai/stable-diffusion-xl-base-1.0",
1082
- ).to("cuda")
1083
- pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1084
- pipeline.get_active_adapters()
1085
- ```
1086
- """
1087
- if not USE_PEFT_BACKEND:
1088
- raise ValueError(
1089
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1090
- )
1091
-
1092
- from peft.tuners.tuners_utils import BaseTunerLayer
1093
-
1094
- active_adapters = []
1095
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1096
- for module in unet.modules():
1097
- if isinstance(module, BaseTunerLayer):
1098
- active_adapters = module.active_adapters
1099
- break
1100
-
1101
- return active_adapters
1102
-
1103
- def get_list_adapters(self) -> Dict[str, List[str]]:
1104
- """
1105
- Gets the current list of all available adapters in the pipeline.
1106
- """
1107
- if not USE_PEFT_BACKEND:
1108
- raise ValueError(
1109
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1110
- )
1111
-
1112
- set_adapters = {}
1113
-
1114
- if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1115
- set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1116
-
1117
- if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1118
- set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1119
-
1120
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1121
- if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1122
- set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1123
-
1124
- return set_adapters
1125
-
1126
- def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1127
- """
1128
- Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1129
- you want to load multiple adapters and free some GPU memory.
1130
-
1131
- Args:
1132
- adapter_names (`List[str]`):
1133
- List of adapters to send device to.
1134
- device (`Union[torch.device, str, int]`):
1135
- Device to send the adapters to. Can be either a torch device, a str or an integer.
1136
- """
1137
- if not USE_PEFT_BACKEND:
1138
- raise ValueError("PEFT backend is required for this method.")
1139
-
1140
- from peft.tuners.tuners_utils import BaseTunerLayer
1141
-
1142
- # Handle the UNET
1143
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1144
- for unet_module in unet.modules():
1145
- if isinstance(unet_module, BaseTunerLayer):
1146
- for adapter_name in adapter_names:
1147
- unet_module.lora_A[adapter_name].to(device)
1148
- unet_module.lora_B[adapter_name].to(device)
1149
- # this is a param, not a module, so device placement is not in-place -> re-assign
1150
- if hasattr(unet_module, "lora_magnitude_vector") and unet_module.lora_magnitude_vector is not None:
1151
- unet_module.lora_magnitude_vector[adapter_name] = unet_module.lora_magnitude_vector[
1152
- adapter_name
1153
- ].to(device)
1154
-
1155
- # Handle the text encoder
1156
- modules_to_process = []
1157
- if hasattr(self, "text_encoder"):
1158
- modules_to_process.append(self.text_encoder)
1159
-
1160
- if hasattr(self, "text_encoder_2"):
1161
- modules_to_process.append(self.text_encoder_2)
1162
-
1163
- for text_encoder in modules_to_process:
1164
- # loop over submodules
1165
- for text_encoder_module in text_encoder.modules():
1166
- if isinstance(text_encoder_module, BaseTunerLayer):
1167
- for adapter_name in adapter_names:
1168
- text_encoder_module.lora_A[adapter_name].to(device)
1169
- text_encoder_module.lora_B[adapter_name].to(device)
1170
- # this is a param, not a module, so device placement is not in-place -> re-assign
1171
- if (
1172
- hasattr(text_encoder_module, "lora_magnitude_vector")
1173
- and text_encoder_module.lora_magnitude_vector is not None
1174
- ):
1175
- text_encoder_module.lora_magnitude_vector[
1176
- adapter_name
1177
- ] = text_encoder_module.lora_magnitude_vector[adapter_name].to(device)
1178
-
1179
-
1180
- class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1181
- """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1182
-
1183
- # Override to properly handle the loading and unloading of the additional text encoder.
1184
- def load_lora_weights(
1185
- self,
1186
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1187
- adapter_name: Optional[str] = None,
1188
- **kwargs,
1189
- ):
1190
- """
1191
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1192
- `self.text_encoder`.
1193
-
1194
- All kwargs are forwarded to `self.lora_state_dict`.
1195
-
1196
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1197
-
1198
- See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1199
- `self.unet`.
1200
-
1201
- See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1202
- into `self.text_encoder`.
1203
-
1204
- Parameters:
1205
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1206
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1207
- adapter_name (`str`, *optional*):
1208
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1209
- `default_{i}` where i is the total number of adapters being loaded.
1210
- kwargs (`dict`, *optional*):
1211
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1212
- """
1213
- if not USE_PEFT_BACKEND:
1214
- raise ValueError("PEFT backend is required for this method.")
1215
-
1216
- # We could have accessed the unet config from `lora_state_dict()` too. We pass
1217
- # it here explicitly to be able to tell that it's coming from an SDXL
1218
- # pipeline.
1219
-
1220
- # if a dict is passed, copy it instead of modifying it inplace
1221
- if isinstance(pretrained_model_name_or_path_or_dict, dict):
1222
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1223
-
1224
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1225
- state_dict, network_alphas = self.lora_state_dict(
1226
- pretrained_model_name_or_path_or_dict,
1227
- unet_config=self.unet.config,
1228
- **kwargs,
1229
- )
1230
- is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
1231
- if not is_correct_format:
1232
- raise ValueError("Invalid LoRA checkpoint.")
1233
-
1234
- self.load_lora_into_unet(
1235
- state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1236
- )
1237
- text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1238
- if len(text_encoder_state_dict) > 0:
1239
- self.load_lora_into_text_encoder(
1240
- text_encoder_state_dict,
1241
- network_alphas=network_alphas,
1242
- text_encoder=self.text_encoder,
1243
- prefix="text_encoder",
1244
- lora_scale=self.lora_scale,
1245
- adapter_name=adapter_name,
1246
- _pipeline=self,
1247
- )
1248
-
1249
- text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1250
- if len(text_encoder_2_state_dict) > 0:
1251
- self.load_lora_into_text_encoder(
1252
- text_encoder_2_state_dict,
1253
- network_alphas=network_alphas,
1254
- text_encoder=self.text_encoder_2,
1255
- prefix="text_encoder_2",
1256
- lora_scale=self.lora_scale,
1257
- adapter_name=adapter_name,
1258
- _pipeline=self,
1259
- )
1260
-
1261
- @classmethod
1262
- def save_lora_weights(
1263
- cls,
1264
- save_directory: Union[str, os.PathLike],
1265
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1266
- text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1267
- text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1268
- is_main_process: bool = True,
1269
- weight_name: str = None,
1270
- save_function: Callable = None,
1271
- safe_serialization: bool = True,
1272
- ):
1273
- r"""
1274
- Save the LoRA parameters corresponding to the UNet and text encoder.
1275
-
1276
- Arguments:
1277
- save_directory (`str` or `os.PathLike`):
1278
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
1279
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1280
- State dict of the LoRA layers corresponding to the `unet`.
1281
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1282
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1283
- encoder LoRA state dict because it comes from 🤗 Transformers.
1284
- text_encoder_2_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1285
- State dict of the LoRA layers corresponding to the `text_encoder_2`. Must explicitly pass the text
1286
- encoder LoRA state dict because it comes from 🤗 Transformers.
1287
- is_main_process (`bool`, *optional*, defaults to `True`):
1288
- Whether the process calling this is the main process or not. Useful during distributed training and you
1289
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1290
- process to avoid race conditions.
1291
- save_function (`Callable`):
1292
- The function to use to save the state dictionary. Useful during distributed training when you need to
1293
- replace `torch.save` with another method. Can be configured with the environment variable
1294
- `DIFFUSERS_SAVE_MODE`.
1295
- safe_serialization (`bool`, *optional*, defaults to `True`):
1296
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1297
- """
1298
- state_dict = {}
1299
-
1300
- def pack_weights(layers, prefix):
1301
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1302
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1303
- return layers_state_dict
1304
-
1305
- if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1306
- raise ValueError(
1307
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1308
- )
1309
-
1310
- if unet_lora_layers:
1311
- state_dict.update(pack_weights(unet_lora_layers, "unet"))
1312
-
1313
- if text_encoder_lora_layers:
1314
- state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1315
-
1316
- if text_encoder_2_lora_layers:
1317
- state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1318
-
1319
- cls.write_lora_layers(
1320
- state_dict=state_dict,
1321
- save_directory=save_directory,
1322
- is_main_process=is_main_process,
1323
- weight_name=weight_name,
1324
- save_function=save_function,
1325
- safe_serialization=safe_serialization,
1326
- )
1327
-
1328
- def _remove_text_encoder_monkey_patch(self):
1329
- recurse_remove_peft_layers(self.text_encoder)
1330
- # TODO: @younesbelkada handle this in transformers side
1331
- if getattr(self.text_encoder, "peft_config", None) is not None:
1332
- del self.text_encoder.peft_config
1333
- self.text_encoder._hf_peft_config_loaded = None
1334
-
1335
- recurse_remove_peft_layers(self.text_encoder_2)
1336
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
1337
- del self.text_encoder_2.peft_config
1338
- self.text_encoder_2._hf_peft_config_loaded = None
1339
-
1340
-
1341
- class SD3LoraLoaderMixin:
1342
- r"""
1343
- Load LoRA layers into [`SD3Transformer2DModel`].
1344
- """
1345
-
1346
- transformer_name = TRANSFORMER_NAME
1347
- num_fused_loras = 0
1348
-
1349
- def load_lora_weights(
1350
- self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
1351
- ):
1352
- """
1353
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1354
- `self.text_encoder`.
1355
-
1356
- All kwargs are forwarded to `self.lora_state_dict`.
1357
-
1358
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1359
-
1360
- See [`~loaders.LoraLoaderMixin.load_lora_into_transformer`] for more details on how the state dict is loaded
1361
- into `self.transformer`.
1362
-
1363
- Parameters:
1364
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1365
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1366
- kwargs (`dict`, *optional*):
1367
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1368
- adapter_name (`str`, *optional*):
1369
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1370
- `default_{i}` where i is the total number of adapters being loaded.
1371
- """
1372
- if not USE_PEFT_BACKEND:
1373
- raise ValueError("PEFT backend is required for this method.")
1374
-
1375
- # if a dict is passed, copy it instead of modifying it inplace
1376
- if isinstance(pretrained_model_name_or_path_or_dict, dict):
1377
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1378
-
1379
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1380
- state_dict = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
1381
-
1382
- is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
1383
- if not is_correct_format:
1384
- raise ValueError("Invalid LoRA checkpoint.")
1385
-
1386
- self.load_lora_into_transformer(
1387
- state_dict,
1388
- transformer=getattr(self, self.transformer_name) if not hasattr(self, "transformer") else self.transformer,
1389
- adapter_name=adapter_name,
1390
- _pipeline=self,
1391
- )
1392
-
1393
- @classmethod
1394
- @validate_hf_hub_args
1395
- def lora_state_dict(
1396
- cls,
1397
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1398
- **kwargs,
1399
- ):
1400
- r"""
1401
- Return state dict for lora weights and the network alphas.
1402
-
1403
- <Tip warning={true}>
1404
-
1405
- We support loading A1111 formatted LoRA checkpoints in a limited capacity.
1406
-
1407
- This function is experimental and might change in the future.
1408
-
1409
- </Tip>
1410
-
1411
- Parameters:
1412
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1413
- Can be either:
1414
-
1415
- - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
1416
- the Hub.
1417
- - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
1418
- with [`ModelMixin.save_pretrained`].
1419
- - A [torch state
1420
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
1421
-
1422
- cache_dir (`Union[str, os.PathLike]`, *optional*):
1423
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
1424
- is not used.
1425
- force_download (`bool`, *optional*, defaults to `False`):
1426
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
1427
- cached versions if they exist.
1428
- resume_download (`bool`, *optional*, defaults to `False`):
1429
- Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
1430
- incompletely downloaded files are deleted.
1431
- proxies (`Dict[str, str]`, *optional*):
1432
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
1433
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
1434
- local_files_only (`bool`, *optional*, defaults to `False`):
1435
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
1436
- won't be downloaded from the Hub.
1437
- token (`str` or *bool*, *optional*):
1438
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
1439
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
1440
- revision (`str`, *optional*, defaults to `"main"`):
1441
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
1442
- allowed by Git.
1443
- subfolder (`str`, *optional*, defaults to `""`):
1444
- The subfolder location of a model file within a larger model repository on the Hub or locally.
1445
-
1446
- """
1447
- # Load the main state dict first which has the LoRA layers for either of
1448
- # UNet and text encoder or both.
1449
- cache_dir = kwargs.pop("cache_dir", None)
1450
- force_download = kwargs.pop("force_download", False)
1451
- resume_download = kwargs.pop("resume_download", False)
1452
- proxies = kwargs.pop("proxies", None)
1453
- local_files_only = kwargs.pop("local_files_only", None)
1454
- token = kwargs.pop("token", None)
1455
- revision = kwargs.pop("revision", None)
1456
- subfolder = kwargs.pop("subfolder", None)
1457
- weight_name = kwargs.pop("weight_name", None)
1458
- use_safetensors = kwargs.pop("use_safetensors", None)
1459
-
1460
- allow_pickle = False
1461
- if use_safetensors is None:
1462
- use_safetensors = True
1463
- allow_pickle = True
1464
-
1465
- user_agent = {
1466
- "file_type": "attn_procs_weights",
1467
- "framework": "pytorch",
1468
- }
1469
-
1470
- model_file = None
1471
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
1472
- # Let's first try to load .safetensors weights
1473
- if (use_safetensors and weight_name is None) or (
1474
- weight_name is not None and weight_name.endswith(".safetensors")
1475
- ):
1476
- try:
1477
- model_file = _get_model_file(
1478
- pretrained_model_name_or_path_or_dict,
1479
- weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
1480
- cache_dir=cache_dir,
1481
- force_download=force_download,
1482
- resume_download=resume_download,
1483
- proxies=proxies,
1484
- local_files_only=local_files_only,
1485
- token=token,
1486
- revision=revision,
1487
- subfolder=subfolder,
1488
- user_agent=user_agent,
1489
- )
1490
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
1491
- except (IOError, safetensors.SafetensorError) as e:
1492
- if not allow_pickle:
1493
- raise e
1494
- # try loading non-safetensors weights
1495
- model_file = None
1496
- pass
1497
-
1498
- if model_file is None:
1499
- model_file = _get_model_file(
1500
- pretrained_model_name_or_path_or_dict,
1501
- weights_name=weight_name or LORA_WEIGHT_NAME,
1502
- cache_dir=cache_dir,
1503
- force_download=force_download,
1504
- resume_download=resume_download,
1505
- proxies=proxies,
1506
- local_files_only=local_files_only,
1507
- token=token,
1508
- revision=revision,
1509
- subfolder=subfolder,
1510
- user_agent=user_agent,
1511
- )
1512
- state_dict = load_state_dict(model_file)
1513
- else:
1514
- state_dict = pretrained_model_name_or_path_or_dict
1515
-
1516
- return state_dict
1517
-
1518
- @classmethod
1519
- def load_lora_into_transformer(cls, state_dict, transformer, adapter_name=None, _pipeline=None):
1520
- """
1521
- This will load the LoRA layers specified in `state_dict` into `transformer`.
1522
-
1523
- Parameters:
1524
- state_dict (`dict`):
1525
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
1526
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
1527
- encoder lora layers.
1528
- transformer (`SD3Transformer2DModel`):
1529
- The Transformer model to load the LoRA layers into.
1530
- adapter_name (`str`, *optional*):
1531
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1532
- `default_{i}` where i is the total number of adapters being loaded.
1533
- """
1534
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
1535
-
1536
- keys = list(state_dict.keys())
1537
-
1538
- transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
1539
- state_dict = {
1540
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
1541
- }
1542
-
1543
- if len(state_dict.keys()) > 0:
1544
- if adapter_name in getattr(transformer, "peft_config", {}):
1545
- raise ValueError(
1546
- f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
1547
- )
1548
-
1549
- rank = {}
1550
- for key, val in state_dict.items():
1551
- if "lora_B" in key:
1552
- rank[key] = val.shape[1]
1553
-
1554
- lora_config_kwargs = get_peft_kwargs(rank, network_alpha_dict=None, peft_state_dict=state_dict)
1555
- if "use_dora" in lora_config_kwargs:
1556
- if lora_config_kwargs["use_dora"] and is_peft_version("<", "0.9.0"):
1557
- raise ValueError(
1558
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
1559
- )
1560
- else:
1561
- lora_config_kwargs.pop("use_dora")
1562
- lora_config = LoraConfig(**lora_config_kwargs)
1563
-
1564
- # adapter_name
1565
- if adapter_name is None:
1566
- adapter_name = get_adapter_name(transformer)
1567
-
1568
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
1569
- # otherwise loading LoRA weights will lead to an error
1570
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
1571
-
1572
- inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
1573
- incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
1574
-
1575
- if incompatible_keys is not None:
1576
- # check only for unexpected keys
1577
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
1578
- if unexpected_keys:
1579
- logger.warning(
1580
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
1581
- f" {unexpected_keys}. "
1582
- )
1583
-
1584
- # Offload back.
1585
- if is_model_cpu_offload:
1586
- _pipeline.enable_model_cpu_offload()
1587
- elif is_sequential_cpu_offload:
1588
- _pipeline.enable_sequential_cpu_offload()
1589
- # Unsafe code />
1590
-
1591
- @classmethod
1592
- def save_lora_weights(
1593
- cls,
1594
- save_directory: Union[str, os.PathLike],
1595
- transformer_lora_layers: Dict[str, torch.nn.Module] = None,
1596
- is_main_process: bool = True,
1597
- weight_name: str = None,
1598
- save_function: Callable = None,
1599
- safe_serialization: bool = True,
1600
- ):
1601
- r"""
1602
- Save the LoRA parameters corresponding to the UNet and text encoder.
1603
-
1604
- Arguments:
1605
- save_directory (`str` or `os.PathLike`):
1606
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
1607
- transformer_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1608
- State dict of the LoRA layers corresponding to the `transformer`.
1609
- is_main_process (`bool`, *optional*, defaults to `True`):
1610
- Whether the process calling this is the main process or not. Useful during distributed training and you
1611
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1612
- process to avoid race conditions.
1613
- save_function (`Callable`):
1614
- The function to use to save the state dictionary. Useful during distributed training when you need to
1615
- replace `torch.save` with another method. Can be configured with the environment variable
1616
- `DIFFUSERS_SAVE_MODE`.
1617
- safe_serialization (`bool`, *optional*, defaults to `True`):
1618
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1619
- """
1620
- state_dict = {}
1621
-
1622
- def pack_weights(layers, prefix):
1623
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1624
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1625
- return layers_state_dict
1626
-
1627
- if not transformer_lora_layers:
1628
- raise ValueError("You must pass `transformer_lora_layers`.")
1629
-
1630
- if transformer_lora_layers:
1631
- state_dict.update(pack_weights(transformer_lora_layers, cls.transformer_name))
1632
-
1633
- # Save the model
1634
- cls.write_lora_layers(
1635
- state_dict=state_dict,
1636
- save_directory=save_directory,
1637
- is_main_process=is_main_process,
1638
- weight_name=weight_name,
1639
- save_function=save_function,
1640
- safe_serialization=safe_serialization,
1641
- )
1642
-
1643
- @staticmethod
1644
- def write_lora_layers(
1645
- state_dict: Dict[str, torch.Tensor],
1646
- save_directory: str,
1647
- is_main_process: bool,
1648
- weight_name: str,
1649
- save_function: Callable,
1650
- safe_serialization: bool,
1651
- ):
1652
- if os.path.isfile(save_directory):
1653
- logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
1654
- return
1655
-
1656
- if save_function is None:
1657
- if safe_serialization:
1658
-
1659
- def save_function(weights, filename):
1660
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
1661
-
1662
- else:
1663
- save_function = torch.save
1664
-
1665
- os.makedirs(save_directory, exist_ok=True)
1666
-
1667
- if weight_name is None:
1668
- if safe_serialization:
1669
- weight_name = LORA_WEIGHT_NAME_SAFE
1670
- else:
1671
- weight_name = LORA_WEIGHT_NAME
1672
-
1673
- save_path = Path(save_directory, weight_name).as_posix()
1674
- save_function(state_dict, save_path)
1675
- logger.info(f"Model weights saved in {save_path}")
1676
-
1677
- def unload_lora_weights(self):
1678
- """
1679
- Unloads the LoRA parameters.
1680
-
1681
- Examples:
1682
-
1683
- ```python
1684
- >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
1685
- >>> pipeline.unload_lora_weights()
1686
- >>> ...
1687
- ```
1688
- """
1689
- transformer = getattr(self, self.transformer_name) if not hasattr(self, "transformer") else self.transformer
1690
- recurse_remove_peft_layers(transformer)
1691
- if hasattr(transformer, "peft_config"):
1692
- del transformer.peft_config
1693
-
1694
- @classmethod
1695
- # Copied from diffusers.loaders.lora.LoraLoaderMixin._optionally_disable_offloading
1696
- def _optionally_disable_offloading(cls, _pipeline):
1697
- """
1698
- Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
1699
-
1700
- Args:
1701
- _pipeline (`DiffusionPipeline`):
1702
- The pipeline to disable offloading for.
1703
-
1704
- Returns:
1705
- tuple:
1706
- A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
1707
- """
1708
- is_model_cpu_offload = False
1709
- is_sequential_cpu_offload = False
1710
-
1711
- if _pipeline is not None and _pipeline.hf_device_map is None:
1712
- for _, component in _pipeline.components.items():
1713
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
1714
- if not is_model_cpu_offload:
1715
- is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
1716
- if not is_sequential_cpu_offload:
1717
- is_sequential_cpu_offload = (
1718
- isinstance(component._hf_hook, AlignDevicesHook)
1719
- or hasattr(component._hf_hook, "hooks")
1720
- and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
1721
- )
1722
-
1723
- logger.info(
1724
- "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."
1725
- )
1726
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
1727
-
1728
- return (is_model_cpu_offload, is_sequential_cpu_offload)