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.
- diffusers/__init__.py +94 -3
- diffusers/commands/env.py +1 -5
- diffusers/configuration_utils.py +4 -9
- diffusers/dependency_versions_table.py +2 -2
- diffusers/image_processor.py +1 -2
- diffusers/loaders/__init__.py +17 -2
- diffusers/loaders/ip_adapter.py +10 -7
- diffusers/loaders/lora_base.py +752 -0
- diffusers/loaders/lora_pipeline.py +2252 -0
- diffusers/loaders/peft.py +213 -5
- diffusers/loaders/single_file.py +3 -14
- diffusers/loaders/single_file_model.py +31 -10
- diffusers/loaders/single_file_utils.py +293 -8
- diffusers/loaders/textual_inversion.py +1 -6
- diffusers/loaders/unet.py +23 -208
- diffusers/models/__init__.py +20 -0
- diffusers/models/activations.py +22 -0
- diffusers/models/attention.py +386 -7
- diffusers/models/attention_processor.py +1937 -629
- diffusers/models/autoencoders/__init__.py +2 -0
- diffusers/models/autoencoders/autoencoder_kl.py +14 -3
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1271 -0
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
- diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vq_model.py +4 -4
- diffusers/models/controlnet.py +2 -3
- diffusers/models/controlnet_hunyuan.py +401 -0
- diffusers/models/controlnet_sd3.py +11 -11
- diffusers/models/controlnet_sparsectrl.py +789 -0
- diffusers/models/controlnet_xs.py +40 -10
- diffusers/models/downsampling.py +68 -0
- diffusers/models/embeddings.py +403 -36
- diffusers/models/model_loading_utils.py +1 -3
- diffusers/models/modeling_flax_utils.py +1 -6
- diffusers/models/modeling_utils.py +4 -16
- diffusers/models/normalization.py +203 -12
- diffusers/models/transformers/__init__.py +6 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +543 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +485 -0
- diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
- diffusers/models/transformers/latte_transformer_3d.py +327 -0
- diffusers/models/transformers/lumina_nextdit2d.py +340 -0
- diffusers/models/transformers/pixart_transformer_2d.py +102 -1
- diffusers/models/transformers/prior_transformer.py +1 -1
- diffusers/models/transformers/stable_audio_transformer.py +458 -0
- diffusers/models/transformers/transformer_flux.py +455 -0
- diffusers/models/transformers/transformer_sd3.py +18 -4
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d_condition.py +8 -1
- diffusers/models/unets/unet_3d_blocks.py +51 -920
- diffusers/models/unets/unet_3d_condition.py +4 -1
- diffusers/models/unets/unet_i2vgen_xl.py +4 -1
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +1330 -84
- diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
- diffusers/models/unets/unet_stable_cascade.py +1 -3
- diffusers/models/unets/uvit_2d.py +1 -1
- diffusers/models/upsampling.py +64 -0
- diffusers/models/vq_model.py +8 -4
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +100 -3
- diffusers/pipelines/animatediff/__init__.py +4 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
- diffusers/pipelines/aura_flow/__init__.py +48 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
- diffusers/pipelines/auto_pipeline.py +97 -19
- diffusers/pipelines/cogvideo/__init__.py +48 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +746 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
- diffusers/pipelines/flux/__init__.py +47 -0
- diffusers/pipelines/flux/pipeline_flux.py +749 -0
- diffusers/pipelines/flux/pipeline_output.py +21 -0
- diffusers/pipelines/free_init_utils.py +2 -0
- diffusers/pipelines/free_noise_utils.py +236 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
- diffusers/pipelines/kolors/__init__.py +54 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
- diffusers/pipelines/kolors/pipeline_output.py +21 -0
- diffusers/pipelines/kolors/text_encoder.py +889 -0
- diffusers/pipelines/kolors/tokenizer.py +334 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
- diffusers/pipelines/latte/__init__.py +48 -0
- diffusers/pipelines/latte/pipeline_latte.py +881 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
- diffusers/pipelines/lumina/__init__.py +48 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
- diffusers/pipelines/pag/__init__.py +67 -0
- diffusers/pipelines/pag/pag_utils.py +237 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
- diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
- diffusers/pipelines/pia/pipeline_pia.py +30 -37
- diffusers/pipelines/pipeline_flax_utils.py +4 -9
- diffusers/pipelines/pipeline_loading_utils.py +0 -3
- diffusers/pipelines/pipeline_utils.py +2 -14
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
- diffusers/pipelines/stable_audio/__init__.py +50 -0
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
- diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
- diffusers/schedulers/__init__.py +8 -0
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
- diffusers/schedulers/scheduling_ddim.py +1 -1
- diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
- diffusers/schedulers/scheduling_ddpm.py +1 -1
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
- diffusers/schedulers/scheduling_deis_multistep.py +2 -2
- diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
- diffusers/schedulers/scheduling_ipndm.py +1 -1
- diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
- diffusers/schedulers/scheduling_utils.py +1 -3
- diffusers/schedulers/scheduling_utils_flax.py +1 -3
- diffusers/training_utils.py +99 -14
- diffusers/utils/__init__.py +2 -2
- diffusers/utils/dummy_pt_objects.py +210 -0
- diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
- diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
- diffusers/utils/dynamic_modules_utils.py +1 -11
- diffusers/utils/export_utils.py +50 -6
- diffusers/utils/hub_utils.py +45 -42
- diffusers/utils/import_utils.py +37 -15
- diffusers/utils/loading_utils.py +80 -3
- diffusers/utils/testing_utils.py +11 -8
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/WHEEL +1 -1
- diffusers/loaders/autoencoder.py +0 -146
- diffusers/loaders/controlnet.py +0 -136
- diffusers/loaders/lora.py +0 -1728
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/LICENSE +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,752 @@
|
|
1
|
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import copy
|
16
|
+
import inspect
|
17
|
+
import os
|
18
|
+
from pathlib import Path
|
19
|
+
from typing import Callable, Dict, List, Optional, Union
|
20
|
+
|
21
|
+
import safetensors
|
22
|
+
import torch
|
23
|
+
import torch.nn as nn
|
24
|
+
from huggingface_hub import model_info
|
25
|
+
from huggingface_hub.constants import HF_HUB_OFFLINE
|
26
|
+
|
27
|
+
from ..models.modeling_utils import ModelMixin, load_state_dict
|
28
|
+
from ..utils import (
|
29
|
+
USE_PEFT_BACKEND,
|
30
|
+
_get_model_file,
|
31
|
+
delete_adapter_layers,
|
32
|
+
deprecate,
|
33
|
+
is_accelerate_available,
|
34
|
+
is_peft_available,
|
35
|
+
is_transformers_available,
|
36
|
+
logging,
|
37
|
+
recurse_remove_peft_layers,
|
38
|
+
set_adapter_layers,
|
39
|
+
set_weights_and_activate_adapters,
|
40
|
+
)
|
41
|
+
|
42
|
+
|
43
|
+
if is_transformers_available():
|
44
|
+
from transformers import PreTrainedModel
|
45
|
+
|
46
|
+
if is_peft_available():
|
47
|
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
48
|
+
|
49
|
+
if is_accelerate_available():
|
50
|
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
51
|
+
|
52
|
+
logger = logging.get_logger(__name__)
|
53
|
+
|
54
|
+
|
55
|
+
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
|
56
|
+
"""
|
57
|
+
Fuses LoRAs for the text encoder.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
text_encoder (`torch.nn.Module`):
|
61
|
+
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
62
|
+
attribute.
|
63
|
+
lora_scale (`float`, defaults to 1.0):
|
64
|
+
Controls how much to influence the outputs with the LoRA parameters.
|
65
|
+
safe_fusing (`bool`, defaults to `False`):
|
66
|
+
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
|
67
|
+
adapter_names (`List[str]` or `str`):
|
68
|
+
The names of the adapters to use.
|
69
|
+
"""
|
70
|
+
merge_kwargs = {"safe_merge": safe_fusing}
|
71
|
+
|
72
|
+
for module in text_encoder.modules():
|
73
|
+
if isinstance(module, BaseTunerLayer):
|
74
|
+
if lora_scale != 1.0:
|
75
|
+
module.scale_layer(lora_scale)
|
76
|
+
|
77
|
+
# For BC with previous PEFT versions, we need to check the signature
|
78
|
+
# of the `merge` method to see if it supports the `adapter_names` argument.
|
79
|
+
supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
|
80
|
+
if "adapter_names" in supported_merge_kwargs:
|
81
|
+
merge_kwargs["adapter_names"] = adapter_names
|
82
|
+
elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
|
83
|
+
raise ValueError(
|
84
|
+
"The `adapter_names` argument is not supported with your PEFT version. "
|
85
|
+
"Please upgrade to the latest version of PEFT. `pip install -U peft`"
|
86
|
+
)
|
87
|
+
|
88
|
+
module.merge(**merge_kwargs)
|
89
|
+
|
90
|
+
|
91
|
+
def unfuse_text_encoder_lora(text_encoder):
|
92
|
+
"""
|
93
|
+
Unfuses LoRAs for the text encoder.
|
94
|
+
|
95
|
+
Args:
|
96
|
+
text_encoder (`torch.nn.Module`):
|
97
|
+
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
98
|
+
attribute.
|
99
|
+
"""
|
100
|
+
for module in text_encoder.modules():
|
101
|
+
if isinstance(module, BaseTunerLayer):
|
102
|
+
module.unmerge()
|
103
|
+
|
104
|
+
|
105
|
+
def set_adapters_for_text_encoder(
|
106
|
+
adapter_names: Union[List[str], str],
|
107
|
+
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
108
|
+
text_encoder_weights: Optional[Union[float, List[float], List[None]]] = None,
|
109
|
+
):
|
110
|
+
"""
|
111
|
+
Sets the adapter layers for the text encoder.
|
112
|
+
|
113
|
+
Args:
|
114
|
+
adapter_names (`List[str]` or `str`):
|
115
|
+
The names of the adapters to use.
|
116
|
+
text_encoder (`torch.nn.Module`, *optional*):
|
117
|
+
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
118
|
+
attribute.
|
119
|
+
text_encoder_weights (`List[float]`, *optional*):
|
120
|
+
The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
|
121
|
+
"""
|
122
|
+
if text_encoder is None:
|
123
|
+
raise ValueError(
|
124
|
+
"The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
|
125
|
+
)
|
126
|
+
|
127
|
+
def process_weights(adapter_names, weights):
|
128
|
+
# Expand weights into a list, one entry per adapter
|
129
|
+
# e.g. for 2 adapters: 7 -> [7,7] ; [3, None] -> [3, None]
|
130
|
+
if not isinstance(weights, list):
|
131
|
+
weights = [weights] * len(adapter_names)
|
132
|
+
|
133
|
+
if len(adapter_names) != len(weights):
|
134
|
+
raise ValueError(
|
135
|
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
|
136
|
+
)
|
137
|
+
|
138
|
+
# Set None values to default of 1.0
|
139
|
+
# e.g. [7,7] -> [7,7] ; [3, None] -> [3,1]
|
140
|
+
weights = [w if w is not None else 1.0 for w in weights]
|
141
|
+
|
142
|
+
return weights
|
143
|
+
|
144
|
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
145
|
+
text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
|
146
|
+
set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
|
147
|
+
|
148
|
+
|
149
|
+
def disable_lora_for_text_encoder(text_encoder: Optional["PreTrainedModel"] = None):
|
150
|
+
"""
|
151
|
+
Disables the LoRA layers for the text encoder.
|
152
|
+
|
153
|
+
Args:
|
154
|
+
text_encoder (`torch.nn.Module`, *optional*):
|
155
|
+
The text encoder module to disable the LoRA layers for. If `None`, it will try to get the `text_encoder`
|
156
|
+
attribute.
|
157
|
+
"""
|
158
|
+
if text_encoder is None:
|
159
|
+
raise ValueError("Text Encoder not found.")
|
160
|
+
set_adapter_layers(text_encoder, enabled=False)
|
161
|
+
|
162
|
+
|
163
|
+
def enable_lora_for_text_encoder(text_encoder: Optional["PreTrainedModel"] = None):
|
164
|
+
"""
|
165
|
+
Enables the LoRA layers for the text encoder.
|
166
|
+
|
167
|
+
Args:
|
168
|
+
text_encoder (`torch.nn.Module`, *optional*):
|
169
|
+
The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
|
170
|
+
attribute.
|
171
|
+
"""
|
172
|
+
if text_encoder is None:
|
173
|
+
raise ValueError("Text Encoder not found.")
|
174
|
+
set_adapter_layers(text_encoder, enabled=True)
|
175
|
+
|
176
|
+
|
177
|
+
def _remove_text_encoder_monkey_patch(text_encoder):
|
178
|
+
recurse_remove_peft_layers(text_encoder)
|
179
|
+
if getattr(text_encoder, "peft_config", None) is not None:
|
180
|
+
del text_encoder.peft_config
|
181
|
+
text_encoder._hf_peft_config_loaded = None
|
182
|
+
|
183
|
+
|
184
|
+
class LoraBaseMixin:
|
185
|
+
"""Utility class for handling LoRAs."""
|
186
|
+
|
187
|
+
_lora_loadable_modules = []
|
188
|
+
num_fused_loras = 0
|
189
|
+
|
190
|
+
def load_lora_weights(self, **kwargs):
|
191
|
+
raise NotImplementedError("`load_lora_weights()` is not implemented.")
|
192
|
+
|
193
|
+
@classmethod
|
194
|
+
def save_lora_weights(cls, **kwargs):
|
195
|
+
raise NotImplementedError("`save_lora_weights()` not implemented.")
|
196
|
+
|
197
|
+
@classmethod
|
198
|
+
def lora_state_dict(cls, **kwargs):
|
199
|
+
raise NotImplementedError("`lora_state_dict()` is not implemented.")
|
200
|
+
|
201
|
+
@classmethod
|
202
|
+
def _optionally_disable_offloading(cls, _pipeline):
|
203
|
+
"""
|
204
|
+
Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
|
205
|
+
|
206
|
+
Args:
|
207
|
+
_pipeline (`DiffusionPipeline`):
|
208
|
+
The pipeline to disable offloading for.
|
209
|
+
|
210
|
+
Returns:
|
211
|
+
tuple:
|
212
|
+
A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
|
213
|
+
"""
|
214
|
+
is_model_cpu_offload = False
|
215
|
+
is_sequential_cpu_offload = False
|
216
|
+
|
217
|
+
if _pipeline is not None and _pipeline.hf_device_map is None:
|
218
|
+
for _, component in _pipeline.components.items():
|
219
|
+
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
220
|
+
if not is_model_cpu_offload:
|
221
|
+
is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
|
222
|
+
if not is_sequential_cpu_offload:
|
223
|
+
is_sequential_cpu_offload = (
|
224
|
+
isinstance(component._hf_hook, AlignDevicesHook)
|
225
|
+
or hasattr(component._hf_hook, "hooks")
|
226
|
+
and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
|
227
|
+
)
|
228
|
+
|
229
|
+
logger.info(
|
230
|
+
"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."
|
231
|
+
)
|
232
|
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
233
|
+
|
234
|
+
return (is_model_cpu_offload, is_sequential_cpu_offload)
|
235
|
+
|
236
|
+
@classmethod
|
237
|
+
def _fetch_state_dict(
|
238
|
+
cls,
|
239
|
+
pretrained_model_name_or_path_or_dict,
|
240
|
+
weight_name,
|
241
|
+
use_safetensors,
|
242
|
+
local_files_only,
|
243
|
+
cache_dir,
|
244
|
+
force_download,
|
245
|
+
proxies,
|
246
|
+
token,
|
247
|
+
revision,
|
248
|
+
subfolder,
|
249
|
+
user_agent,
|
250
|
+
allow_pickle,
|
251
|
+
):
|
252
|
+
from .lora_pipeline import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE
|
253
|
+
|
254
|
+
model_file = None
|
255
|
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
256
|
+
# Let's first try to load .safetensors weights
|
257
|
+
if (use_safetensors and weight_name is None) or (
|
258
|
+
weight_name is not None and weight_name.endswith(".safetensors")
|
259
|
+
):
|
260
|
+
try:
|
261
|
+
# Here we're relaxing the loading check to enable more Inference API
|
262
|
+
# friendliness where sometimes, it's not at all possible to automatically
|
263
|
+
# determine `weight_name`.
|
264
|
+
if weight_name is None:
|
265
|
+
weight_name = cls._best_guess_weight_name(
|
266
|
+
pretrained_model_name_or_path_or_dict,
|
267
|
+
file_extension=".safetensors",
|
268
|
+
local_files_only=local_files_only,
|
269
|
+
)
|
270
|
+
model_file = _get_model_file(
|
271
|
+
pretrained_model_name_or_path_or_dict,
|
272
|
+
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
273
|
+
cache_dir=cache_dir,
|
274
|
+
force_download=force_download,
|
275
|
+
proxies=proxies,
|
276
|
+
local_files_only=local_files_only,
|
277
|
+
token=token,
|
278
|
+
revision=revision,
|
279
|
+
subfolder=subfolder,
|
280
|
+
user_agent=user_agent,
|
281
|
+
)
|
282
|
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
283
|
+
except (IOError, safetensors.SafetensorError) as e:
|
284
|
+
if not allow_pickle:
|
285
|
+
raise e
|
286
|
+
# try loading non-safetensors weights
|
287
|
+
model_file = None
|
288
|
+
pass
|
289
|
+
|
290
|
+
if model_file is None:
|
291
|
+
if weight_name is None:
|
292
|
+
weight_name = cls._best_guess_weight_name(
|
293
|
+
pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
|
294
|
+
)
|
295
|
+
model_file = _get_model_file(
|
296
|
+
pretrained_model_name_or_path_or_dict,
|
297
|
+
weights_name=weight_name or LORA_WEIGHT_NAME,
|
298
|
+
cache_dir=cache_dir,
|
299
|
+
force_download=force_download,
|
300
|
+
proxies=proxies,
|
301
|
+
local_files_only=local_files_only,
|
302
|
+
token=token,
|
303
|
+
revision=revision,
|
304
|
+
subfolder=subfolder,
|
305
|
+
user_agent=user_agent,
|
306
|
+
)
|
307
|
+
state_dict = load_state_dict(model_file)
|
308
|
+
else:
|
309
|
+
state_dict = pretrained_model_name_or_path_or_dict
|
310
|
+
|
311
|
+
return state_dict
|
312
|
+
|
313
|
+
@classmethod
|
314
|
+
def _best_guess_weight_name(
|
315
|
+
cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
|
316
|
+
):
|
317
|
+
from .lora_pipeline import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE
|
318
|
+
|
319
|
+
if local_files_only or HF_HUB_OFFLINE:
|
320
|
+
raise ValueError("When using the offline mode, you must specify a `weight_name`.")
|
321
|
+
|
322
|
+
targeted_files = []
|
323
|
+
|
324
|
+
if os.path.isfile(pretrained_model_name_or_path_or_dict):
|
325
|
+
return
|
326
|
+
elif os.path.isdir(pretrained_model_name_or_path_or_dict):
|
327
|
+
targeted_files = [
|
328
|
+
f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
|
329
|
+
]
|
330
|
+
else:
|
331
|
+
files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
|
332
|
+
targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
|
333
|
+
if len(targeted_files) == 0:
|
334
|
+
return
|
335
|
+
|
336
|
+
# "scheduler" does not correspond to a LoRA checkpoint.
|
337
|
+
# "optimizer" does not correspond to a LoRA checkpoint
|
338
|
+
# only top-level checkpoints are considered and not the other ones, hence "checkpoint".
|
339
|
+
unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
|
340
|
+
targeted_files = list(
|
341
|
+
filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
|
342
|
+
)
|
343
|
+
|
344
|
+
if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
|
345
|
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
|
346
|
+
elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
|
347
|
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
|
348
|
+
|
349
|
+
if len(targeted_files) > 1:
|
350
|
+
raise ValueError(
|
351
|
+
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}."
|
352
|
+
)
|
353
|
+
weight_name = targeted_files[0]
|
354
|
+
return weight_name
|
355
|
+
|
356
|
+
def unload_lora_weights(self):
|
357
|
+
"""
|
358
|
+
Unloads the LoRA parameters.
|
359
|
+
|
360
|
+
Examples:
|
361
|
+
|
362
|
+
```python
|
363
|
+
>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
|
364
|
+
>>> pipeline.unload_lora_weights()
|
365
|
+
>>> ...
|
366
|
+
```
|
367
|
+
"""
|
368
|
+
if not USE_PEFT_BACKEND:
|
369
|
+
raise ValueError("PEFT backend is required for this method.")
|
370
|
+
|
371
|
+
for component in self._lora_loadable_modules:
|
372
|
+
model = getattr(self, component, None)
|
373
|
+
if model is not None:
|
374
|
+
if issubclass(model.__class__, ModelMixin):
|
375
|
+
model.unload_lora()
|
376
|
+
elif issubclass(model.__class__, PreTrainedModel):
|
377
|
+
_remove_text_encoder_monkey_patch(model)
|
378
|
+
|
379
|
+
def fuse_lora(
|
380
|
+
self,
|
381
|
+
components: List[str] = [],
|
382
|
+
lora_scale: float = 1.0,
|
383
|
+
safe_fusing: bool = False,
|
384
|
+
adapter_names: Optional[List[str]] = None,
|
385
|
+
**kwargs,
|
386
|
+
):
|
387
|
+
r"""
|
388
|
+
Fuses the LoRA parameters into the original parameters of the corresponding blocks.
|
389
|
+
|
390
|
+
<Tip warning={true}>
|
391
|
+
|
392
|
+
This is an experimental API.
|
393
|
+
|
394
|
+
</Tip>
|
395
|
+
|
396
|
+
Args:
|
397
|
+
components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into.
|
398
|
+
lora_scale (`float`, defaults to 1.0):
|
399
|
+
Controls how much to influence the outputs with the LoRA parameters.
|
400
|
+
safe_fusing (`bool`, defaults to `False`):
|
401
|
+
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
|
402
|
+
adapter_names (`List[str]`, *optional*):
|
403
|
+
Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
|
404
|
+
|
405
|
+
Example:
|
406
|
+
|
407
|
+
```py
|
408
|
+
from diffusers import DiffusionPipeline
|
409
|
+
import torch
|
410
|
+
|
411
|
+
pipeline = DiffusionPipeline.from_pretrained(
|
412
|
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
413
|
+
).to("cuda")
|
414
|
+
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
|
415
|
+
pipeline.fuse_lora(lora_scale=0.7)
|
416
|
+
```
|
417
|
+
"""
|
418
|
+
if "fuse_unet" in kwargs:
|
419
|
+
depr_message = "Passing `fuse_unet` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_unet` will be removed in a future version."
|
420
|
+
deprecate(
|
421
|
+
"fuse_unet",
|
422
|
+
"1.0.0",
|
423
|
+
depr_message,
|
424
|
+
)
|
425
|
+
if "fuse_transformer" in kwargs:
|
426
|
+
depr_message = "Passing `fuse_transformer` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_transformer` will be removed in a future version."
|
427
|
+
deprecate(
|
428
|
+
"fuse_transformer",
|
429
|
+
"1.0.0",
|
430
|
+
depr_message,
|
431
|
+
)
|
432
|
+
if "fuse_text_encoder" in kwargs:
|
433
|
+
depr_message = "Passing `fuse_text_encoder` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_text_encoder` will be removed in a future version."
|
434
|
+
deprecate(
|
435
|
+
"fuse_text_encoder",
|
436
|
+
"1.0.0",
|
437
|
+
depr_message,
|
438
|
+
)
|
439
|
+
|
440
|
+
if len(components) == 0:
|
441
|
+
raise ValueError("`components` cannot be an empty list.")
|
442
|
+
|
443
|
+
for fuse_component in components:
|
444
|
+
if fuse_component not in self._lora_loadable_modules:
|
445
|
+
raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.")
|
446
|
+
|
447
|
+
model = getattr(self, fuse_component, None)
|
448
|
+
if model is not None:
|
449
|
+
# check if diffusers model
|
450
|
+
if issubclass(model.__class__, ModelMixin):
|
451
|
+
model.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
|
452
|
+
# handle transformers models.
|
453
|
+
if issubclass(model.__class__, PreTrainedModel):
|
454
|
+
fuse_text_encoder_lora(
|
455
|
+
model, lora_scale=lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names
|
456
|
+
)
|
457
|
+
|
458
|
+
self.num_fused_loras += 1
|
459
|
+
|
460
|
+
def unfuse_lora(self, components: List[str] = [], **kwargs):
|
461
|
+
r"""
|
462
|
+
Reverses the effect of
|
463
|
+
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora).
|
464
|
+
|
465
|
+
<Tip warning={true}>
|
466
|
+
|
467
|
+
This is an experimental API.
|
468
|
+
|
469
|
+
</Tip>
|
470
|
+
|
471
|
+
Args:
|
472
|
+
components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from.
|
473
|
+
unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
|
474
|
+
unfuse_text_encoder (`bool`, defaults to `True`):
|
475
|
+
Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
476
|
+
LoRA parameters then it won't have any effect.
|
477
|
+
"""
|
478
|
+
if "unfuse_unet" in kwargs:
|
479
|
+
depr_message = "Passing `unfuse_unet` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_unet` will be removed in a future version."
|
480
|
+
deprecate(
|
481
|
+
"unfuse_unet",
|
482
|
+
"1.0.0",
|
483
|
+
depr_message,
|
484
|
+
)
|
485
|
+
if "unfuse_transformer" in kwargs:
|
486
|
+
depr_message = "Passing `unfuse_transformer` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_transformer` will be removed in a future version."
|
487
|
+
deprecate(
|
488
|
+
"unfuse_transformer",
|
489
|
+
"1.0.0",
|
490
|
+
depr_message,
|
491
|
+
)
|
492
|
+
if "unfuse_text_encoder" in kwargs:
|
493
|
+
depr_message = "Passing `unfuse_text_encoder` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_text_encoder` will be removed in a future version."
|
494
|
+
deprecate(
|
495
|
+
"unfuse_text_encoder",
|
496
|
+
"1.0.0",
|
497
|
+
depr_message,
|
498
|
+
)
|
499
|
+
|
500
|
+
if len(components) == 0:
|
501
|
+
raise ValueError("`components` cannot be an empty list.")
|
502
|
+
|
503
|
+
for fuse_component in components:
|
504
|
+
if fuse_component not in self._lora_loadable_modules:
|
505
|
+
raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.")
|
506
|
+
|
507
|
+
model = getattr(self, fuse_component, None)
|
508
|
+
if model is not None:
|
509
|
+
if issubclass(model.__class__, (ModelMixin, PreTrainedModel)):
|
510
|
+
for module in model.modules():
|
511
|
+
if isinstance(module, BaseTunerLayer):
|
512
|
+
module.unmerge()
|
513
|
+
|
514
|
+
self.num_fused_loras -= 1
|
515
|
+
|
516
|
+
def set_adapters(
|
517
|
+
self,
|
518
|
+
adapter_names: Union[List[str], str],
|
519
|
+
adapter_weights: Optional[Union[float, Dict, List[float], List[Dict]]] = None,
|
520
|
+
):
|
521
|
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
522
|
+
|
523
|
+
adapter_weights = copy.deepcopy(adapter_weights)
|
524
|
+
|
525
|
+
# Expand weights into a list, one entry per adapter
|
526
|
+
if not isinstance(adapter_weights, list):
|
527
|
+
adapter_weights = [adapter_weights] * len(adapter_names)
|
528
|
+
|
529
|
+
if len(adapter_names) != len(adapter_weights):
|
530
|
+
raise ValueError(
|
531
|
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(adapter_weights)}"
|
532
|
+
)
|
533
|
+
|
534
|
+
list_adapters = self.get_list_adapters() # eg {"unet": ["adapter1", "adapter2"], "text_encoder": ["adapter2"]}
|
535
|
+
all_adapters = {
|
536
|
+
adapter for adapters in list_adapters.values() for adapter in adapters
|
537
|
+
} # eg ["adapter1", "adapter2"]
|
538
|
+
invert_list_adapters = {
|
539
|
+
adapter: [part for part, adapters in list_adapters.items() if adapter in adapters]
|
540
|
+
for adapter in all_adapters
|
541
|
+
} # eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]}
|
542
|
+
|
543
|
+
# Decompose weights into weights for denoiser and text encoders.
|
544
|
+
_component_adapter_weights = {}
|
545
|
+
for component in self._lora_loadable_modules:
|
546
|
+
model = getattr(self, component)
|
547
|
+
|
548
|
+
for adapter_name, weights in zip(adapter_names, adapter_weights):
|
549
|
+
if isinstance(weights, dict):
|
550
|
+
component_adapter_weights = weights.pop(component, None)
|
551
|
+
|
552
|
+
if component_adapter_weights is not None and not hasattr(self, component):
|
553
|
+
logger.warning(
|
554
|
+
f"Lora weight dict contains {component} weights but will be ignored because pipeline does not have {component}."
|
555
|
+
)
|
556
|
+
|
557
|
+
if component_adapter_weights is not None and component not in invert_list_adapters[adapter_name]:
|
558
|
+
logger.warning(
|
559
|
+
(
|
560
|
+
f"Lora weight dict for adapter '{adapter_name}' contains {component},"
|
561
|
+
f"but this will be ignored because {adapter_name} does not contain weights for {component}."
|
562
|
+
f"Valid parts for {adapter_name} are: {invert_list_adapters[adapter_name]}."
|
563
|
+
)
|
564
|
+
)
|
565
|
+
|
566
|
+
else:
|
567
|
+
component_adapter_weights = weights
|
568
|
+
|
569
|
+
_component_adapter_weights.setdefault(component, [])
|
570
|
+
_component_adapter_weights[component].append(component_adapter_weights)
|
571
|
+
|
572
|
+
if issubclass(model.__class__, ModelMixin):
|
573
|
+
model.set_adapters(adapter_names, _component_adapter_weights[component])
|
574
|
+
elif issubclass(model.__class__, PreTrainedModel):
|
575
|
+
set_adapters_for_text_encoder(adapter_names, model, _component_adapter_weights[component])
|
576
|
+
|
577
|
+
def disable_lora(self):
|
578
|
+
if not USE_PEFT_BACKEND:
|
579
|
+
raise ValueError("PEFT backend is required for this method.")
|
580
|
+
|
581
|
+
for component in self._lora_loadable_modules:
|
582
|
+
model = getattr(self, component, None)
|
583
|
+
if model is not None:
|
584
|
+
if issubclass(model.__class__, ModelMixin):
|
585
|
+
model.disable_lora()
|
586
|
+
elif issubclass(model.__class__, PreTrainedModel):
|
587
|
+
disable_lora_for_text_encoder(model)
|
588
|
+
|
589
|
+
def enable_lora(self):
|
590
|
+
if not USE_PEFT_BACKEND:
|
591
|
+
raise ValueError("PEFT backend is required for this method.")
|
592
|
+
|
593
|
+
for component in self._lora_loadable_modules:
|
594
|
+
model = getattr(self, component, None)
|
595
|
+
if model is not None:
|
596
|
+
if issubclass(model.__class__, ModelMixin):
|
597
|
+
model.enable_lora()
|
598
|
+
elif issubclass(model.__class__, PreTrainedModel):
|
599
|
+
enable_lora_for_text_encoder(model)
|
600
|
+
|
601
|
+
def delete_adapters(self, adapter_names: Union[List[str], str]):
|
602
|
+
"""
|
603
|
+
Args:
|
604
|
+
Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
|
605
|
+
adapter_names (`Union[List[str], str]`):
|
606
|
+
The names of the adapter to delete. Can be a single string or a list of strings
|
607
|
+
"""
|
608
|
+
if not USE_PEFT_BACKEND:
|
609
|
+
raise ValueError("PEFT backend is required for this method.")
|
610
|
+
|
611
|
+
if isinstance(adapter_names, str):
|
612
|
+
adapter_names = [adapter_names]
|
613
|
+
|
614
|
+
for component in self._lora_loadable_modules:
|
615
|
+
model = getattr(self, component, None)
|
616
|
+
if model is not None:
|
617
|
+
if issubclass(model.__class__, ModelMixin):
|
618
|
+
model.delete_adapters(adapter_names)
|
619
|
+
elif issubclass(model.__class__, PreTrainedModel):
|
620
|
+
for adapter_name in adapter_names:
|
621
|
+
delete_adapter_layers(model, adapter_name)
|
622
|
+
|
623
|
+
def get_active_adapters(self) -> List[str]:
|
624
|
+
"""
|
625
|
+
Gets the list of the current active adapters.
|
626
|
+
|
627
|
+
Example:
|
628
|
+
|
629
|
+
```python
|
630
|
+
from diffusers import DiffusionPipeline
|
631
|
+
|
632
|
+
pipeline = DiffusionPipeline.from_pretrained(
|
633
|
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
634
|
+
).to("cuda")
|
635
|
+
pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
|
636
|
+
pipeline.get_active_adapters()
|
637
|
+
```
|
638
|
+
"""
|
639
|
+
if not USE_PEFT_BACKEND:
|
640
|
+
raise ValueError(
|
641
|
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
642
|
+
)
|
643
|
+
|
644
|
+
active_adapters = []
|
645
|
+
|
646
|
+
for component in self._lora_loadable_modules:
|
647
|
+
model = getattr(self, component, None)
|
648
|
+
if model is not None and issubclass(model.__class__, ModelMixin):
|
649
|
+
for module in model.modules():
|
650
|
+
if isinstance(module, BaseTunerLayer):
|
651
|
+
active_adapters = module.active_adapters
|
652
|
+
break
|
653
|
+
|
654
|
+
return active_adapters
|
655
|
+
|
656
|
+
def get_list_adapters(self) -> Dict[str, List[str]]:
|
657
|
+
"""
|
658
|
+
Gets the current list of all available adapters in the pipeline.
|
659
|
+
"""
|
660
|
+
if not USE_PEFT_BACKEND:
|
661
|
+
raise ValueError(
|
662
|
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
663
|
+
)
|
664
|
+
|
665
|
+
set_adapters = {}
|
666
|
+
|
667
|
+
for component in self._lora_loadable_modules:
|
668
|
+
model = getattr(self, component, None)
|
669
|
+
if (
|
670
|
+
model is not None
|
671
|
+
and issubclass(model.__class__, (ModelMixin, PreTrainedModel))
|
672
|
+
and hasattr(model, "peft_config")
|
673
|
+
):
|
674
|
+
set_adapters[component] = list(model.peft_config.keys())
|
675
|
+
|
676
|
+
return set_adapters
|
677
|
+
|
678
|
+
def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
|
679
|
+
"""
|
680
|
+
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
|
681
|
+
you want to load multiple adapters and free some GPU memory.
|
682
|
+
|
683
|
+
Args:
|
684
|
+
adapter_names (`List[str]`):
|
685
|
+
List of adapters to send device to.
|
686
|
+
device (`Union[torch.device, str, int]`):
|
687
|
+
Device to send the adapters to. Can be either a torch device, a str or an integer.
|
688
|
+
"""
|
689
|
+
if not USE_PEFT_BACKEND:
|
690
|
+
raise ValueError("PEFT backend is required for this method.")
|
691
|
+
|
692
|
+
for component in self._lora_loadable_modules:
|
693
|
+
model = getattr(self, component, None)
|
694
|
+
if model is not None:
|
695
|
+
for module in model.modules():
|
696
|
+
if isinstance(module, BaseTunerLayer):
|
697
|
+
for adapter_name in adapter_names:
|
698
|
+
module.lora_A[adapter_name].to(device)
|
699
|
+
module.lora_B[adapter_name].to(device)
|
700
|
+
# this is a param, not a module, so device placement is not in-place -> re-assign
|
701
|
+
if hasattr(module, "lora_magnitude_vector") and module.lora_magnitude_vector is not None:
|
702
|
+
module.lora_magnitude_vector[adapter_name] = module.lora_magnitude_vector[
|
703
|
+
adapter_name
|
704
|
+
].to(device)
|
705
|
+
|
706
|
+
@staticmethod
|
707
|
+
def pack_weights(layers, prefix):
|
708
|
+
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
709
|
+
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
710
|
+
return layers_state_dict
|
711
|
+
|
712
|
+
@staticmethod
|
713
|
+
def write_lora_layers(
|
714
|
+
state_dict: Dict[str, torch.Tensor],
|
715
|
+
save_directory: str,
|
716
|
+
is_main_process: bool,
|
717
|
+
weight_name: str,
|
718
|
+
save_function: Callable,
|
719
|
+
safe_serialization: bool,
|
720
|
+
):
|
721
|
+
from .lora_pipeline import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE
|
722
|
+
|
723
|
+
if os.path.isfile(save_directory):
|
724
|
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
725
|
+
return
|
726
|
+
|
727
|
+
if save_function is None:
|
728
|
+
if safe_serialization:
|
729
|
+
|
730
|
+
def save_function(weights, filename):
|
731
|
+
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
732
|
+
|
733
|
+
else:
|
734
|
+
save_function = torch.save
|
735
|
+
|
736
|
+
os.makedirs(save_directory, exist_ok=True)
|
737
|
+
|
738
|
+
if weight_name is None:
|
739
|
+
if safe_serialization:
|
740
|
+
weight_name = LORA_WEIGHT_NAME_SAFE
|
741
|
+
else:
|
742
|
+
weight_name = LORA_WEIGHT_NAME
|
743
|
+
|
744
|
+
save_path = Path(save_directory, weight_name).as_posix()
|
745
|
+
save_function(state_dict, save_path)
|
746
|
+
logger.info(f"Model weights saved in {save_path}")
|
747
|
+
|
748
|
+
@property
|
749
|
+
def lora_scale(self) -> float:
|
750
|
+
# property function that returns the lora scale which can be set at run time by the pipeline.
|
751
|
+
# if _lora_scale has not been set, return 1
|
752
|
+
return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
|