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