diffusers 0.23.1__py3-none-any.whl → 0.25.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +26 -2
- diffusers/commands/fp16_safetensors.py +10 -11
- diffusers/configuration_utils.py +13 -8
- diffusers/dependency_versions_check.py +0 -1
- diffusers/dependency_versions_table.py +5 -5
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/image_processor.py +463 -51
- diffusers/loaders/__init__.py +82 -0
- diffusers/loaders/ip_adapter.py +159 -0
- diffusers/loaders/lora.py +1553 -0
- diffusers/loaders/lora_conversion_utils.py +284 -0
- diffusers/loaders/single_file.py +637 -0
- diffusers/loaders/textual_inversion.py +455 -0
- diffusers/loaders/unet.py +828 -0
- diffusers/loaders/utils.py +59 -0
- diffusers/models/__init__.py +26 -9
- diffusers/models/activations.py +9 -6
- diffusers/models/attention.py +301 -29
- diffusers/models/attention_flax.py +9 -1
- diffusers/models/attention_processor.py +378 -6
- diffusers/models/autoencoders/__init__.py +5 -0
- diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
- diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
- diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
- diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
- diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
- diffusers/models/controlnet.py +59 -39
- diffusers/models/controlnet_flax.py +19 -18
- diffusers/models/downsampling.py +338 -0
- diffusers/models/embeddings.py +112 -29
- diffusers/models/embeddings_flax.py +2 -0
- diffusers/models/lora.py +131 -1
- diffusers/models/modeling_flax_utils.py +14 -8
- diffusers/models/modeling_outputs.py +17 -0
- diffusers/models/modeling_utils.py +37 -29
- diffusers/models/normalization.py +110 -4
- diffusers/models/resnet.py +299 -652
- diffusers/models/transformer_2d.py +22 -5
- diffusers/models/transformer_temporal.py +183 -1
- diffusers/models/unet_2d_blocks_flax.py +5 -0
- diffusers/models/unet_2d_condition.py +46 -0
- diffusers/models/unet_2d_condition_flax.py +13 -13
- diffusers/models/unet_3d_blocks.py +957 -173
- diffusers/models/unet_3d_condition.py +16 -8
- diffusers/models/unet_kandinsky3.py +535 -0
- diffusers/models/unet_motion_model.py +48 -33
- diffusers/models/unet_spatio_temporal_condition.py +489 -0
- diffusers/models/upsampling.py +454 -0
- diffusers/models/uvit_2d.py +471 -0
- diffusers/models/vae_flax.py +7 -0
- diffusers/models/vq_model.py +12 -3
- diffusers/optimization.py +16 -9
- diffusers/pipelines/__init__.py +137 -76
- diffusers/pipelines/amused/__init__.py +62 -0
- diffusers/pipelines/amused/pipeline_amused.py +328 -0
- diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
- diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
- diffusers/pipelines/auto_pipeline.py +23 -13
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
- diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
- diffusers/pipelines/deprecated/__init__.py +153 -0
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
- diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
- diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
- diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
- diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
- diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
- diffusers/pipelines/dit/pipeline_dit.py +1 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
- diffusers/pipelines/kandinsky3/__init__.py +49 -0
- diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
- diffusers/pipelines/onnx_utils.py +8 -5
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
- diffusers/pipelines/pipeline_flax_utils.py +11 -8
- diffusers/pipelines/pipeline_utils.py +63 -42
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
- diffusers/pipelines/stable_diffusion/__init__.py +37 -65
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
- diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
- diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
- diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
- diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
- diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
- diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
- diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
- diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
- diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
- diffusers/schedulers/__init__.py +4 -4
- diffusers/schedulers/deprecated/__init__.py +50 -0
- diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
- diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
- diffusers/schedulers/scheduling_amused.py +162 -0
- diffusers/schedulers/scheduling_consistency_models.py +2 -0
- diffusers/schedulers/scheduling_ddim.py +1 -3
- diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
- diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
- diffusers/schedulers/scheduling_ddpm.py +47 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
- diffusers/schedulers/scheduling_deis_multistep.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
- diffusers/schedulers/scheduling_euler_discrete.py +102 -16
- diffusers/schedulers/scheduling_heun_discrete.py +17 -5
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
- diffusers/schedulers/scheduling_lcm.py +123 -29
- diffusers/schedulers/scheduling_lms_discrete.py +3 -3
- diffusers/schedulers/scheduling_pndm.py +1 -3
- diffusers/schedulers/scheduling_repaint.py +1 -3
- diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
- diffusers/schedulers/scheduling_utils.py +3 -1
- diffusers/schedulers/scheduling_utils_flax.py +3 -1
- diffusers/training_utils.py +1 -1
- diffusers/utils/__init__.py +1 -2
- diffusers/utils/constants.py +10 -12
- diffusers/utils/dummy_pt_objects.py +75 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
- diffusers/utils/dynamic_modules_utils.py +18 -22
- diffusers/utils/export_utils.py +8 -3
- diffusers/utils/hub_utils.py +24 -36
- diffusers/utils/logging.py +11 -11
- diffusers/utils/outputs.py +5 -5
- diffusers/utils/peft_utils.py +88 -44
- diffusers/utils/state_dict_utils.py +8 -0
- diffusers/utils/testing_utils.py +199 -1
- diffusers/utils/torch_utils.py +4 -4
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
- diffusers-0.25.0.dist-info/RECORD +360 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
- diffusers/loaders.py +0 -3336
- diffusers-0.23.1.dist-info/RECORD +0 -323
- /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
diffusers/loaders.py
DELETED
@@ -1,3336 +0,0 @@
|
|
1
|
-
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
import os
|
15
|
-
import re
|
16
|
-
from collections import defaultdict
|
17
|
-
from contextlib import nullcontext
|
18
|
-
from io import BytesIO
|
19
|
-
from pathlib import Path
|
20
|
-
from typing import Callable, Dict, List, Optional, Union
|
21
|
-
|
22
|
-
import requests
|
23
|
-
import safetensors
|
24
|
-
import torch
|
25
|
-
from huggingface_hub import hf_hub_download, model_info
|
26
|
-
from packaging import version
|
27
|
-
from torch import nn
|
28
|
-
|
29
|
-
from . import __version__
|
30
|
-
from .models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
|
31
|
-
from .utils import (
|
32
|
-
DIFFUSERS_CACHE,
|
33
|
-
HF_HUB_OFFLINE,
|
34
|
-
USE_PEFT_BACKEND,
|
35
|
-
_get_model_file,
|
36
|
-
convert_state_dict_to_diffusers,
|
37
|
-
convert_state_dict_to_peft,
|
38
|
-
convert_unet_state_dict_to_peft,
|
39
|
-
deprecate,
|
40
|
-
get_adapter_name,
|
41
|
-
get_peft_kwargs,
|
42
|
-
is_accelerate_available,
|
43
|
-
is_omegaconf_available,
|
44
|
-
is_transformers_available,
|
45
|
-
logging,
|
46
|
-
recurse_remove_peft_layers,
|
47
|
-
scale_lora_layers,
|
48
|
-
set_adapter_layers,
|
49
|
-
set_weights_and_activate_adapters,
|
50
|
-
)
|
51
|
-
from .utils.import_utils import BACKENDS_MAPPING
|
52
|
-
|
53
|
-
|
54
|
-
if is_transformers_available():
|
55
|
-
from transformers import CLIPTextModel, CLIPTextModelWithProjection, PreTrainedModel
|
56
|
-
|
57
|
-
if is_accelerate_available():
|
58
|
-
from accelerate import init_empty_weights
|
59
|
-
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
60
|
-
|
61
|
-
logger = logging.get_logger(__name__)
|
62
|
-
|
63
|
-
TEXT_ENCODER_NAME = "text_encoder"
|
64
|
-
UNET_NAME = "unet"
|
65
|
-
|
66
|
-
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
|
67
|
-
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
|
68
|
-
|
69
|
-
TEXT_INVERSION_NAME = "learned_embeds.bin"
|
70
|
-
TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
|
71
|
-
|
72
|
-
CUSTOM_DIFFUSION_WEIGHT_NAME = "pytorch_custom_diffusion_weights.bin"
|
73
|
-
CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE = "pytorch_custom_diffusion_weights.safetensors"
|
74
|
-
|
75
|
-
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."
|
76
|
-
|
77
|
-
|
78
|
-
class PatchedLoraProjection(nn.Module):
|
79
|
-
def __init__(self, regular_linear_layer, lora_scale=1, network_alpha=None, rank=4, dtype=None):
|
80
|
-
super().__init__()
|
81
|
-
from .models.lora import LoRALinearLayer
|
82
|
-
|
83
|
-
self.regular_linear_layer = regular_linear_layer
|
84
|
-
|
85
|
-
device = self.regular_linear_layer.weight.device
|
86
|
-
|
87
|
-
if dtype is None:
|
88
|
-
dtype = self.regular_linear_layer.weight.dtype
|
89
|
-
|
90
|
-
self.lora_linear_layer = LoRALinearLayer(
|
91
|
-
self.regular_linear_layer.in_features,
|
92
|
-
self.regular_linear_layer.out_features,
|
93
|
-
network_alpha=network_alpha,
|
94
|
-
device=device,
|
95
|
-
dtype=dtype,
|
96
|
-
rank=rank,
|
97
|
-
)
|
98
|
-
|
99
|
-
self.lora_scale = lora_scale
|
100
|
-
|
101
|
-
# overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved
|
102
|
-
# when saving the whole text encoder model and when LoRA is unloaded or fused
|
103
|
-
def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
|
104
|
-
if self.lora_linear_layer is None:
|
105
|
-
return self.regular_linear_layer.state_dict(
|
106
|
-
*args, destination=destination, prefix=prefix, keep_vars=keep_vars
|
107
|
-
)
|
108
|
-
|
109
|
-
return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
|
110
|
-
|
111
|
-
def _fuse_lora(self, lora_scale=1.0, safe_fusing=False):
|
112
|
-
if self.lora_linear_layer is None:
|
113
|
-
return
|
114
|
-
|
115
|
-
dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device
|
116
|
-
|
117
|
-
w_orig = self.regular_linear_layer.weight.data.float()
|
118
|
-
w_up = self.lora_linear_layer.up.weight.data.float()
|
119
|
-
w_down = self.lora_linear_layer.down.weight.data.float()
|
120
|
-
|
121
|
-
if self.lora_linear_layer.network_alpha is not None:
|
122
|
-
w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank
|
123
|
-
|
124
|
-
fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
|
125
|
-
|
126
|
-
if safe_fusing and torch.isnan(fused_weight).any().item():
|
127
|
-
raise ValueError(
|
128
|
-
"This LoRA weight seems to be broken. "
|
129
|
-
f"Encountered NaN values when trying to fuse LoRA weights for {self}."
|
130
|
-
"LoRA weights will not be fused."
|
131
|
-
)
|
132
|
-
|
133
|
-
self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype)
|
134
|
-
|
135
|
-
# we can drop the lora layer now
|
136
|
-
self.lora_linear_layer = None
|
137
|
-
|
138
|
-
# offload the up and down matrices to CPU to not blow the memory
|
139
|
-
self.w_up = w_up.cpu()
|
140
|
-
self.w_down = w_down.cpu()
|
141
|
-
self.lora_scale = lora_scale
|
142
|
-
|
143
|
-
def _unfuse_lora(self):
|
144
|
-
if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
|
145
|
-
return
|
146
|
-
|
147
|
-
fused_weight = self.regular_linear_layer.weight.data
|
148
|
-
dtype, device = fused_weight.dtype, fused_weight.device
|
149
|
-
|
150
|
-
w_up = self.w_up.to(device=device).float()
|
151
|
-
w_down = self.w_down.to(device).float()
|
152
|
-
|
153
|
-
unfused_weight = fused_weight.float() - (self.lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
|
154
|
-
self.regular_linear_layer.weight.data = unfused_weight.to(device=device, dtype=dtype)
|
155
|
-
|
156
|
-
self.w_up = None
|
157
|
-
self.w_down = None
|
158
|
-
|
159
|
-
def forward(self, input):
|
160
|
-
if self.lora_scale is None:
|
161
|
-
self.lora_scale = 1.0
|
162
|
-
if self.lora_linear_layer is None:
|
163
|
-
return self.regular_linear_layer(input)
|
164
|
-
return self.regular_linear_layer(input) + (self.lora_scale * self.lora_linear_layer(input))
|
165
|
-
|
166
|
-
|
167
|
-
def text_encoder_attn_modules(text_encoder):
|
168
|
-
attn_modules = []
|
169
|
-
|
170
|
-
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
|
171
|
-
for i, layer in enumerate(text_encoder.text_model.encoder.layers):
|
172
|
-
name = f"text_model.encoder.layers.{i}.self_attn"
|
173
|
-
mod = layer.self_attn
|
174
|
-
attn_modules.append((name, mod))
|
175
|
-
else:
|
176
|
-
raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
|
177
|
-
|
178
|
-
return attn_modules
|
179
|
-
|
180
|
-
|
181
|
-
def text_encoder_mlp_modules(text_encoder):
|
182
|
-
mlp_modules = []
|
183
|
-
|
184
|
-
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
|
185
|
-
for i, layer in enumerate(text_encoder.text_model.encoder.layers):
|
186
|
-
mlp_mod = layer.mlp
|
187
|
-
name = f"text_model.encoder.layers.{i}.mlp"
|
188
|
-
mlp_modules.append((name, mlp_mod))
|
189
|
-
else:
|
190
|
-
raise ValueError(f"do not know how to get mlp modules for: {text_encoder.__class__.__name__}")
|
191
|
-
|
192
|
-
return mlp_modules
|
193
|
-
|
194
|
-
|
195
|
-
def text_encoder_lora_state_dict(text_encoder):
|
196
|
-
state_dict = {}
|
197
|
-
|
198
|
-
for name, module in text_encoder_attn_modules(text_encoder):
|
199
|
-
for k, v in module.q_proj.lora_linear_layer.state_dict().items():
|
200
|
-
state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
|
201
|
-
|
202
|
-
for k, v in module.k_proj.lora_linear_layer.state_dict().items():
|
203
|
-
state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
|
204
|
-
|
205
|
-
for k, v in module.v_proj.lora_linear_layer.state_dict().items():
|
206
|
-
state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
|
207
|
-
|
208
|
-
for k, v in module.out_proj.lora_linear_layer.state_dict().items():
|
209
|
-
state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
|
210
|
-
|
211
|
-
return state_dict
|
212
|
-
|
213
|
-
|
214
|
-
class AttnProcsLayers(torch.nn.Module):
|
215
|
-
def __init__(self, state_dict: Dict[str, torch.Tensor]):
|
216
|
-
super().__init__()
|
217
|
-
self.layers = torch.nn.ModuleList(state_dict.values())
|
218
|
-
self.mapping = dict(enumerate(state_dict.keys()))
|
219
|
-
self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
|
220
|
-
|
221
|
-
# .processor for unet, .self_attn for text encoder
|
222
|
-
self.split_keys = [".processor", ".self_attn"]
|
223
|
-
|
224
|
-
# we add a hook to state_dict() and load_state_dict() so that the
|
225
|
-
# naming fits with `unet.attn_processors`
|
226
|
-
def map_to(module, state_dict, *args, **kwargs):
|
227
|
-
new_state_dict = {}
|
228
|
-
for key, value in state_dict.items():
|
229
|
-
num = int(key.split(".")[1]) # 0 is always "layers"
|
230
|
-
new_key = key.replace(f"layers.{num}", module.mapping[num])
|
231
|
-
new_state_dict[new_key] = value
|
232
|
-
|
233
|
-
return new_state_dict
|
234
|
-
|
235
|
-
def remap_key(key, state_dict):
|
236
|
-
for k in self.split_keys:
|
237
|
-
if k in key:
|
238
|
-
return key.split(k)[0] + k
|
239
|
-
|
240
|
-
raise ValueError(
|
241
|
-
f"There seems to be a problem with the state_dict: {set(state_dict.keys())}. {key} has to have one of {self.split_keys}."
|
242
|
-
)
|
243
|
-
|
244
|
-
def map_from(module, state_dict, *args, **kwargs):
|
245
|
-
all_keys = list(state_dict.keys())
|
246
|
-
for key in all_keys:
|
247
|
-
replace_key = remap_key(key, state_dict)
|
248
|
-
new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
|
249
|
-
state_dict[new_key] = state_dict[key]
|
250
|
-
del state_dict[key]
|
251
|
-
|
252
|
-
self._register_state_dict_hook(map_to)
|
253
|
-
self._register_load_state_dict_pre_hook(map_from, with_module=True)
|
254
|
-
|
255
|
-
|
256
|
-
class UNet2DConditionLoadersMixin:
|
257
|
-
text_encoder_name = TEXT_ENCODER_NAME
|
258
|
-
unet_name = UNET_NAME
|
259
|
-
|
260
|
-
def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
|
261
|
-
r"""
|
262
|
-
Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
|
263
|
-
defined in
|
264
|
-
[`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
|
265
|
-
and be a `torch.nn.Module` class.
|
266
|
-
|
267
|
-
Parameters:
|
268
|
-
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
269
|
-
Can be either:
|
270
|
-
|
271
|
-
- A string, the model id (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
272
|
-
the Hub.
|
273
|
-
- A path to a directory (for example `./my_model_directory`) containing the model weights saved
|
274
|
-
with [`ModelMixin.save_pretrained`].
|
275
|
-
- A [torch state
|
276
|
-
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
277
|
-
|
278
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
279
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
280
|
-
is not used.
|
281
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
282
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
283
|
-
cached versions if they exist.
|
284
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
285
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
286
|
-
incompletely downloaded files are deleted.
|
287
|
-
proxies (`Dict[str, str]`, *optional*):
|
288
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
289
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
290
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
291
|
-
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
292
|
-
won't be downloaded from the Hub.
|
293
|
-
use_auth_token (`str` or *bool*, *optional*):
|
294
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
295
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
296
|
-
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
297
|
-
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
298
|
-
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
299
|
-
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
300
|
-
argument to `True` will raise an error.
|
301
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
302
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
303
|
-
allowed by Git.
|
304
|
-
subfolder (`str`, *optional*, defaults to `""`):
|
305
|
-
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
306
|
-
mirror (`str`, *optional*):
|
307
|
-
Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
|
308
|
-
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
309
|
-
information.
|
310
|
-
|
311
|
-
"""
|
312
|
-
from .models.attention_processor import (
|
313
|
-
CustomDiffusionAttnProcessor,
|
314
|
-
)
|
315
|
-
from .models.lora import LoRACompatibleConv, LoRACompatibleLinear, LoRAConv2dLayer, LoRALinearLayer
|
316
|
-
|
317
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
318
|
-
force_download = kwargs.pop("force_download", False)
|
319
|
-
resume_download = kwargs.pop("resume_download", False)
|
320
|
-
proxies = kwargs.pop("proxies", None)
|
321
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
322
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
323
|
-
revision = kwargs.pop("revision", None)
|
324
|
-
subfolder = kwargs.pop("subfolder", None)
|
325
|
-
weight_name = kwargs.pop("weight_name", None)
|
326
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
327
|
-
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
328
|
-
# This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
|
329
|
-
# See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
|
330
|
-
network_alphas = kwargs.pop("network_alphas", None)
|
331
|
-
|
332
|
-
_pipeline = kwargs.pop("_pipeline", None)
|
333
|
-
|
334
|
-
is_network_alphas_none = network_alphas is None
|
335
|
-
|
336
|
-
allow_pickle = False
|
337
|
-
|
338
|
-
if use_safetensors is None:
|
339
|
-
use_safetensors = True
|
340
|
-
allow_pickle = True
|
341
|
-
|
342
|
-
user_agent = {
|
343
|
-
"file_type": "attn_procs_weights",
|
344
|
-
"framework": "pytorch",
|
345
|
-
}
|
346
|
-
|
347
|
-
if low_cpu_mem_usage and not is_accelerate_available():
|
348
|
-
low_cpu_mem_usage = False
|
349
|
-
logger.warning(
|
350
|
-
"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
|
351
|
-
" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
|
352
|
-
" `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
|
353
|
-
" install accelerate\n```\n."
|
354
|
-
)
|
355
|
-
|
356
|
-
model_file = None
|
357
|
-
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
358
|
-
# Let's first try to load .safetensors weights
|
359
|
-
if (use_safetensors and weight_name is None) or (
|
360
|
-
weight_name is not None and weight_name.endswith(".safetensors")
|
361
|
-
):
|
362
|
-
try:
|
363
|
-
model_file = _get_model_file(
|
364
|
-
pretrained_model_name_or_path_or_dict,
|
365
|
-
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
366
|
-
cache_dir=cache_dir,
|
367
|
-
force_download=force_download,
|
368
|
-
resume_download=resume_download,
|
369
|
-
proxies=proxies,
|
370
|
-
local_files_only=local_files_only,
|
371
|
-
use_auth_token=use_auth_token,
|
372
|
-
revision=revision,
|
373
|
-
subfolder=subfolder,
|
374
|
-
user_agent=user_agent,
|
375
|
-
)
|
376
|
-
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
377
|
-
except IOError as e:
|
378
|
-
if not allow_pickle:
|
379
|
-
raise e
|
380
|
-
# try loading non-safetensors weights
|
381
|
-
pass
|
382
|
-
if model_file is None:
|
383
|
-
model_file = _get_model_file(
|
384
|
-
pretrained_model_name_or_path_or_dict,
|
385
|
-
weights_name=weight_name or LORA_WEIGHT_NAME,
|
386
|
-
cache_dir=cache_dir,
|
387
|
-
force_download=force_download,
|
388
|
-
resume_download=resume_download,
|
389
|
-
proxies=proxies,
|
390
|
-
local_files_only=local_files_only,
|
391
|
-
use_auth_token=use_auth_token,
|
392
|
-
revision=revision,
|
393
|
-
subfolder=subfolder,
|
394
|
-
user_agent=user_agent,
|
395
|
-
)
|
396
|
-
state_dict = torch.load(model_file, map_location="cpu")
|
397
|
-
else:
|
398
|
-
state_dict = pretrained_model_name_or_path_or_dict
|
399
|
-
|
400
|
-
# fill attn processors
|
401
|
-
lora_layers_list = []
|
402
|
-
|
403
|
-
is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys()) and not USE_PEFT_BACKEND
|
404
|
-
is_custom_diffusion = any("custom_diffusion" in k for k in state_dict.keys())
|
405
|
-
|
406
|
-
if is_lora:
|
407
|
-
# correct keys
|
408
|
-
state_dict, network_alphas = self.convert_state_dict_legacy_attn_format(state_dict, network_alphas)
|
409
|
-
|
410
|
-
if network_alphas is not None:
|
411
|
-
network_alphas_keys = list(network_alphas.keys())
|
412
|
-
used_network_alphas_keys = set()
|
413
|
-
|
414
|
-
lora_grouped_dict = defaultdict(dict)
|
415
|
-
mapped_network_alphas = {}
|
416
|
-
|
417
|
-
all_keys = list(state_dict.keys())
|
418
|
-
for key in all_keys:
|
419
|
-
value = state_dict.pop(key)
|
420
|
-
attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
|
421
|
-
lora_grouped_dict[attn_processor_key][sub_key] = value
|
422
|
-
|
423
|
-
# Create another `mapped_network_alphas` dictionary so that we can properly map them.
|
424
|
-
if network_alphas is not None:
|
425
|
-
for k in network_alphas_keys:
|
426
|
-
if k.replace(".alpha", "") in key:
|
427
|
-
mapped_network_alphas.update({attn_processor_key: network_alphas.get(k)})
|
428
|
-
used_network_alphas_keys.add(k)
|
429
|
-
|
430
|
-
if not is_network_alphas_none:
|
431
|
-
if len(set(network_alphas_keys) - used_network_alphas_keys) > 0:
|
432
|
-
raise ValueError(
|
433
|
-
f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
|
434
|
-
)
|
435
|
-
|
436
|
-
if len(state_dict) > 0:
|
437
|
-
raise ValueError(
|
438
|
-
f"The `state_dict` has to be empty at this point but has the following keys \n\n {', '.join(state_dict.keys())}"
|
439
|
-
)
|
440
|
-
|
441
|
-
for key, value_dict in lora_grouped_dict.items():
|
442
|
-
attn_processor = self
|
443
|
-
for sub_key in key.split("."):
|
444
|
-
attn_processor = getattr(attn_processor, sub_key)
|
445
|
-
|
446
|
-
# Process non-attention layers, which don't have to_{k,v,q,out_proj}_lora layers
|
447
|
-
# or add_{k,v,q,out_proj}_proj_lora layers.
|
448
|
-
rank = value_dict["lora.down.weight"].shape[0]
|
449
|
-
|
450
|
-
if isinstance(attn_processor, LoRACompatibleConv):
|
451
|
-
in_features = attn_processor.in_channels
|
452
|
-
out_features = attn_processor.out_channels
|
453
|
-
kernel_size = attn_processor.kernel_size
|
454
|
-
|
455
|
-
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
456
|
-
with ctx():
|
457
|
-
lora = LoRAConv2dLayer(
|
458
|
-
in_features=in_features,
|
459
|
-
out_features=out_features,
|
460
|
-
rank=rank,
|
461
|
-
kernel_size=kernel_size,
|
462
|
-
stride=attn_processor.stride,
|
463
|
-
padding=attn_processor.padding,
|
464
|
-
network_alpha=mapped_network_alphas.get(key),
|
465
|
-
)
|
466
|
-
elif isinstance(attn_processor, LoRACompatibleLinear):
|
467
|
-
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
468
|
-
with ctx():
|
469
|
-
lora = LoRALinearLayer(
|
470
|
-
attn_processor.in_features,
|
471
|
-
attn_processor.out_features,
|
472
|
-
rank,
|
473
|
-
mapped_network_alphas.get(key),
|
474
|
-
)
|
475
|
-
else:
|
476
|
-
raise ValueError(f"Module {key} is not a LoRACompatibleConv or LoRACompatibleLinear module.")
|
477
|
-
|
478
|
-
value_dict = {k.replace("lora.", ""): v for k, v in value_dict.items()}
|
479
|
-
lora_layers_list.append((attn_processor, lora))
|
480
|
-
|
481
|
-
if low_cpu_mem_usage:
|
482
|
-
device = next(iter(value_dict.values())).device
|
483
|
-
dtype = next(iter(value_dict.values())).dtype
|
484
|
-
load_model_dict_into_meta(lora, value_dict, device=device, dtype=dtype)
|
485
|
-
else:
|
486
|
-
lora.load_state_dict(value_dict)
|
487
|
-
|
488
|
-
elif is_custom_diffusion:
|
489
|
-
attn_processors = {}
|
490
|
-
custom_diffusion_grouped_dict = defaultdict(dict)
|
491
|
-
for key, value in state_dict.items():
|
492
|
-
if len(value) == 0:
|
493
|
-
custom_diffusion_grouped_dict[key] = {}
|
494
|
-
else:
|
495
|
-
if "to_out" in key:
|
496
|
-
attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
|
497
|
-
else:
|
498
|
-
attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
|
499
|
-
custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
|
500
|
-
|
501
|
-
for key, value_dict in custom_diffusion_grouped_dict.items():
|
502
|
-
if len(value_dict) == 0:
|
503
|
-
attn_processors[key] = CustomDiffusionAttnProcessor(
|
504
|
-
train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
|
505
|
-
)
|
506
|
-
else:
|
507
|
-
cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
|
508
|
-
hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
|
509
|
-
train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
|
510
|
-
attn_processors[key] = CustomDiffusionAttnProcessor(
|
511
|
-
train_kv=True,
|
512
|
-
train_q_out=train_q_out,
|
513
|
-
hidden_size=hidden_size,
|
514
|
-
cross_attention_dim=cross_attention_dim,
|
515
|
-
)
|
516
|
-
attn_processors[key].load_state_dict(value_dict)
|
517
|
-
elif USE_PEFT_BACKEND:
|
518
|
-
# In that case we have nothing to do as loading the adapter weights is already handled above by `set_peft_model_state_dict`
|
519
|
-
# on the Unet
|
520
|
-
pass
|
521
|
-
else:
|
522
|
-
raise ValueError(
|
523
|
-
f"{model_file} does not seem to be in the correct format expected by LoRA or Custom Diffusion training."
|
524
|
-
)
|
525
|
-
|
526
|
-
# <Unsafe code
|
527
|
-
# We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
|
528
|
-
# Now we remove any existing hooks to
|
529
|
-
is_model_cpu_offload = False
|
530
|
-
is_sequential_cpu_offload = False
|
531
|
-
|
532
|
-
# For PEFT backend the Unet is already offloaded at this stage as it is handled inside `lora_lora_weights_into_unet`
|
533
|
-
if not USE_PEFT_BACKEND:
|
534
|
-
if _pipeline is not None:
|
535
|
-
for _, component in _pipeline.components.items():
|
536
|
-
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
537
|
-
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
538
|
-
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
539
|
-
|
540
|
-
logger.info(
|
541
|
-
"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."
|
542
|
-
)
|
543
|
-
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
544
|
-
|
545
|
-
# only custom diffusion needs to set attn processors
|
546
|
-
if is_custom_diffusion:
|
547
|
-
self.set_attn_processor(attn_processors)
|
548
|
-
|
549
|
-
# set lora layers
|
550
|
-
for target_module, lora_layer in lora_layers_list:
|
551
|
-
target_module.set_lora_layer(lora_layer)
|
552
|
-
|
553
|
-
self.to(dtype=self.dtype, device=self.device)
|
554
|
-
|
555
|
-
# Offload back.
|
556
|
-
if is_model_cpu_offload:
|
557
|
-
_pipeline.enable_model_cpu_offload()
|
558
|
-
elif is_sequential_cpu_offload:
|
559
|
-
_pipeline.enable_sequential_cpu_offload()
|
560
|
-
# Unsafe code />
|
561
|
-
|
562
|
-
def convert_state_dict_legacy_attn_format(self, state_dict, network_alphas):
|
563
|
-
is_new_lora_format = all(
|
564
|
-
key.startswith(self.unet_name) or key.startswith(self.text_encoder_name) for key in state_dict.keys()
|
565
|
-
)
|
566
|
-
if is_new_lora_format:
|
567
|
-
# Strip the `"unet"` prefix.
|
568
|
-
is_text_encoder_present = any(key.startswith(self.text_encoder_name) for key in state_dict.keys())
|
569
|
-
if is_text_encoder_present:
|
570
|
-
warn_message = "The state_dict contains LoRA params corresponding to the text encoder which are not being used here. To use both UNet and text encoder related LoRA params, use [`pipe.load_lora_weights()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.load_lora_weights)."
|
571
|
-
logger.warn(warn_message)
|
572
|
-
unet_keys = [k for k in state_dict.keys() if k.startswith(self.unet_name)]
|
573
|
-
state_dict = {k.replace(f"{self.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
|
574
|
-
|
575
|
-
# change processor format to 'pure' LoRACompatibleLinear format
|
576
|
-
if any("processor" in k.split(".") for k in state_dict.keys()):
|
577
|
-
|
578
|
-
def format_to_lora_compatible(key):
|
579
|
-
if "processor" not in key.split("."):
|
580
|
-
return key
|
581
|
-
return key.replace(".processor", "").replace("to_out_lora", "to_out.0.lora").replace("_lora", ".lora")
|
582
|
-
|
583
|
-
state_dict = {format_to_lora_compatible(k): v for k, v in state_dict.items()}
|
584
|
-
|
585
|
-
if network_alphas is not None:
|
586
|
-
network_alphas = {format_to_lora_compatible(k): v for k, v in network_alphas.items()}
|
587
|
-
return state_dict, network_alphas
|
588
|
-
|
589
|
-
def save_attn_procs(
|
590
|
-
self,
|
591
|
-
save_directory: Union[str, os.PathLike],
|
592
|
-
is_main_process: bool = True,
|
593
|
-
weight_name: str = None,
|
594
|
-
save_function: Callable = None,
|
595
|
-
safe_serialization: bool = True,
|
596
|
-
**kwargs,
|
597
|
-
):
|
598
|
-
r"""
|
599
|
-
Save an attention processor to a directory so that it can be reloaded using the
|
600
|
-
[`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method.
|
601
|
-
|
602
|
-
Arguments:
|
603
|
-
save_directory (`str` or `os.PathLike`):
|
604
|
-
Directory to save an attention processor to. Will be created if it doesn't exist.
|
605
|
-
is_main_process (`bool`, *optional*, defaults to `True`):
|
606
|
-
Whether the process calling this is the main process or not. Useful during distributed training and you
|
607
|
-
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
608
|
-
process to avoid race conditions.
|
609
|
-
save_function (`Callable`):
|
610
|
-
The function to use to save the state dictionary. Useful during distributed training when you need to
|
611
|
-
replace `torch.save` with another method. Can be configured with the environment variable
|
612
|
-
`DIFFUSERS_SAVE_MODE`.
|
613
|
-
safe_serialization (`bool`, *optional*, defaults to `True`):
|
614
|
-
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
615
|
-
"""
|
616
|
-
from .models.attention_processor import (
|
617
|
-
CustomDiffusionAttnProcessor,
|
618
|
-
CustomDiffusionAttnProcessor2_0,
|
619
|
-
CustomDiffusionXFormersAttnProcessor,
|
620
|
-
)
|
621
|
-
|
622
|
-
if os.path.isfile(save_directory):
|
623
|
-
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
624
|
-
return
|
625
|
-
|
626
|
-
if save_function is None:
|
627
|
-
if safe_serialization:
|
628
|
-
|
629
|
-
def save_function(weights, filename):
|
630
|
-
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
631
|
-
|
632
|
-
else:
|
633
|
-
save_function = torch.save
|
634
|
-
|
635
|
-
os.makedirs(save_directory, exist_ok=True)
|
636
|
-
|
637
|
-
is_custom_diffusion = any(
|
638
|
-
isinstance(
|
639
|
-
x,
|
640
|
-
(CustomDiffusionAttnProcessor, CustomDiffusionAttnProcessor2_0, CustomDiffusionXFormersAttnProcessor),
|
641
|
-
)
|
642
|
-
for (_, x) in self.attn_processors.items()
|
643
|
-
)
|
644
|
-
if is_custom_diffusion:
|
645
|
-
model_to_save = AttnProcsLayers(
|
646
|
-
{
|
647
|
-
y: x
|
648
|
-
for (y, x) in self.attn_processors.items()
|
649
|
-
if isinstance(
|
650
|
-
x,
|
651
|
-
(
|
652
|
-
CustomDiffusionAttnProcessor,
|
653
|
-
CustomDiffusionAttnProcessor2_0,
|
654
|
-
CustomDiffusionXFormersAttnProcessor,
|
655
|
-
),
|
656
|
-
)
|
657
|
-
}
|
658
|
-
)
|
659
|
-
state_dict = model_to_save.state_dict()
|
660
|
-
for name, attn in self.attn_processors.items():
|
661
|
-
if len(attn.state_dict()) == 0:
|
662
|
-
state_dict[name] = {}
|
663
|
-
else:
|
664
|
-
model_to_save = AttnProcsLayers(self.attn_processors)
|
665
|
-
state_dict = model_to_save.state_dict()
|
666
|
-
|
667
|
-
if weight_name is None:
|
668
|
-
if safe_serialization:
|
669
|
-
weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE if is_custom_diffusion else LORA_WEIGHT_NAME_SAFE
|
670
|
-
else:
|
671
|
-
weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME if is_custom_diffusion else LORA_WEIGHT_NAME
|
672
|
-
|
673
|
-
# Save the model
|
674
|
-
save_function(state_dict, os.path.join(save_directory, weight_name))
|
675
|
-
logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
|
676
|
-
|
677
|
-
def fuse_lora(self, lora_scale=1.0, safe_fusing=False):
|
678
|
-
self.lora_scale = lora_scale
|
679
|
-
self._safe_fusing = safe_fusing
|
680
|
-
self.apply(self._fuse_lora_apply)
|
681
|
-
|
682
|
-
def _fuse_lora_apply(self, module):
|
683
|
-
if not USE_PEFT_BACKEND:
|
684
|
-
if hasattr(module, "_fuse_lora"):
|
685
|
-
module._fuse_lora(self.lora_scale, self._safe_fusing)
|
686
|
-
else:
|
687
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
688
|
-
|
689
|
-
if isinstance(module, BaseTunerLayer):
|
690
|
-
if self.lora_scale != 1.0:
|
691
|
-
module.scale_layer(self.lora_scale)
|
692
|
-
module.merge(safe_merge=self._safe_fusing)
|
693
|
-
|
694
|
-
def unfuse_lora(self):
|
695
|
-
self.apply(self._unfuse_lora_apply)
|
696
|
-
|
697
|
-
def _unfuse_lora_apply(self, module):
|
698
|
-
if not USE_PEFT_BACKEND:
|
699
|
-
if hasattr(module, "_unfuse_lora"):
|
700
|
-
module._unfuse_lora()
|
701
|
-
else:
|
702
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
703
|
-
|
704
|
-
if isinstance(module, BaseTunerLayer):
|
705
|
-
module.unmerge()
|
706
|
-
|
707
|
-
def set_adapters(
|
708
|
-
self,
|
709
|
-
adapter_names: Union[List[str], str],
|
710
|
-
weights: Optional[Union[List[float], float]] = None,
|
711
|
-
):
|
712
|
-
"""
|
713
|
-
Sets the adapter layers for the unet.
|
714
|
-
|
715
|
-
Args:
|
716
|
-
adapter_names (`List[str]` or `str`):
|
717
|
-
The names of the adapters to use.
|
718
|
-
weights (`Union[List[float], float]`, *optional*):
|
719
|
-
The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
|
720
|
-
adapters.
|
721
|
-
"""
|
722
|
-
if not USE_PEFT_BACKEND:
|
723
|
-
raise ValueError("PEFT backend is required for `set_adapters()`.")
|
724
|
-
|
725
|
-
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
726
|
-
|
727
|
-
if weights is None:
|
728
|
-
weights = [1.0] * len(adapter_names)
|
729
|
-
elif isinstance(weights, float):
|
730
|
-
weights = [weights] * len(adapter_names)
|
731
|
-
|
732
|
-
if len(adapter_names) != len(weights):
|
733
|
-
raise ValueError(
|
734
|
-
f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
|
735
|
-
)
|
736
|
-
|
737
|
-
set_weights_and_activate_adapters(self, adapter_names, weights)
|
738
|
-
|
739
|
-
def disable_lora(self):
|
740
|
-
"""
|
741
|
-
Disables the active LoRA layers for the unet.
|
742
|
-
"""
|
743
|
-
if not USE_PEFT_BACKEND:
|
744
|
-
raise ValueError("PEFT backend is required for this method.")
|
745
|
-
set_adapter_layers(self, enabled=False)
|
746
|
-
|
747
|
-
def enable_lora(self):
|
748
|
-
"""
|
749
|
-
Enables the active LoRA layers for the unet.
|
750
|
-
"""
|
751
|
-
if not USE_PEFT_BACKEND:
|
752
|
-
raise ValueError("PEFT backend is required for this method.")
|
753
|
-
set_adapter_layers(self, enabled=True)
|
754
|
-
|
755
|
-
|
756
|
-
def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
|
757
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
758
|
-
force_download = kwargs.pop("force_download", False)
|
759
|
-
resume_download = kwargs.pop("resume_download", False)
|
760
|
-
proxies = kwargs.pop("proxies", None)
|
761
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
762
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
763
|
-
revision = kwargs.pop("revision", None)
|
764
|
-
subfolder = kwargs.pop("subfolder", None)
|
765
|
-
weight_name = kwargs.pop("weight_name", None)
|
766
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
767
|
-
|
768
|
-
allow_pickle = False
|
769
|
-
if use_safetensors is None:
|
770
|
-
use_safetensors = True
|
771
|
-
allow_pickle = True
|
772
|
-
|
773
|
-
user_agent = {
|
774
|
-
"file_type": "text_inversion",
|
775
|
-
"framework": "pytorch",
|
776
|
-
}
|
777
|
-
state_dicts = []
|
778
|
-
for pretrained_model_name_or_path in pretrained_model_name_or_paths:
|
779
|
-
if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
|
780
|
-
# 3.1. Load textual inversion file
|
781
|
-
model_file = None
|
782
|
-
|
783
|
-
# Let's first try to load .safetensors weights
|
784
|
-
if (use_safetensors and weight_name is None) or (
|
785
|
-
weight_name is not None and weight_name.endswith(".safetensors")
|
786
|
-
):
|
787
|
-
try:
|
788
|
-
model_file = _get_model_file(
|
789
|
-
pretrained_model_name_or_path,
|
790
|
-
weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
|
791
|
-
cache_dir=cache_dir,
|
792
|
-
force_download=force_download,
|
793
|
-
resume_download=resume_download,
|
794
|
-
proxies=proxies,
|
795
|
-
local_files_only=local_files_only,
|
796
|
-
use_auth_token=use_auth_token,
|
797
|
-
revision=revision,
|
798
|
-
subfolder=subfolder,
|
799
|
-
user_agent=user_agent,
|
800
|
-
)
|
801
|
-
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
802
|
-
except Exception as e:
|
803
|
-
if not allow_pickle:
|
804
|
-
raise e
|
805
|
-
|
806
|
-
model_file = None
|
807
|
-
|
808
|
-
if model_file is None:
|
809
|
-
model_file = _get_model_file(
|
810
|
-
pretrained_model_name_or_path,
|
811
|
-
weights_name=weight_name or TEXT_INVERSION_NAME,
|
812
|
-
cache_dir=cache_dir,
|
813
|
-
force_download=force_download,
|
814
|
-
resume_download=resume_download,
|
815
|
-
proxies=proxies,
|
816
|
-
local_files_only=local_files_only,
|
817
|
-
use_auth_token=use_auth_token,
|
818
|
-
revision=revision,
|
819
|
-
subfolder=subfolder,
|
820
|
-
user_agent=user_agent,
|
821
|
-
)
|
822
|
-
state_dict = torch.load(model_file, map_location="cpu")
|
823
|
-
else:
|
824
|
-
state_dict = pretrained_model_name_or_path
|
825
|
-
|
826
|
-
state_dicts.append(state_dict)
|
827
|
-
|
828
|
-
return state_dicts
|
829
|
-
|
830
|
-
|
831
|
-
class TextualInversionLoaderMixin:
|
832
|
-
r"""
|
833
|
-
Load textual inversion tokens and embeddings to the tokenizer and text encoder.
|
834
|
-
"""
|
835
|
-
|
836
|
-
def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
837
|
-
r"""
|
838
|
-
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
|
839
|
-
be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
840
|
-
inversion token or if the textual inversion token is a single vector, the input prompt is returned.
|
841
|
-
|
842
|
-
Parameters:
|
843
|
-
prompt (`str` or list of `str`):
|
844
|
-
The prompt or prompts to guide the image generation.
|
845
|
-
tokenizer (`PreTrainedTokenizer`):
|
846
|
-
The tokenizer responsible for encoding the prompt into input tokens.
|
847
|
-
|
848
|
-
Returns:
|
849
|
-
`str` or list of `str`: The converted prompt
|
850
|
-
"""
|
851
|
-
if not isinstance(prompt, List):
|
852
|
-
prompts = [prompt]
|
853
|
-
else:
|
854
|
-
prompts = prompt
|
855
|
-
|
856
|
-
prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
|
857
|
-
|
858
|
-
if not isinstance(prompt, List):
|
859
|
-
return prompts[0]
|
860
|
-
|
861
|
-
return prompts
|
862
|
-
|
863
|
-
def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
864
|
-
r"""
|
865
|
-
Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
|
866
|
-
to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
|
867
|
-
is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
868
|
-
inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
|
869
|
-
|
870
|
-
Parameters:
|
871
|
-
prompt (`str`):
|
872
|
-
The prompt to guide the image generation.
|
873
|
-
tokenizer (`PreTrainedTokenizer`):
|
874
|
-
The tokenizer responsible for encoding the prompt into input tokens.
|
875
|
-
|
876
|
-
Returns:
|
877
|
-
`str`: The converted prompt
|
878
|
-
"""
|
879
|
-
tokens = tokenizer.tokenize(prompt)
|
880
|
-
unique_tokens = set(tokens)
|
881
|
-
for token in unique_tokens:
|
882
|
-
if token in tokenizer.added_tokens_encoder:
|
883
|
-
replacement = token
|
884
|
-
i = 1
|
885
|
-
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
886
|
-
replacement += f" {token}_{i}"
|
887
|
-
i += 1
|
888
|
-
|
889
|
-
prompt = prompt.replace(token, replacement)
|
890
|
-
|
891
|
-
return prompt
|
892
|
-
|
893
|
-
def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
|
894
|
-
if tokenizer is None:
|
895
|
-
raise ValueError(
|
896
|
-
f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
|
897
|
-
f" `{self.load_textual_inversion.__name__}`"
|
898
|
-
)
|
899
|
-
|
900
|
-
if text_encoder is None:
|
901
|
-
raise ValueError(
|
902
|
-
f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
|
903
|
-
f" `{self.load_textual_inversion.__name__}`"
|
904
|
-
)
|
905
|
-
|
906
|
-
if len(pretrained_model_name_or_paths) != len(tokens):
|
907
|
-
raise ValueError(
|
908
|
-
f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
|
909
|
-
f"Make sure both lists have the same length."
|
910
|
-
)
|
911
|
-
|
912
|
-
valid_tokens = [t for t in tokens if t is not None]
|
913
|
-
if len(set(valid_tokens)) < len(valid_tokens):
|
914
|
-
raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
|
915
|
-
|
916
|
-
@staticmethod
|
917
|
-
def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
|
918
|
-
all_tokens = []
|
919
|
-
all_embeddings = []
|
920
|
-
for state_dict, token in zip(state_dicts, tokens):
|
921
|
-
if isinstance(state_dict, torch.Tensor):
|
922
|
-
if token is None:
|
923
|
-
raise ValueError(
|
924
|
-
"You are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`."
|
925
|
-
)
|
926
|
-
loaded_token = token
|
927
|
-
embedding = state_dict
|
928
|
-
elif len(state_dict) == 1:
|
929
|
-
# diffusers
|
930
|
-
loaded_token, embedding = next(iter(state_dict.items()))
|
931
|
-
elif "string_to_param" in state_dict:
|
932
|
-
# A1111
|
933
|
-
loaded_token = state_dict["name"]
|
934
|
-
embedding = state_dict["string_to_param"]["*"]
|
935
|
-
else:
|
936
|
-
raise ValueError(
|
937
|
-
f"Loaded state dictonary is incorrect: {state_dict}. \n\n"
|
938
|
-
"Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
|
939
|
-
" input key."
|
940
|
-
)
|
941
|
-
|
942
|
-
if token is not None and loaded_token != token:
|
943
|
-
logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
|
944
|
-
else:
|
945
|
-
token = loaded_token
|
946
|
-
|
947
|
-
if token in tokenizer.get_vocab():
|
948
|
-
raise ValueError(
|
949
|
-
f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
|
950
|
-
)
|
951
|
-
|
952
|
-
all_tokens.append(token)
|
953
|
-
all_embeddings.append(embedding)
|
954
|
-
|
955
|
-
return all_tokens, all_embeddings
|
956
|
-
|
957
|
-
@staticmethod
|
958
|
-
def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
|
959
|
-
all_tokens = []
|
960
|
-
all_embeddings = []
|
961
|
-
|
962
|
-
for embedding, token in zip(embeddings, tokens):
|
963
|
-
if f"{token}_1" in tokenizer.get_vocab():
|
964
|
-
multi_vector_tokens = [token]
|
965
|
-
i = 1
|
966
|
-
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
967
|
-
multi_vector_tokens.append(f"{token}_{i}")
|
968
|
-
i += 1
|
969
|
-
|
970
|
-
raise ValueError(
|
971
|
-
f"Multi-vector Token {multi_vector_tokens} already in tokenizer vocabulary. Please choose a different token name or remove the {multi_vector_tokens} and embedding from the tokenizer and text encoder."
|
972
|
-
)
|
973
|
-
|
974
|
-
is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
|
975
|
-
if is_multi_vector:
|
976
|
-
all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
|
977
|
-
all_embeddings += [e for e in embedding] # noqa: C416
|
978
|
-
else:
|
979
|
-
all_tokens += [token]
|
980
|
-
all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
|
981
|
-
|
982
|
-
return all_tokens, all_embeddings
|
983
|
-
|
984
|
-
def load_textual_inversion(
|
985
|
-
self,
|
986
|
-
pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
|
987
|
-
token: Optional[Union[str, List[str]]] = None,
|
988
|
-
tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
|
989
|
-
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
990
|
-
**kwargs,
|
991
|
-
):
|
992
|
-
r"""
|
993
|
-
Load textual inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
|
994
|
-
Automatic1111 formats are supported).
|
995
|
-
|
996
|
-
Parameters:
|
997
|
-
pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
|
998
|
-
Can be either one of the following or a list of them:
|
999
|
-
|
1000
|
-
- A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
|
1001
|
-
pretrained model hosted on the Hub.
|
1002
|
-
- A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
|
1003
|
-
inversion weights.
|
1004
|
-
- A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
|
1005
|
-
- A [torch state
|
1006
|
-
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
1007
|
-
|
1008
|
-
token (`str` or `List[str]`, *optional*):
|
1009
|
-
Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
|
1010
|
-
list, then `token` must also be a list of equal length.
|
1011
|
-
text_encoder ([`~transformers.CLIPTextModel`], *optional*):
|
1012
|
-
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
1013
|
-
If not specified, function will take self.tokenizer.
|
1014
|
-
tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
|
1015
|
-
A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
|
1016
|
-
weight_name (`str`, *optional*):
|
1017
|
-
Name of a custom weight file. This should be used when:
|
1018
|
-
|
1019
|
-
- The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
|
1020
|
-
name such as `text_inv.bin`.
|
1021
|
-
- The saved textual inversion file is in the Automatic1111 format.
|
1022
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
1023
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
1024
|
-
is not used.
|
1025
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
1026
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
1027
|
-
cached versions if they exist.
|
1028
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
1029
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
1030
|
-
incompletely downloaded files are deleted.
|
1031
|
-
proxies (`Dict[str, str]`, *optional*):
|
1032
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
1033
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
1034
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
1035
|
-
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
1036
|
-
won't be downloaded from the Hub.
|
1037
|
-
use_auth_token (`str` or *bool*, *optional*):
|
1038
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
1039
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
1040
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
1041
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
1042
|
-
allowed by Git.
|
1043
|
-
subfolder (`str`, *optional*, defaults to `""`):
|
1044
|
-
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
1045
|
-
mirror (`str`, *optional*):
|
1046
|
-
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
1047
|
-
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
1048
|
-
information.
|
1049
|
-
|
1050
|
-
Example:
|
1051
|
-
|
1052
|
-
To load a textual inversion embedding vector in 🤗 Diffusers format:
|
1053
|
-
|
1054
|
-
```py
|
1055
|
-
from diffusers import StableDiffusionPipeline
|
1056
|
-
import torch
|
1057
|
-
|
1058
|
-
model_id = "runwayml/stable-diffusion-v1-5"
|
1059
|
-
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
1060
|
-
|
1061
|
-
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
|
1062
|
-
|
1063
|
-
prompt = "A <cat-toy> backpack"
|
1064
|
-
|
1065
|
-
image = pipe(prompt, num_inference_steps=50).images[0]
|
1066
|
-
image.save("cat-backpack.png")
|
1067
|
-
```
|
1068
|
-
|
1069
|
-
To load a textual inversion embedding vector in Automatic1111 format, make sure to download the vector first
|
1070
|
-
(for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
|
1071
|
-
locally:
|
1072
|
-
|
1073
|
-
```py
|
1074
|
-
from diffusers import StableDiffusionPipeline
|
1075
|
-
import torch
|
1076
|
-
|
1077
|
-
model_id = "runwayml/stable-diffusion-v1-5"
|
1078
|
-
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
1079
|
-
|
1080
|
-
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
|
1081
|
-
|
1082
|
-
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
|
1083
|
-
|
1084
|
-
image = pipe(prompt, num_inference_steps=50).images[0]
|
1085
|
-
image.save("character.png")
|
1086
|
-
```
|
1087
|
-
|
1088
|
-
"""
|
1089
|
-
# 1. Set correct tokenizer and text encoder
|
1090
|
-
tokenizer = tokenizer or getattr(self, "tokenizer", None)
|
1091
|
-
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
1092
|
-
|
1093
|
-
# 2. Normalize inputs
|
1094
|
-
pretrained_model_name_or_paths = (
|
1095
|
-
[pretrained_model_name_or_path]
|
1096
|
-
if not isinstance(pretrained_model_name_or_path, list)
|
1097
|
-
else pretrained_model_name_or_path
|
1098
|
-
)
|
1099
|
-
tokens = len(pretrained_model_name_or_paths) * [token] if (isinstance(token, str) or token is None) else token
|
1100
|
-
|
1101
|
-
# 3. Check inputs
|
1102
|
-
self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
|
1103
|
-
|
1104
|
-
# 4. Load state dicts of textual embeddings
|
1105
|
-
state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
|
1106
|
-
|
1107
|
-
# 4. Retrieve tokens and embeddings
|
1108
|
-
tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
|
1109
|
-
|
1110
|
-
# 5. Extend tokens and embeddings for multi vector
|
1111
|
-
tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
|
1112
|
-
|
1113
|
-
# 6. Make sure all embeddings have the correct size
|
1114
|
-
expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
|
1115
|
-
if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
|
1116
|
-
raise ValueError(
|
1117
|
-
"Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
|
1118
|
-
"to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
|
1119
|
-
)
|
1120
|
-
|
1121
|
-
# 7. Now we can be sure that loading the embedding matrix works
|
1122
|
-
# < Unsafe code:
|
1123
|
-
|
1124
|
-
# 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
|
1125
|
-
is_model_cpu_offload = False
|
1126
|
-
is_sequential_cpu_offload = False
|
1127
|
-
for _, component in self.components.items():
|
1128
|
-
if isinstance(component, nn.Module):
|
1129
|
-
if hasattr(component, "_hf_hook"):
|
1130
|
-
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
1131
|
-
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
1132
|
-
logger.info(
|
1133
|
-
"Accelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again."
|
1134
|
-
)
|
1135
|
-
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
1136
|
-
|
1137
|
-
# 7.2 save expected device and dtype
|
1138
|
-
device = text_encoder.device
|
1139
|
-
dtype = text_encoder.dtype
|
1140
|
-
|
1141
|
-
# 7.3 Increase token embedding matrix
|
1142
|
-
text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
|
1143
|
-
input_embeddings = text_encoder.get_input_embeddings().weight
|
1144
|
-
|
1145
|
-
# 7.4 Load token and embedding
|
1146
|
-
for token, embedding in zip(tokens, embeddings):
|
1147
|
-
# add tokens and get ids
|
1148
|
-
tokenizer.add_tokens(token)
|
1149
|
-
token_id = tokenizer.convert_tokens_to_ids(token)
|
1150
|
-
input_embeddings.data[token_id] = embedding
|
1151
|
-
logger.info(f"Loaded textual inversion embedding for {token}.")
|
1152
|
-
|
1153
|
-
input_embeddings.to(dtype=dtype, device=device)
|
1154
|
-
|
1155
|
-
# 7.5 Offload the model again
|
1156
|
-
if is_model_cpu_offload:
|
1157
|
-
self.enable_model_cpu_offload()
|
1158
|
-
elif is_sequential_cpu_offload:
|
1159
|
-
self.enable_sequential_cpu_offload()
|
1160
|
-
|
1161
|
-
# / Unsafe Code >
|
1162
|
-
|
1163
|
-
|
1164
|
-
class LoraLoaderMixin:
|
1165
|
-
r"""
|
1166
|
-
Load LoRA layers into [`UNet2DConditionModel`] and
|
1167
|
-
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
|
1168
|
-
"""
|
1169
|
-
text_encoder_name = TEXT_ENCODER_NAME
|
1170
|
-
unet_name = UNET_NAME
|
1171
|
-
num_fused_loras = 0
|
1172
|
-
|
1173
|
-
def load_lora_weights(
|
1174
|
-
self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
|
1175
|
-
):
|
1176
|
-
"""
|
1177
|
-
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
1178
|
-
`self.text_encoder`.
|
1179
|
-
|
1180
|
-
All kwargs are forwarded to `self.lora_state_dict`.
|
1181
|
-
|
1182
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
1183
|
-
|
1184
|
-
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
1185
|
-
`self.unet`.
|
1186
|
-
|
1187
|
-
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
1188
|
-
into `self.text_encoder`.
|
1189
|
-
|
1190
|
-
Parameters:
|
1191
|
-
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
1192
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
1193
|
-
kwargs (`dict`, *optional*):
|
1194
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
1195
|
-
adapter_name (`str`, *optional*):
|
1196
|
-
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
1197
|
-
`default_{i}` where i is the total number of adapters being loaded.
|
1198
|
-
"""
|
1199
|
-
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
1200
|
-
state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
|
1201
|
-
|
1202
|
-
is_correct_format = all("lora" in key for key in state_dict.keys())
|
1203
|
-
if not is_correct_format:
|
1204
|
-
raise ValueError("Invalid LoRA checkpoint.")
|
1205
|
-
|
1206
|
-
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
1207
|
-
|
1208
|
-
self.load_lora_into_unet(
|
1209
|
-
state_dict,
|
1210
|
-
network_alphas=network_alphas,
|
1211
|
-
unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
|
1212
|
-
low_cpu_mem_usage=low_cpu_mem_usage,
|
1213
|
-
adapter_name=adapter_name,
|
1214
|
-
_pipeline=self,
|
1215
|
-
)
|
1216
|
-
self.load_lora_into_text_encoder(
|
1217
|
-
state_dict,
|
1218
|
-
network_alphas=network_alphas,
|
1219
|
-
text_encoder=getattr(self, self.text_encoder_name)
|
1220
|
-
if not hasattr(self, "text_encoder")
|
1221
|
-
else self.text_encoder,
|
1222
|
-
lora_scale=self.lora_scale,
|
1223
|
-
low_cpu_mem_usage=low_cpu_mem_usage,
|
1224
|
-
adapter_name=adapter_name,
|
1225
|
-
_pipeline=self,
|
1226
|
-
)
|
1227
|
-
|
1228
|
-
@classmethod
|
1229
|
-
def lora_state_dict(
|
1230
|
-
cls,
|
1231
|
-
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
1232
|
-
**kwargs,
|
1233
|
-
):
|
1234
|
-
r"""
|
1235
|
-
Return state dict for lora weights and the network alphas.
|
1236
|
-
|
1237
|
-
<Tip warning={true}>
|
1238
|
-
|
1239
|
-
We support loading A1111 formatted LoRA checkpoints in a limited capacity.
|
1240
|
-
|
1241
|
-
This function is experimental and might change in the future.
|
1242
|
-
|
1243
|
-
</Tip>
|
1244
|
-
|
1245
|
-
Parameters:
|
1246
|
-
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
1247
|
-
Can be either:
|
1248
|
-
|
1249
|
-
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
1250
|
-
the Hub.
|
1251
|
-
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
|
1252
|
-
with [`ModelMixin.save_pretrained`].
|
1253
|
-
- A [torch state
|
1254
|
-
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
1255
|
-
|
1256
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
1257
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
1258
|
-
is not used.
|
1259
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
1260
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
1261
|
-
cached versions if they exist.
|
1262
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
1263
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
1264
|
-
incompletely downloaded files are deleted.
|
1265
|
-
proxies (`Dict[str, str]`, *optional*):
|
1266
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
1267
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
1268
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
1269
|
-
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
1270
|
-
won't be downloaded from the Hub.
|
1271
|
-
use_auth_token (`str` or *bool*, *optional*):
|
1272
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
1273
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
1274
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
1275
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
1276
|
-
allowed by Git.
|
1277
|
-
subfolder (`str`, *optional*, defaults to `""`):
|
1278
|
-
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
1279
|
-
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
1280
|
-
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
1281
|
-
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
1282
|
-
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
1283
|
-
argument to `True` will raise an error.
|
1284
|
-
mirror (`str`, *optional*):
|
1285
|
-
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
1286
|
-
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
1287
|
-
information.
|
1288
|
-
|
1289
|
-
"""
|
1290
|
-
# Load the main state dict first which has the LoRA layers for either of
|
1291
|
-
# UNet and text encoder or both.
|
1292
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
1293
|
-
force_download = kwargs.pop("force_download", False)
|
1294
|
-
resume_download = kwargs.pop("resume_download", False)
|
1295
|
-
proxies = kwargs.pop("proxies", None)
|
1296
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
1297
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
1298
|
-
revision = kwargs.pop("revision", None)
|
1299
|
-
subfolder = kwargs.pop("subfolder", None)
|
1300
|
-
weight_name = kwargs.pop("weight_name", None)
|
1301
|
-
unet_config = kwargs.pop("unet_config", None)
|
1302
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
1303
|
-
|
1304
|
-
allow_pickle = False
|
1305
|
-
if use_safetensors is None:
|
1306
|
-
use_safetensors = True
|
1307
|
-
allow_pickle = True
|
1308
|
-
|
1309
|
-
user_agent = {
|
1310
|
-
"file_type": "attn_procs_weights",
|
1311
|
-
"framework": "pytorch",
|
1312
|
-
}
|
1313
|
-
|
1314
|
-
model_file = None
|
1315
|
-
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
1316
|
-
# Let's first try to load .safetensors weights
|
1317
|
-
if (use_safetensors and weight_name is None) or (
|
1318
|
-
weight_name is not None and weight_name.endswith(".safetensors")
|
1319
|
-
):
|
1320
|
-
try:
|
1321
|
-
# Here we're relaxing the loading check to enable more Inference API
|
1322
|
-
# friendliness where sometimes, it's not at all possible to automatically
|
1323
|
-
# determine `weight_name`.
|
1324
|
-
if weight_name is None:
|
1325
|
-
weight_name = cls._best_guess_weight_name(
|
1326
|
-
pretrained_model_name_or_path_or_dict, file_extension=".safetensors"
|
1327
|
-
)
|
1328
|
-
model_file = _get_model_file(
|
1329
|
-
pretrained_model_name_or_path_or_dict,
|
1330
|
-
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
1331
|
-
cache_dir=cache_dir,
|
1332
|
-
force_download=force_download,
|
1333
|
-
resume_download=resume_download,
|
1334
|
-
proxies=proxies,
|
1335
|
-
local_files_only=local_files_only,
|
1336
|
-
use_auth_token=use_auth_token,
|
1337
|
-
revision=revision,
|
1338
|
-
subfolder=subfolder,
|
1339
|
-
user_agent=user_agent,
|
1340
|
-
)
|
1341
|
-
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
1342
|
-
except (IOError, safetensors.SafetensorError) as e:
|
1343
|
-
if not allow_pickle:
|
1344
|
-
raise e
|
1345
|
-
# try loading non-safetensors weights
|
1346
|
-
model_file = None
|
1347
|
-
pass
|
1348
|
-
|
1349
|
-
if model_file is None:
|
1350
|
-
if weight_name is None:
|
1351
|
-
weight_name = cls._best_guess_weight_name(
|
1352
|
-
pretrained_model_name_or_path_or_dict, file_extension=".bin"
|
1353
|
-
)
|
1354
|
-
model_file = _get_model_file(
|
1355
|
-
pretrained_model_name_or_path_or_dict,
|
1356
|
-
weights_name=weight_name or LORA_WEIGHT_NAME,
|
1357
|
-
cache_dir=cache_dir,
|
1358
|
-
force_download=force_download,
|
1359
|
-
resume_download=resume_download,
|
1360
|
-
proxies=proxies,
|
1361
|
-
local_files_only=local_files_only,
|
1362
|
-
use_auth_token=use_auth_token,
|
1363
|
-
revision=revision,
|
1364
|
-
subfolder=subfolder,
|
1365
|
-
user_agent=user_agent,
|
1366
|
-
)
|
1367
|
-
state_dict = torch.load(model_file, map_location="cpu")
|
1368
|
-
else:
|
1369
|
-
state_dict = pretrained_model_name_or_path_or_dict
|
1370
|
-
|
1371
|
-
network_alphas = None
|
1372
|
-
# TODO: replace it with a method from `state_dict_utils`
|
1373
|
-
if all(
|
1374
|
-
(
|
1375
|
-
k.startswith("lora_te_")
|
1376
|
-
or k.startswith("lora_unet_")
|
1377
|
-
or k.startswith("lora_te1_")
|
1378
|
-
or k.startswith("lora_te2_")
|
1379
|
-
)
|
1380
|
-
for k in state_dict.keys()
|
1381
|
-
):
|
1382
|
-
# Map SDXL blocks correctly.
|
1383
|
-
if unet_config is not None:
|
1384
|
-
# use unet config to remap block numbers
|
1385
|
-
state_dict = cls._maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
|
1386
|
-
state_dict, network_alphas = cls._convert_kohya_lora_to_diffusers(state_dict)
|
1387
|
-
|
1388
|
-
return state_dict, network_alphas
|
1389
|
-
|
1390
|
-
@classmethod
|
1391
|
-
def _best_guess_weight_name(cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors"):
|
1392
|
-
targeted_files = []
|
1393
|
-
|
1394
|
-
if os.path.isfile(pretrained_model_name_or_path_or_dict):
|
1395
|
-
return
|
1396
|
-
elif os.path.isdir(pretrained_model_name_or_path_or_dict):
|
1397
|
-
targeted_files = [
|
1398
|
-
f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
|
1399
|
-
]
|
1400
|
-
else:
|
1401
|
-
files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
|
1402
|
-
targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
|
1403
|
-
if len(targeted_files) == 0:
|
1404
|
-
return
|
1405
|
-
|
1406
|
-
# "scheduler" does not correspond to a LoRA checkpoint.
|
1407
|
-
# "optimizer" does not correspond to a LoRA checkpoint
|
1408
|
-
# only top-level checkpoints are considered and not the other ones, hence "checkpoint".
|
1409
|
-
unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
|
1410
|
-
targeted_files = list(
|
1411
|
-
filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
|
1412
|
-
)
|
1413
|
-
|
1414
|
-
if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
|
1415
|
-
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
|
1416
|
-
elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
|
1417
|
-
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
|
1418
|
-
|
1419
|
-
if len(targeted_files) > 1:
|
1420
|
-
raise ValueError(
|
1421
|
-
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}."
|
1422
|
-
)
|
1423
|
-
weight_name = targeted_files[0]
|
1424
|
-
return weight_name
|
1425
|
-
|
1426
|
-
@classmethod
|
1427
|
-
def _maybe_map_sgm_blocks_to_diffusers(cls, state_dict, unet_config, delimiter="_", block_slice_pos=5):
|
1428
|
-
# 1. get all state_dict_keys
|
1429
|
-
all_keys = list(state_dict.keys())
|
1430
|
-
sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
|
1431
|
-
|
1432
|
-
# 2. check if needs remapping, if not return original dict
|
1433
|
-
is_in_sgm_format = False
|
1434
|
-
for key in all_keys:
|
1435
|
-
if any(p in key for p in sgm_patterns):
|
1436
|
-
is_in_sgm_format = True
|
1437
|
-
break
|
1438
|
-
|
1439
|
-
if not is_in_sgm_format:
|
1440
|
-
return state_dict
|
1441
|
-
|
1442
|
-
# 3. Else remap from SGM patterns
|
1443
|
-
new_state_dict = {}
|
1444
|
-
inner_block_map = ["resnets", "attentions", "upsamplers"]
|
1445
|
-
|
1446
|
-
# Retrieves # of down, mid and up blocks
|
1447
|
-
input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
|
1448
|
-
|
1449
|
-
for layer in all_keys:
|
1450
|
-
if "text" in layer:
|
1451
|
-
new_state_dict[layer] = state_dict.pop(layer)
|
1452
|
-
else:
|
1453
|
-
layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
|
1454
|
-
if sgm_patterns[0] in layer:
|
1455
|
-
input_block_ids.add(layer_id)
|
1456
|
-
elif sgm_patterns[1] in layer:
|
1457
|
-
middle_block_ids.add(layer_id)
|
1458
|
-
elif sgm_patterns[2] in layer:
|
1459
|
-
output_block_ids.add(layer_id)
|
1460
|
-
else:
|
1461
|
-
raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
|
1462
|
-
|
1463
|
-
input_blocks = {
|
1464
|
-
layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
|
1465
|
-
for layer_id in input_block_ids
|
1466
|
-
}
|
1467
|
-
middle_blocks = {
|
1468
|
-
layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
|
1469
|
-
for layer_id in middle_block_ids
|
1470
|
-
}
|
1471
|
-
output_blocks = {
|
1472
|
-
layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
|
1473
|
-
for layer_id in output_block_ids
|
1474
|
-
}
|
1475
|
-
|
1476
|
-
# Rename keys accordingly
|
1477
|
-
for i in input_block_ids:
|
1478
|
-
block_id = (i - 1) // (unet_config.layers_per_block + 1)
|
1479
|
-
layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
|
1480
|
-
|
1481
|
-
for key in input_blocks[i]:
|
1482
|
-
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
1483
|
-
inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
|
1484
|
-
inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
|
1485
|
-
new_key = delimiter.join(
|
1486
|
-
key.split(delimiter)[: block_slice_pos - 1]
|
1487
|
-
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
1488
|
-
+ key.split(delimiter)[block_slice_pos + 1 :]
|
1489
|
-
)
|
1490
|
-
new_state_dict[new_key] = state_dict.pop(key)
|
1491
|
-
|
1492
|
-
for i in middle_block_ids:
|
1493
|
-
key_part = None
|
1494
|
-
if i == 0:
|
1495
|
-
key_part = [inner_block_map[0], "0"]
|
1496
|
-
elif i == 1:
|
1497
|
-
key_part = [inner_block_map[1], "0"]
|
1498
|
-
elif i == 2:
|
1499
|
-
key_part = [inner_block_map[0], "1"]
|
1500
|
-
else:
|
1501
|
-
raise ValueError(f"Invalid middle block id {i}.")
|
1502
|
-
|
1503
|
-
for key in middle_blocks[i]:
|
1504
|
-
new_key = delimiter.join(
|
1505
|
-
key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
|
1506
|
-
)
|
1507
|
-
new_state_dict[new_key] = state_dict.pop(key)
|
1508
|
-
|
1509
|
-
for i in output_block_ids:
|
1510
|
-
block_id = i // (unet_config.layers_per_block + 1)
|
1511
|
-
layer_in_block_id = i % (unet_config.layers_per_block + 1)
|
1512
|
-
|
1513
|
-
for key in output_blocks[i]:
|
1514
|
-
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
1515
|
-
inner_block_key = inner_block_map[inner_block_id]
|
1516
|
-
inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
|
1517
|
-
new_key = delimiter.join(
|
1518
|
-
key.split(delimiter)[: block_slice_pos - 1]
|
1519
|
-
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
1520
|
-
+ key.split(delimiter)[block_slice_pos + 1 :]
|
1521
|
-
)
|
1522
|
-
new_state_dict[new_key] = state_dict.pop(key)
|
1523
|
-
|
1524
|
-
if len(state_dict) > 0:
|
1525
|
-
raise ValueError("At this point all state dict entries have to be converted.")
|
1526
|
-
|
1527
|
-
return new_state_dict
|
1528
|
-
|
1529
|
-
@classmethod
|
1530
|
-
def _optionally_disable_offloading(cls, _pipeline):
|
1531
|
-
"""
|
1532
|
-
Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
|
1533
|
-
|
1534
|
-
Args:
|
1535
|
-
_pipeline (`DiffusionPipeline`):
|
1536
|
-
The pipeline to disable offloading for.
|
1537
|
-
|
1538
|
-
Returns:
|
1539
|
-
tuple:
|
1540
|
-
A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
|
1541
|
-
"""
|
1542
|
-
is_model_cpu_offload = False
|
1543
|
-
is_sequential_cpu_offload = False
|
1544
|
-
|
1545
|
-
if _pipeline is not None:
|
1546
|
-
for _, component in _pipeline.components.items():
|
1547
|
-
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
1548
|
-
if not is_model_cpu_offload:
|
1549
|
-
is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
|
1550
|
-
if not is_sequential_cpu_offload:
|
1551
|
-
is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
|
1552
|
-
|
1553
|
-
logger.info(
|
1554
|
-
"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."
|
1555
|
-
)
|
1556
|
-
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
1557
|
-
|
1558
|
-
return (is_model_cpu_offload, is_sequential_cpu_offload)
|
1559
|
-
|
1560
|
-
@classmethod
|
1561
|
-
def load_lora_into_unet(
|
1562
|
-
cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
|
1563
|
-
):
|
1564
|
-
"""
|
1565
|
-
This will load the LoRA layers specified in `state_dict` into `unet`.
|
1566
|
-
|
1567
|
-
Parameters:
|
1568
|
-
state_dict (`dict`):
|
1569
|
-
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
|
1570
|
-
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
|
1571
|
-
encoder lora layers.
|
1572
|
-
network_alphas (`Dict[str, float]`):
|
1573
|
-
See `LoRALinearLayer` for more details.
|
1574
|
-
unet (`UNet2DConditionModel`):
|
1575
|
-
The UNet model to load the LoRA layers into.
|
1576
|
-
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
1577
|
-
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
1578
|
-
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
1579
|
-
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
1580
|
-
argument to `True` will raise an error.
|
1581
|
-
adapter_name (`str`, *optional*):
|
1582
|
-
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
1583
|
-
`default_{i}` where i is the total number of adapters being loaded.
|
1584
|
-
"""
|
1585
|
-
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
1586
|
-
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
1587
|
-
# then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
|
1588
|
-
# their prefixes.
|
1589
|
-
keys = list(state_dict.keys())
|
1590
|
-
|
1591
|
-
if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
|
1592
|
-
# Load the layers corresponding to UNet.
|
1593
|
-
logger.info(f"Loading {cls.unet_name}.")
|
1594
|
-
|
1595
|
-
unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
|
1596
|
-
state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
|
1597
|
-
|
1598
|
-
if network_alphas is not None:
|
1599
|
-
alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
|
1600
|
-
network_alphas = {
|
1601
|
-
k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
1602
|
-
}
|
1603
|
-
|
1604
|
-
else:
|
1605
|
-
# Otherwise, we're dealing with the old format. This means the `state_dict` should only
|
1606
|
-
# contain the module names of the `unet` as its keys WITHOUT any prefix.
|
1607
|
-
warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
|
1608
|
-
logger.warn(warn_message)
|
1609
|
-
|
1610
|
-
if USE_PEFT_BACKEND and len(state_dict.keys()) > 0:
|
1611
|
-
from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
|
1612
|
-
|
1613
|
-
if adapter_name in getattr(unet, "peft_config", {}):
|
1614
|
-
raise ValueError(
|
1615
|
-
f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
|
1616
|
-
)
|
1617
|
-
|
1618
|
-
state_dict = convert_unet_state_dict_to_peft(state_dict)
|
1619
|
-
|
1620
|
-
if network_alphas is not None:
|
1621
|
-
# The alphas state dict have the same structure as Unet, thus we convert it to peft format using
|
1622
|
-
# `convert_unet_state_dict_to_peft` method.
|
1623
|
-
network_alphas = convert_unet_state_dict_to_peft(network_alphas)
|
1624
|
-
|
1625
|
-
rank = {}
|
1626
|
-
for key, val in state_dict.items():
|
1627
|
-
if "lora_B" in key:
|
1628
|
-
rank[key] = val.shape[1]
|
1629
|
-
|
1630
|
-
lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
|
1631
|
-
lora_config = LoraConfig(**lora_config_kwargs)
|
1632
|
-
|
1633
|
-
# adapter_name
|
1634
|
-
if adapter_name is None:
|
1635
|
-
adapter_name = get_adapter_name(unet)
|
1636
|
-
|
1637
|
-
# In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
|
1638
|
-
# otherwise loading LoRA weights will lead to an error
|
1639
|
-
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
1640
|
-
|
1641
|
-
inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
|
1642
|
-
incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
|
1643
|
-
|
1644
|
-
if incompatible_keys is not None:
|
1645
|
-
# check only for unexpected keys
|
1646
|
-
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
1647
|
-
if unexpected_keys:
|
1648
|
-
logger.warning(
|
1649
|
-
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
1650
|
-
f" {unexpected_keys}. "
|
1651
|
-
)
|
1652
|
-
|
1653
|
-
# Offload back.
|
1654
|
-
if is_model_cpu_offload:
|
1655
|
-
_pipeline.enable_model_cpu_offload()
|
1656
|
-
elif is_sequential_cpu_offload:
|
1657
|
-
_pipeline.enable_sequential_cpu_offload()
|
1658
|
-
# Unsafe code />
|
1659
|
-
|
1660
|
-
unet.load_attn_procs(
|
1661
|
-
state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
|
1662
|
-
)
|
1663
|
-
|
1664
|
-
@classmethod
|
1665
|
-
def load_lora_into_text_encoder(
|
1666
|
-
cls,
|
1667
|
-
state_dict,
|
1668
|
-
network_alphas,
|
1669
|
-
text_encoder,
|
1670
|
-
prefix=None,
|
1671
|
-
lora_scale=1.0,
|
1672
|
-
low_cpu_mem_usage=None,
|
1673
|
-
adapter_name=None,
|
1674
|
-
_pipeline=None,
|
1675
|
-
):
|
1676
|
-
"""
|
1677
|
-
This will load the LoRA layers specified in `state_dict` into `text_encoder`
|
1678
|
-
|
1679
|
-
Parameters:
|
1680
|
-
state_dict (`dict`):
|
1681
|
-
A standard state dict containing the lora layer parameters. The key should be prefixed with an
|
1682
|
-
additional `text_encoder` to distinguish between unet lora layers.
|
1683
|
-
network_alphas (`Dict[str, float]`):
|
1684
|
-
See `LoRALinearLayer` for more details.
|
1685
|
-
text_encoder (`CLIPTextModel`):
|
1686
|
-
The text encoder model to load the LoRA layers into.
|
1687
|
-
prefix (`str`):
|
1688
|
-
Expected prefix of the `text_encoder` in the `state_dict`.
|
1689
|
-
lora_scale (`float`):
|
1690
|
-
How much to scale the output of the lora linear layer before it is added with the output of the regular
|
1691
|
-
lora layer.
|
1692
|
-
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
1693
|
-
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
1694
|
-
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
1695
|
-
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
1696
|
-
argument to `True` will raise an error.
|
1697
|
-
adapter_name (`str`, *optional*):
|
1698
|
-
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
1699
|
-
`default_{i}` where i is the total number of adapters being loaded.
|
1700
|
-
"""
|
1701
|
-
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
1702
|
-
|
1703
|
-
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
1704
|
-
# then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
|
1705
|
-
# their prefixes.
|
1706
|
-
keys = list(state_dict.keys())
|
1707
|
-
prefix = cls.text_encoder_name if prefix is None else prefix
|
1708
|
-
|
1709
|
-
# Safe prefix to check with.
|
1710
|
-
if any(cls.text_encoder_name in key for key in keys):
|
1711
|
-
# Load the layers corresponding to text encoder and make necessary adjustments.
|
1712
|
-
text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
|
1713
|
-
text_encoder_lora_state_dict = {
|
1714
|
-
k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
|
1715
|
-
}
|
1716
|
-
|
1717
|
-
if len(text_encoder_lora_state_dict) > 0:
|
1718
|
-
logger.info(f"Loading {prefix}.")
|
1719
|
-
rank = {}
|
1720
|
-
text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
|
1721
|
-
|
1722
|
-
if USE_PEFT_BACKEND:
|
1723
|
-
# convert state dict
|
1724
|
-
text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
|
1725
|
-
|
1726
|
-
for name, _ in text_encoder_attn_modules(text_encoder):
|
1727
|
-
rank_key = f"{name}.out_proj.lora_B.weight"
|
1728
|
-
rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
|
1729
|
-
|
1730
|
-
patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
|
1731
|
-
if patch_mlp:
|
1732
|
-
for name, _ in text_encoder_mlp_modules(text_encoder):
|
1733
|
-
rank_key_fc1 = f"{name}.fc1.lora_B.weight"
|
1734
|
-
rank_key_fc2 = f"{name}.fc2.lora_B.weight"
|
1735
|
-
|
1736
|
-
rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
|
1737
|
-
rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
|
1738
|
-
else:
|
1739
|
-
for name, _ in text_encoder_attn_modules(text_encoder):
|
1740
|
-
rank_key = f"{name}.out_proj.lora_linear_layer.up.weight"
|
1741
|
-
rank.update({rank_key: text_encoder_lora_state_dict[rank_key].shape[1]})
|
1742
|
-
|
1743
|
-
patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
|
1744
|
-
if patch_mlp:
|
1745
|
-
for name, _ in text_encoder_mlp_modules(text_encoder):
|
1746
|
-
rank_key_fc1 = f"{name}.fc1.lora_linear_layer.up.weight"
|
1747
|
-
rank_key_fc2 = f"{name}.fc2.lora_linear_layer.up.weight"
|
1748
|
-
rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
|
1749
|
-
rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
|
1750
|
-
|
1751
|
-
if network_alphas is not None:
|
1752
|
-
alpha_keys = [
|
1753
|
-
k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
|
1754
|
-
]
|
1755
|
-
network_alphas = {
|
1756
|
-
k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
1757
|
-
}
|
1758
|
-
|
1759
|
-
if USE_PEFT_BACKEND:
|
1760
|
-
from peft import LoraConfig
|
1761
|
-
|
1762
|
-
lora_config_kwargs = get_peft_kwargs(
|
1763
|
-
rank, network_alphas, text_encoder_lora_state_dict, is_unet=False
|
1764
|
-
)
|
1765
|
-
|
1766
|
-
lora_config = LoraConfig(**lora_config_kwargs)
|
1767
|
-
|
1768
|
-
# adapter_name
|
1769
|
-
if adapter_name is None:
|
1770
|
-
adapter_name = get_adapter_name(text_encoder)
|
1771
|
-
|
1772
|
-
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
1773
|
-
|
1774
|
-
# inject LoRA layers and load the state dict
|
1775
|
-
# in transformers we automatically check whether the adapter name is already in use or not
|
1776
|
-
text_encoder.load_adapter(
|
1777
|
-
adapter_name=adapter_name,
|
1778
|
-
adapter_state_dict=text_encoder_lora_state_dict,
|
1779
|
-
peft_config=lora_config,
|
1780
|
-
)
|
1781
|
-
|
1782
|
-
# scale LoRA layers with `lora_scale`
|
1783
|
-
scale_lora_layers(text_encoder, weight=lora_scale)
|
1784
|
-
else:
|
1785
|
-
cls._modify_text_encoder(
|
1786
|
-
text_encoder,
|
1787
|
-
lora_scale,
|
1788
|
-
network_alphas,
|
1789
|
-
rank=rank,
|
1790
|
-
patch_mlp=patch_mlp,
|
1791
|
-
low_cpu_mem_usage=low_cpu_mem_usage,
|
1792
|
-
)
|
1793
|
-
|
1794
|
-
is_pipeline_offloaded = _pipeline is not None and any(
|
1795
|
-
isinstance(c, torch.nn.Module) and hasattr(c, "_hf_hook")
|
1796
|
-
for c in _pipeline.components.values()
|
1797
|
-
)
|
1798
|
-
if is_pipeline_offloaded and low_cpu_mem_usage:
|
1799
|
-
low_cpu_mem_usage = True
|
1800
|
-
logger.info(
|
1801
|
-
f"Pipeline {_pipeline.__class__} is offloaded. Therefore low cpu mem usage loading is forced."
|
1802
|
-
)
|
1803
|
-
|
1804
|
-
if low_cpu_mem_usage:
|
1805
|
-
device = next(iter(text_encoder_lora_state_dict.values())).device
|
1806
|
-
dtype = next(iter(text_encoder_lora_state_dict.values())).dtype
|
1807
|
-
unexpected_keys = load_model_dict_into_meta(
|
1808
|
-
text_encoder, text_encoder_lora_state_dict, device=device, dtype=dtype
|
1809
|
-
)
|
1810
|
-
else:
|
1811
|
-
load_state_dict_results = text_encoder.load_state_dict(
|
1812
|
-
text_encoder_lora_state_dict, strict=False
|
1813
|
-
)
|
1814
|
-
unexpected_keys = load_state_dict_results.unexpected_keys
|
1815
|
-
|
1816
|
-
if len(unexpected_keys) != 0:
|
1817
|
-
raise ValueError(
|
1818
|
-
f"failed to load text encoder state dict, unexpected keys: {load_state_dict_results.unexpected_keys}"
|
1819
|
-
)
|
1820
|
-
|
1821
|
-
# <Unsafe code
|
1822
|
-
# We can be sure that the following works as all we do is change the dtype and device of the text encoder
|
1823
|
-
# Now we remove any existing hooks to
|
1824
|
-
is_model_cpu_offload = False
|
1825
|
-
is_sequential_cpu_offload = False
|
1826
|
-
if _pipeline is not None:
|
1827
|
-
for _, component in _pipeline.components.items():
|
1828
|
-
if isinstance(component, torch.nn.Module):
|
1829
|
-
if hasattr(component, "_hf_hook"):
|
1830
|
-
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
1831
|
-
is_sequential_cpu_offload = isinstance(
|
1832
|
-
getattr(component, "_hf_hook"), AlignDevicesHook
|
1833
|
-
)
|
1834
|
-
logger.info(
|
1835
|
-
"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."
|
1836
|
-
)
|
1837
|
-
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
1838
|
-
|
1839
|
-
text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
|
1840
|
-
|
1841
|
-
# Offload back.
|
1842
|
-
if is_model_cpu_offload:
|
1843
|
-
_pipeline.enable_model_cpu_offload()
|
1844
|
-
elif is_sequential_cpu_offload:
|
1845
|
-
_pipeline.enable_sequential_cpu_offload()
|
1846
|
-
# Unsafe code />
|
1847
|
-
|
1848
|
-
@property
|
1849
|
-
def lora_scale(self) -> float:
|
1850
|
-
# property function that returns the lora scale which can be set at run time by the pipeline.
|
1851
|
-
# if _lora_scale has not been set, return 1
|
1852
|
-
return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
|
1853
|
-
|
1854
|
-
def _remove_text_encoder_monkey_patch(self):
|
1855
|
-
if USE_PEFT_BACKEND:
|
1856
|
-
remove_method = recurse_remove_peft_layers
|
1857
|
-
else:
|
1858
|
-
remove_method = self._remove_text_encoder_monkey_patch_classmethod
|
1859
|
-
|
1860
|
-
if hasattr(self, "text_encoder"):
|
1861
|
-
remove_method(self.text_encoder)
|
1862
|
-
|
1863
|
-
# In case text encoder have no Lora attached
|
1864
|
-
if USE_PEFT_BACKEND and getattr(self.text_encoder, "peft_config", None) is not None:
|
1865
|
-
del self.text_encoder.peft_config
|
1866
|
-
self.text_encoder._hf_peft_config_loaded = None
|
1867
|
-
if hasattr(self, "text_encoder_2"):
|
1868
|
-
remove_method(self.text_encoder_2)
|
1869
|
-
if USE_PEFT_BACKEND:
|
1870
|
-
del self.text_encoder_2.peft_config
|
1871
|
-
self.text_encoder_2._hf_peft_config_loaded = None
|
1872
|
-
|
1873
|
-
@classmethod
|
1874
|
-
def _remove_text_encoder_monkey_patch_classmethod(cls, text_encoder):
|
1875
|
-
if version.parse(__version__) > version.parse("0.23"):
|
1876
|
-
deprecate("_remove_text_encoder_monkey_patch_classmethod", "0.25", LORA_DEPRECATION_MESSAGE)
|
1877
|
-
|
1878
|
-
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
1879
|
-
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
1880
|
-
attn_module.q_proj.lora_linear_layer = None
|
1881
|
-
attn_module.k_proj.lora_linear_layer = None
|
1882
|
-
attn_module.v_proj.lora_linear_layer = None
|
1883
|
-
attn_module.out_proj.lora_linear_layer = None
|
1884
|
-
|
1885
|
-
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
1886
|
-
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
1887
|
-
mlp_module.fc1.lora_linear_layer = None
|
1888
|
-
mlp_module.fc2.lora_linear_layer = None
|
1889
|
-
|
1890
|
-
@classmethod
|
1891
|
-
def _modify_text_encoder(
|
1892
|
-
cls,
|
1893
|
-
text_encoder,
|
1894
|
-
lora_scale=1,
|
1895
|
-
network_alphas=None,
|
1896
|
-
rank: Union[Dict[str, int], int] = 4,
|
1897
|
-
dtype=None,
|
1898
|
-
patch_mlp=False,
|
1899
|
-
low_cpu_mem_usage=False,
|
1900
|
-
):
|
1901
|
-
r"""
|
1902
|
-
Monkey-patches the forward passes of attention modules of the text encoder.
|
1903
|
-
"""
|
1904
|
-
if version.parse(__version__) > version.parse("0.23"):
|
1905
|
-
deprecate("_modify_text_encoder", "0.25", LORA_DEPRECATION_MESSAGE)
|
1906
|
-
|
1907
|
-
def create_patched_linear_lora(model, network_alpha, rank, dtype, lora_parameters):
|
1908
|
-
linear_layer = model.regular_linear_layer if isinstance(model, PatchedLoraProjection) else model
|
1909
|
-
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
1910
|
-
with ctx():
|
1911
|
-
model = PatchedLoraProjection(linear_layer, lora_scale, network_alpha, rank, dtype=dtype)
|
1912
|
-
|
1913
|
-
lora_parameters.extend(model.lora_linear_layer.parameters())
|
1914
|
-
return model
|
1915
|
-
|
1916
|
-
# First, remove any monkey-patch that might have been applied before
|
1917
|
-
cls._remove_text_encoder_monkey_patch_classmethod(text_encoder)
|
1918
|
-
|
1919
|
-
lora_parameters = []
|
1920
|
-
network_alphas = {} if network_alphas is None else network_alphas
|
1921
|
-
is_network_alphas_populated = len(network_alphas) > 0
|
1922
|
-
|
1923
|
-
for name, attn_module in text_encoder_attn_modules(text_encoder):
|
1924
|
-
query_alpha = network_alphas.pop(name + ".to_q_lora.down.weight.alpha", None)
|
1925
|
-
key_alpha = network_alphas.pop(name + ".to_k_lora.down.weight.alpha", None)
|
1926
|
-
value_alpha = network_alphas.pop(name + ".to_v_lora.down.weight.alpha", None)
|
1927
|
-
out_alpha = network_alphas.pop(name + ".to_out_lora.down.weight.alpha", None)
|
1928
|
-
|
1929
|
-
if isinstance(rank, dict):
|
1930
|
-
current_rank = rank.pop(f"{name}.out_proj.lora_linear_layer.up.weight")
|
1931
|
-
else:
|
1932
|
-
current_rank = rank
|
1933
|
-
|
1934
|
-
attn_module.q_proj = create_patched_linear_lora(
|
1935
|
-
attn_module.q_proj, query_alpha, current_rank, dtype, lora_parameters
|
1936
|
-
)
|
1937
|
-
attn_module.k_proj = create_patched_linear_lora(
|
1938
|
-
attn_module.k_proj, key_alpha, current_rank, dtype, lora_parameters
|
1939
|
-
)
|
1940
|
-
attn_module.v_proj = create_patched_linear_lora(
|
1941
|
-
attn_module.v_proj, value_alpha, current_rank, dtype, lora_parameters
|
1942
|
-
)
|
1943
|
-
attn_module.out_proj = create_patched_linear_lora(
|
1944
|
-
attn_module.out_proj, out_alpha, current_rank, dtype, lora_parameters
|
1945
|
-
)
|
1946
|
-
|
1947
|
-
if patch_mlp:
|
1948
|
-
for name, mlp_module in text_encoder_mlp_modules(text_encoder):
|
1949
|
-
fc1_alpha = network_alphas.pop(name + ".fc1.lora_linear_layer.down.weight.alpha", None)
|
1950
|
-
fc2_alpha = network_alphas.pop(name + ".fc2.lora_linear_layer.down.weight.alpha", None)
|
1951
|
-
|
1952
|
-
current_rank_fc1 = rank.pop(f"{name}.fc1.lora_linear_layer.up.weight")
|
1953
|
-
current_rank_fc2 = rank.pop(f"{name}.fc2.lora_linear_layer.up.weight")
|
1954
|
-
|
1955
|
-
mlp_module.fc1 = create_patched_linear_lora(
|
1956
|
-
mlp_module.fc1, fc1_alpha, current_rank_fc1, dtype, lora_parameters
|
1957
|
-
)
|
1958
|
-
mlp_module.fc2 = create_patched_linear_lora(
|
1959
|
-
mlp_module.fc2, fc2_alpha, current_rank_fc2, dtype, lora_parameters
|
1960
|
-
)
|
1961
|
-
|
1962
|
-
if is_network_alphas_populated and len(network_alphas) > 0:
|
1963
|
-
raise ValueError(
|
1964
|
-
f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
|
1965
|
-
)
|
1966
|
-
|
1967
|
-
return lora_parameters
|
1968
|
-
|
1969
|
-
@classmethod
|
1970
|
-
def save_lora_weights(
|
1971
|
-
cls,
|
1972
|
-
save_directory: Union[str, os.PathLike],
|
1973
|
-
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
1974
|
-
text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
|
1975
|
-
is_main_process: bool = True,
|
1976
|
-
weight_name: str = None,
|
1977
|
-
save_function: Callable = None,
|
1978
|
-
safe_serialization: bool = True,
|
1979
|
-
):
|
1980
|
-
r"""
|
1981
|
-
Save the LoRA parameters corresponding to the UNet and text encoder.
|
1982
|
-
|
1983
|
-
Arguments:
|
1984
|
-
save_directory (`str` or `os.PathLike`):
|
1985
|
-
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
1986
|
-
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
1987
|
-
State dict of the LoRA layers corresponding to the `unet`.
|
1988
|
-
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
1989
|
-
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
1990
|
-
encoder LoRA state dict because it comes from 🤗 Transformers.
|
1991
|
-
is_main_process (`bool`, *optional*, defaults to `True`):
|
1992
|
-
Whether the process calling this is the main process or not. Useful during distributed training and you
|
1993
|
-
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
1994
|
-
process to avoid race conditions.
|
1995
|
-
save_function (`Callable`):
|
1996
|
-
The function to use to save the state dictionary. Useful during distributed training when you need to
|
1997
|
-
replace `torch.save` with another method. Can be configured with the environment variable
|
1998
|
-
`DIFFUSERS_SAVE_MODE`.
|
1999
|
-
safe_serialization (`bool`, *optional*, defaults to `True`):
|
2000
|
-
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
2001
|
-
"""
|
2002
|
-
# Create a flat dictionary.
|
2003
|
-
state_dict = {}
|
2004
|
-
|
2005
|
-
# Populate the dictionary.
|
2006
|
-
if unet_lora_layers is not None:
|
2007
|
-
weights = (
|
2008
|
-
unet_lora_layers.state_dict() if isinstance(unet_lora_layers, torch.nn.Module) else unet_lora_layers
|
2009
|
-
)
|
2010
|
-
|
2011
|
-
unet_lora_state_dict = {f"{cls.unet_name}.{module_name}": param for module_name, param in weights.items()}
|
2012
|
-
state_dict.update(unet_lora_state_dict)
|
2013
|
-
|
2014
|
-
if text_encoder_lora_layers is not None:
|
2015
|
-
weights = (
|
2016
|
-
text_encoder_lora_layers.state_dict()
|
2017
|
-
if isinstance(text_encoder_lora_layers, torch.nn.Module)
|
2018
|
-
else text_encoder_lora_layers
|
2019
|
-
)
|
2020
|
-
|
2021
|
-
text_encoder_lora_state_dict = {
|
2022
|
-
f"{cls.text_encoder_name}.{module_name}": param for module_name, param in weights.items()
|
2023
|
-
}
|
2024
|
-
state_dict.update(text_encoder_lora_state_dict)
|
2025
|
-
|
2026
|
-
# Save the model
|
2027
|
-
cls.write_lora_layers(
|
2028
|
-
state_dict=state_dict,
|
2029
|
-
save_directory=save_directory,
|
2030
|
-
is_main_process=is_main_process,
|
2031
|
-
weight_name=weight_name,
|
2032
|
-
save_function=save_function,
|
2033
|
-
safe_serialization=safe_serialization,
|
2034
|
-
)
|
2035
|
-
|
2036
|
-
@staticmethod
|
2037
|
-
def write_lora_layers(
|
2038
|
-
state_dict: Dict[str, torch.Tensor],
|
2039
|
-
save_directory: str,
|
2040
|
-
is_main_process: bool,
|
2041
|
-
weight_name: str,
|
2042
|
-
save_function: Callable,
|
2043
|
-
safe_serialization: bool,
|
2044
|
-
):
|
2045
|
-
if os.path.isfile(save_directory):
|
2046
|
-
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
2047
|
-
return
|
2048
|
-
|
2049
|
-
if save_function is None:
|
2050
|
-
if safe_serialization:
|
2051
|
-
|
2052
|
-
def save_function(weights, filename):
|
2053
|
-
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
2054
|
-
|
2055
|
-
else:
|
2056
|
-
save_function = torch.save
|
2057
|
-
|
2058
|
-
os.makedirs(save_directory, exist_ok=True)
|
2059
|
-
|
2060
|
-
if weight_name is None:
|
2061
|
-
if safe_serialization:
|
2062
|
-
weight_name = LORA_WEIGHT_NAME_SAFE
|
2063
|
-
else:
|
2064
|
-
weight_name = LORA_WEIGHT_NAME
|
2065
|
-
|
2066
|
-
save_function(state_dict, os.path.join(save_directory, weight_name))
|
2067
|
-
logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
|
2068
|
-
|
2069
|
-
@classmethod
|
2070
|
-
def _convert_kohya_lora_to_diffusers(cls, state_dict):
|
2071
|
-
unet_state_dict = {}
|
2072
|
-
te_state_dict = {}
|
2073
|
-
te2_state_dict = {}
|
2074
|
-
network_alphas = {}
|
2075
|
-
|
2076
|
-
# every down weight has a corresponding up weight and potentially an alpha weight
|
2077
|
-
lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
|
2078
|
-
for key in lora_keys:
|
2079
|
-
lora_name = key.split(".")[0]
|
2080
|
-
lora_name_up = lora_name + ".lora_up.weight"
|
2081
|
-
lora_name_alpha = lora_name + ".alpha"
|
2082
|
-
|
2083
|
-
if lora_name.startswith("lora_unet_"):
|
2084
|
-
diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
|
2085
|
-
|
2086
|
-
if "input.blocks" in diffusers_name:
|
2087
|
-
diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
|
2088
|
-
else:
|
2089
|
-
diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
|
2090
|
-
|
2091
|
-
if "middle.block" in diffusers_name:
|
2092
|
-
diffusers_name = diffusers_name.replace("middle.block", "mid_block")
|
2093
|
-
else:
|
2094
|
-
diffusers_name = diffusers_name.replace("mid.block", "mid_block")
|
2095
|
-
if "output.blocks" in diffusers_name:
|
2096
|
-
diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
|
2097
|
-
else:
|
2098
|
-
diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
|
2099
|
-
|
2100
|
-
diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
|
2101
|
-
diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
|
2102
|
-
diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
|
2103
|
-
diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
|
2104
|
-
diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
|
2105
|
-
diffusers_name = diffusers_name.replace("proj.in", "proj_in")
|
2106
|
-
diffusers_name = diffusers_name.replace("proj.out", "proj_out")
|
2107
|
-
diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
|
2108
|
-
|
2109
|
-
# SDXL specificity.
|
2110
|
-
if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
|
2111
|
-
pattern = r"\.\d+(?=\D*$)"
|
2112
|
-
diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
|
2113
|
-
if ".in." in diffusers_name:
|
2114
|
-
diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
|
2115
|
-
if ".out." in diffusers_name:
|
2116
|
-
diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
|
2117
|
-
if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
|
2118
|
-
diffusers_name = diffusers_name.replace("op", "conv")
|
2119
|
-
if "skip" in diffusers_name:
|
2120
|
-
diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
|
2121
|
-
|
2122
|
-
# LyCORIS specificity.
|
2123
|
-
if "time.emb.proj" in diffusers_name:
|
2124
|
-
diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
|
2125
|
-
if "conv.shortcut" in diffusers_name:
|
2126
|
-
diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
|
2127
|
-
|
2128
|
-
# General coverage.
|
2129
|
-
if "transformer_blocks" in diffusers_name:
|
2130
|
-
if "attn1" in diffusers_name or "attn2" in diffusers_name:
|
2131
|
-
diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
|
2132
|
-
diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
|
2133
|
-
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
2134
|
-
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2135
|
-
elif "ff" in diffusers_name:
|
2136
|
-
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
2137
|
-
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2138
|
-
elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
|
2139
|
-
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
2140
|
-
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2141
|
-
else:
|
2142
|
-
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
2143
|
-
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2144
|
-
|
2145
|
-
elif lora_name.startswith("lora_te_"):
|
2146
|
-
diffusers_name = key.replace("lora_te_", "").replace("_", ".")
|
2147
|
-
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
2148
|
-
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
2149
|
-
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
2150
|
-
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
2151
|
-
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
2152
|
-
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
2153
|
-
if "self_attn" in diffusers_name:
|
2154
|
-
te_state_dict[diffusers_name] = state_dict.pop(key)
|
2155
|
-
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2156
|
-
elif "mlp" in diffusers_name:
|
2157
|
-
# Be aware that this is the new diffusers convention and the rest of the code might
|
2158
|
-
# not utilize it yet.
|
2159
|
-
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
2160
|
-
te_state_dict[diffusers_name] = state_dict.pop(key)
|
2161
|
-
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2162
|
-
|
2163
|
-
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
2164
|
-
elif lora_name.startswith("lora_te1_"):
|
2165
|
-
diffusers_name = key.replace("lora_te1_", "").replace("_", ".")
|
2166
|
-
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
2167
|
-
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
2168
|
-
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
2169
|
-
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
2170
|
-
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
2171
|
-
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
2172
|
-
if "self_attn" in diffusers_name:
|
2173
|
-
te_state_dict[diffusers_name] = state_dict.pop(key)
|
2174
|
-
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2175
|
-
elif "mlp" in diffusers_name:
|
2176
|
-
# Be aware that this is the new diffusers convention and the rest of the code might
|
2177
|
-
# not utilize it yet.
|
2178
|
-
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
2179
|
-
te_state_dict[diffusers_name] = state_dict.pop(key)
|
2180
|
-
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2181
|
-
|
2182
|
-
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
2183
|
-
elif lora_name.startswith("lora_te2_"):
|
2184
|
-
diffusers_name = key.replace("lora_te2_", "").replace("_", ".")
|
2185
|
-
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
2186
|
-
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
2187
|
-
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
2188
|
-
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
2189
|
-
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
2190
|
-
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
2191
|
-
if "self_attn" in diffusers_name:
|
2192
|
-
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
2193
|
-
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2194
|
-
elif "mlp" in diffusers_name:
|
2195
|
-
# Be aware that this is the new diffusers convention and the rest of the code might
|
2196
|
-
# not utilize it yet.
|
2197
|
-
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
2198
|
-
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
2199
|
-
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
2200
|
-
|
2201
|
-
# Rename the alphas so that they can be mapped appropriately.
|
2202
|
-
if lora_name_alpha in state_dict:
|
2203
|
-
alpha = state_dict.pop(lora_name_alpha).item()
|
2204
|
-
if lora_name_alpha.startswith("lora_unet_"):
|
2205
|
-
prefix = "unet."
|
2206
|
-
elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
|
2207
|
-
prefix = "text_encoder."
|
2208
|
-
else:
|
2209
|
-
prefix = "text_encoder_2."
|
2210
|
-
new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
|
2211
|
-
network_alphas.update({new_name: alpha})
|
2212
|
-
|
2213
|
-
if len(state_dict) > 0:
|
2214
|
-
raise ValueError(
|
2215
|
-
f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}"
|
2216
|
-
)
|
2217
|
-
|
2218
|
-
logger.info("Kohya-style checkpoint detected.")
|
2219
|
-
unet_state_dict = {f"{cls.unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
|
2220
|
-
te_state_dict = {
|
2221
|
-
f"{cls.text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()
|
2222
|
-
}
|
2223
|
-
te2_state_dict = (
|
2224
|
-
{f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
|
2225
|
-
if len(te2_state_dict) > 0
|
2226
|
-
else None
|
2227
|
-
)
|
2228
|
-
if te2_state_dict is not None:
|
2229
|
-
te_state_dict.update(te2_state_dict)
|
2230
|
-
|
2231
|
-
new_state_dict = {**unet_state_dict, **te_state_dict}
|
2232
|
-
return new_state_dict, network_alphas
|
2233
|
-
|
2234
|
-
def unload_lora_weights(self):
|
2235
|
-
"""
|
2236
|
-
Unloads the LoRA parameters.
|
2237
|
-
|
2238
|
-
Examples:
|
2239
|
-
|
2240
|
-
```python
|
2241
|
-
>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
|
2242
|
-
>>> pipeline.unload_lora_weights()
|
2243
|
-
>>> ...
|
2244
|
-
```
|
2245
|
-
"""
|
2246
|
-
if not USE_PEFT_BACKEND:
|
2247
|
-
if version.parse(__version__) > version.parse("0.23"):
|
2248
|
-
logger.warn(
|
2249
|
-
"You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
|
2250
|
-
"you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
|
2251
|
-
)
|
2252
|
-
|
2253
|
-
for _, module in self.unet.named_modules():
|
2254
|
-
if hasattr(module, "set_lora_layer"):
|
2255
|
-
module.set_lora_layer(None)
|
2256
|
-
else:
|
2257
|
-
recurse_remove_peft_layers(self.unet)
|
2258
|
-
if hasattr(self.unet, "peft_config"):
|
2259
|
-
del self.unet.peft_config
|
2260
|
-
|
2261
|
-
# Safe to call the following regardless of LoRA.
|
2262
|
-
self._remove_text_encoder_monkey_patch()
|
2263
|
-
|
2264
|
-
def fuse_lora(
|
2265
|
-
self,
|
2266
|
-
fuse_unet: bool = True,
|
2267
|
-
fuse_text_encoder: bool = True,
|
2268
|
-
lora_scale: float = 1.0,
|
2269
|
-
safe_fusing: bool = False,
|
2270
|
-
):
|
2271
|
-
r"""
|
2272
|
-
Fuses the LoRA parameters into the original parameters of the corresponding blocks.
|
2273
|
-
|
2274
|
-
<Tip warning={true}>
|
2275
|
-
|
2276
|
-
This is an experimental API.
|
2277
|
-
|
2278
|
-
</Tip>
|
2279
|
-
|
2280
|
-
Args:
|
2281
|
-
fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
|
2282
|
-
fuse_text_encoder (`bool`, defaults to `True`):
|
2283
|
-
Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
2284
|
-
LoRA parameters then it won't have any effect.
|
2285
|
-
lora_scale (`float`, defaults to 1.0):
|
2286
|
-
Controls how much to influence the outputs with the LoRA parameters.
|
2287
|
-
safe_fusing (`bool`, defaults to `False`):
|
2288
|
-
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
|
2289
|
-
"""
|
2290
|
-
if fuse_unet or fuse_text_encoder:
|
2291
|
-
self.num_fused_loras += 1
|
2292
|
-
if self.num_fused_loras > 1:
|
2293
|
-
logger.warn(
|
2294
|
-
"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.",
|
2295
|
-
)
|
2296
|
-
|
2297
|
-
if fuse_unet:
|
2298
|
-
self.unet.fuse_lora(lora_scale, safe_fusing=safe_fusing)
|
2299
|
-
|
2300
|
-
if USE_PEFT_BACKEND:
|
2301
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
2302
|
-
|
2303
|
-
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
|
2304
|
-
# TODO(Patrick, Younes): enable "safe" fusing
|
2305
|
-
for module in text_encoder.modules():
|
2306
|
-
if isinstance(module, BaseTunerLayer):
|
2307
|
-
if lora_scale != 1.0:
|
2308
|
-
module.scale_layer(lora_scale)
|
2309
|
-
|
2310
|
-
module.merge()
|
2311
|
-
|
2312
|
-
else:
|
2313
|
-
if version.parse(__version__) > version.parse("0.23"):
|
2314
|
-
deprecate("fuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
|
2315
|
-
|
2316
|
-
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
|
2317
|
-
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
2318
|
-
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
2319
|
-
attn_module.q_proj._fuse_lora(lora_scale, safe_fusing)
|
2320
|
-
attn_module.k_proj._fuse_lora(lora_scale, safe_fusing)
|
2321
|
-
attn_module.v_proj._fuse_lora(lora_scale, safe_fusing)
|
2322
|
-
attn_module.out_proj._fuse_lora(lora_scale, safe_fusing)
|
2323
|
-
|
2324
|
-
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
2325
|
-
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
2326
|
-
mlp_module.fc1._fuse_lora(lora_scale, safe_fusing)
|
2327
|
-
mlp_module.fc2._fuse_lora(lora_scale, safe_fusing)
|
2328
|
-
|
2329
|
-
if fuse_text_encoder:
|
2330
|
-
if hasattr(self, "text_encoder"):
|
2331
|
-
fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing)
|
2332
|
-
if hasattr(self, "text_encoder_2"):
|
2333
|
-
fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing)
|
2334
|
-
|
2335
|
-
def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
|
2336
|
-
r"""
|
2337
|
-
Reverses the effect of
|
2338
|
-
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
|
2339
|
-
|
2340
|
-
<Tip warning={true}>
|
2341
|
-
|
2342
|
-
This is an experimental API.
|
2343
|
-
|
2344
|
-
</Tip>
|
2345
|
-
|
2346
|
-
Args:
|
2347
|
-
unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
|
2348
|
-
unfuse_text_encoder (`bool`, defaults to `True`):
|
2349
|
-
Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
2350
|
-
LoRA parameters then it won't have any effect.
|
2351
|
-
"""
|
2352
|
-
if unfuse_unet:
|
2353
|
-
if not USE_PEFT_BACKEND:
|
2354
|
-
self.unet.unfuse_lora()
|
2355
|
-
else:
|
2356
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
2357
|
-
|
2358
|
-
for module in self.unet.modules():
|
2359
|
-
if isinstance(module, BaseTunerLayer):
|
2360
|
-
module.unmerge()
|
2361
|
-
|
2362
|
-
if USE_PEFT_BACKEND:
|
2363
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
2364
|
-
|
2365
|
-
def unfuse_text_encoder_lora(text_encoder):
|
2366
|
-
for module in text_encoder.modules():
|
2367
|
-
if isinstance(module, BaseTunerLayer):
|
2368
|
-
module.unmerge()
|
2369
|
-
|
2370
|
-
else:
|
2371
|
-
if version.parse(__version__) > version.parse("0.23"):
|
2372
|
-
deprecate("unfuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
|
2373
|
-
|
2374
|
-
def unfuse_text_encoder_lora(text_encoder):
|
2375
|
-
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
2376
|
-
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
2377
|
-
attn_module.q_proj._unfuse_lora()
|
2378
|
-
attn_module.k_proj._unfuse_lora()
|
2379
|
-
attn_module.v_proj._unfuse_lora()
|
2380
|
-
attn_module.out_proj._unfuse_lora()
|
2381
|
-
|
2382
|
-
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
2383
|
-
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
2384
|
-
mlp_module.fc1._unfuse_lora()
|
2385
|
-
mlp_module.fc2._unfuse_lora()
|
2386
|
-
|
2387
|
-
if unfuse_text_encoder:
|
2388
|
-
if hasattr(self, "text_encoder"):
|
2389
|
-
unfuse_text_encoder_lora(self.text_encoder)
|
2390
|
-
if hasattr(self, "text_encoder_2"):
|
2391
|
-
unfuse_text_encoder_lora(self.text_encoder_2)
|
2392
|
-
|
2393
|
-
self.num_fused_loras -= 1
|
2394
|
-
|
2395
|
-
def set_adapters_for_text_encoder(
|
2396
|
-
self,
|
2397
|
-
adapter_names: Union[List[str], str],
|
2398
|
-
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
2399
|
-
text_encoder_weights: List[float] = None,
|
2400
|
-
):
|
2401
|
-
"""
|
2402
|
-
Sets the adapter layers for the text encoder.
|
2403
|
-
|
2404
|
-
Args:
|
2405
|
-
adapter_names (`List[str]` or `str`):
|
2406
|
-
The names of the adapters to use.
|
2407
|
-
text_encoder (`torch.nn.Module`, *optional*):
|
2408
|
-
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
2409
|
-
attribute.
|
2410
|
-
text_encoder_weights (`List[float]`, *optional*):
|
2411
|
-
The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
|
2412
|
-
"""
|
2413
|
-
if not USE_PEFT_BACKEND:
|
2414
|
-
raise ValueError("PEFT backend is required for this method.")
|
2415
|
-
|
2416
|
-
def process_weights(adapter_names, weights):
|
2417
|
-
if weights is None:
|
2418
|
-
weights = [1.0] * len(adapter_names)
|
2419
|
-
elif isinstance(weights, float):
|
2420
|
-
weights = [weights]
|
2421
|
-
|
2422
|
-
if len(adapter_names) != len(weights):
|
2423
|
-
raise ValueError(
|
2424
|
-
f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
|
2425
|
-
)
|
2426
|
-
return weights
|
2427
|
-
|
2428
|
-
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
2429
|
-
text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
|
2430
|
-
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
2431
|
-
if text_encoder is None:
|
2432
|
-
raise ValueError(
|
2433
|
-
"The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
|
2434
|
-
)
|
2435
|
-
set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
|
2436
|
-
|
2437
|
-
def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
2438
|
-
"""
|
2439
|
-
Disables the LoRA layers for the text encoder.
|
2440
|
-
|
2441
|
-
Args:
|
2442
|
-
text_encoder (`torch.nn.Module`, *optional*):
|
2443
|
-
The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
|
2444
|
-
`text_encoder` attribute.
|
2445
|
-
"""
|
2446
|
-
if not USE_PEFT_BACKEND:
|
2447
|
-
raise ValueError("PEFT backend is required for this method.")
|
2448
|
-
|
2449
|
-
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
2450
|
-
if text_encoder is None:
|
2451
|
-
raise ValueError("Text Encoder not found.")
|
2452
|
-
set_adapter_layers(text_encoder, enabled=False)
|
2453
|
-
|
2454
|
-
def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
2455
|
-
"""
|
2456
|
-
Enables the LoRA layers for the text encoder.
|
2457
|
-
|
2458
|
-
Args:
|
2459
|
-
text_encoder (`torch.nn.Module`, *optional*):
|
2460
|
-
The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
|
2461
|
-
attribute.
|
2462
|
-
"""
|
2463
|
-
if not USE_PEFT_BACKEND:
|
2464
|
-
raise ValueError("PEFT backend is required for this method.")
|
2465
|
-
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
2466
|
-
if text_encoder is None:
|
2467
|
-
raise ValueError("Text Encoder not found.")
|
2468
|
-
set_adapter_layers(self.text_encoder, enabled=True)
|
2469
|
-
|
2470
|
-
def set_adapters(
|
2471
|
-
self,
|
2472
|
-
adapter_names: Union[List[str], str],
|
2473
|
-
adapter_weights: Optional[List[float]] = None,
|
2474
|
-
):
|
2475
|
-
# Handle the UNET
|
2476
|
-
self.unet.set_adapters(adapter_names, adapter_weights)
|
2477
|
-
|
2478
|
-
# Handle the Text Encoder
|
2479
|
-
if hasattr(self, "text_encoder"):
|
2480
|
-
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
|
2481
|
-
if hasattr(self, "text_encoder_2"):
|
2482
|
-
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
|
2483
|
-
|
2484
|
-
def disable_lora(self):
|
2485
|
-
if not USE_PEFT_BACKEND:
|
2486
|
-
raise ValueError("PEFT backend is required for this method.")
|
2487
|
-
|
2488
|
-
# Disable unet adapters
|
2489
|
-
self.unet.disable_lora()
|
2490
|
-
|
2491
|
-
# Disable text encoder adapters
|
2492
|
-
if hasattr(self, "text_encoder"):
|
2493
|
-
self.disable_lora_for_text_encoder(self.text_encoder)
|
2494
|
-
if hasattr(self, "text_encoder_2"):
|
2495
|
-
self.disable_lora_for_text_encoder(self.text_encoder_2)
|
2496
|
-
|
2497
|
-
def enable_lora(self):
|
2498
|
-
if not USE_PEFT_BACKEND:
|
2499
|
-
raise ValueError("PEFT backend is required for this method.")
|
2500
|
-
|
2501
|
-
# Enable unet adapters
|
2502
|
-
self.unet.enable_lora()
|
2503
|
-
|
2504
|
-
# Enable text encoder adapters
|
2505
|
-
if hasattr(self, "text_encoder"):
|
2506
|
-
self.enable_lora_for_text_encoder(self.text_encoder)
|
2507
|
-
if hasattr(self, "text_encoder_2"):
|
2508
|
-
self.enable_lora_for_text_encoder(self.text_encoder_2)
|
2509
|
-
|
2510
|
-
def get_active_adapters(self) -> List[str]:
|
2511
|
-
"""
|
2512
|
-
Gets the list of the current active adapters.
|
2513
|
-
|
2514
|
-
Example:
|
2515
|
-
|
2516
|
-
```python
|
2517
|
-
from diffusers import DiffusionPipeline
|
2518
|
-
|
2519
|
-
pipeline = DiffusionPipeline.from_pretrained(
|
2520
|
-
"stabilityai/stable-diffusion-xl-base-1.0",
|
2521
|
-
).to("cuda")
|
2522
|
-
pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
|
2523
|
-
pipeline.get_active_adapters()
|
2524
|
-
```
|
2525
|
-
"""
|
2526
|
-
if not USE_PEFT_BACKEND:
|
2527
|
-
raise ValueError(
|
2528
|
-
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
2529
|
-
)
|
2530
|
-
|
2531
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
2532
|
-
|
2533
|
-
active_adapters = []
|
2534
|
-
|
2535
|
-
for module in self.unet.modules():
|
2536
|
-
if isinstance(module, BaseTunerLayer):
|
2537
|
-
active_adapters = module.active_adapters
|
2538
|
-
break
|
2539
|
-
|
2540
|
-
return active_adapters
|
2541
|
-
|
2542
|
-
def get_list_adapters(self) -> Dict[str, List[str]]:
|
2543
|
-
"""
|
2544
|
-
Gets the current list of all available adapters in the pipeline.
|
2545
|
-
"""
|
2546
|
-
if not USE_PEFT_BACKEND:
|
2547
|
-
raise ValueError(
|
2548
|
-
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
2549
|
-
)
|
2550
|
-
|
2551
|
-
set_adapters = {}
|
2552
|
-
|
2553
|
-
if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
|
2554
|
-
set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
|
2555
|
-
|
2556
|
-
if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
|
2557
|
-
set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
|
2558
|
-
|
2559
|
-
if hasattr(self, "unet") and hasattr(self.unet, "peft_config"):
|
2560
|
-
set_adapters["unet"] = list(self.unet.peft_config.keys())
|
2561
|
-
|
2562
|
-
return set_adapters
|
2563
|
-
|
2564
|
-
def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
|
2565
|
-
"""
|
2566
|
-
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
|
2567
|
-
you want to load multiple adapters and free some GPU memory.
|
2568
|
-
|
2569
|
-
Args:
|
2570
|
-
adapter_names (`List[str]`):
|
2571
|
-
List of adapters to send device to.
|
2572
|
-
device (`Union[torch.device, str, int]`):
|
2573
|
-
Device to send the adapters to. Can be either a torch device, a str or an integer.
|
2574
|
-
"""
|
2575
|
-
if not USE_PEFT_BACKEND:
|
2576
|
-
raise ValueError("PEFT backend is required for this method.")
|
2577
|
-
|
2578
|
-
from peft.tuners.tuners_utils import BaseTunerLayer
|
2579
|
-
|
2580
|
-
# Handle the UNET
|
2581
|
-
for unet_module in self.unet.modules():
|
2582
|
-
if isinstance(unet_module, BaseTunerLayer):
|
2583
|
-
for adapter_name in adapter_names:
|
2584
|
-
unet_module.lora_A[adapter_name].to(device)
|
2585
|
-
unet_module.lora_B[adapter_name].to(device)
|
2586
|
-
|
2587
|
-
# Handle the text encoder
|
2588
|
-
modules_to_process = []
|
2589
|
-
if hasattr(self, "text_encoder"):
|
2590
|
-
modules_to_process.append(self.text_encoder)
|
2591
|
-
|
2592
|
-
if hasattr(self, "text_encoder_2"):
|
2593
|
-
modules_to_process.append(self.text_encoder_2)
|
2594
|
-
|
2595
|
-
for text_encoder in modules_to_process:
|
2596
|
-
# loop over submodules
|
2597
|
-
for text_encoder_module in text_encoder.modules():
|
2598
|
-
if isinstance(text_encoder_module, BaseTunerLayer):
|
2599
|
-
for adapter_name in adapter_names:
|
2600
|
-
text_encoder_module.lora_A[adapter_name].to(device)
|
2601
|
-
text_encoder_module.lora_B[adapter_name].to(device)
|
2602
|
-
|
2603
|
-
|
2604
|
-
class FromSingleFileMixin:
|
2605
|
-
"""
|
2606
|
-
Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
|
2607
|
-
"""
|
2608
|
-
|
2609
|
-
@classmethod
|
2610
|
-
def from_ckpt(cls, *args, **kwargs):
|
2611
|
-
deprecation_message = "The function `from_ckpt` is deprecated in favor of `from_single_file` and will be removed in diffusers v.0.21. Please make sure to use `StableDiffusionPipeline.from_single_file(...)` instead."
|
2612
|
-
deprecate("from_ckpt", "0.21.0", deprecation_message, standard_warn=False)
|
2613
|
-
return cls.from_single_file(*args, **kwargs)
|
2614
|
-
|
2615
|
-
@classmethod
|
2616
|
-
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
2617
|
-
r"""
|
2618
|
-
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
|
2619
|
-
format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
2620
|
-
|
2621
|
-
Parameters:
|
2622
|
-
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
2623
|
-
Can be either:
|
2624
|
-
- A link to the `.ckpt` file (for example
|
2625
|
-
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
2626
|
-
- A path to a *file* containing all pipeline weights.
|
2627
|
-
torch_dtype (`str` or `torch.dtype`, *optional*):
|
2628
|
-
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
2629
|
-
dtype is automatically derived from the model's weights.
|
2630
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
2631
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
2632
|
-
cached versions if they exist.
|
2633
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
2634
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
2635
|
-
is not used.
|
2636
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
2637
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
2638
|
-
incompletely downloaded files are deleted.
|
2639
|
-
proxies (`Dict[str, str]`, *optional*):
|
2640
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
2641
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
2642
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
2643
|
-
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
2644
|
-
won't be downloaded from the Hub.
|
2645
|
-
use_auth_token (`str` or *bool*, *optional*):
|
2646
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
2647
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
2648
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
2649
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
2650
|
-
allowed by Git.
|
2651
|
-
use_safetensors (`bool`, *optional*, defaults to `None`):
|
2652
|
-
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
2653
|
-
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
2654
|
-
weights. If set to `False`, safetensors weights are not loaded.
|
2655
|
-
extract_ema (`bool`, *optional*, defaults to `False`):
|
2656
|
-
Whether to extract the EMA weights or not. Pass `True` to extract the EMA weights which usually yield
|
2657
|
-
higher quality images for inference. Non-EMA weights are usually better for continuing finetuning.
|
2658
|
-
upcast_attention (`bool`, *optional*, defaults to `None`):
|
2659
|
-
Whether the attention computation should always be upcasted.
|
2660
|
-
image_size (`int`, *optional*, defaults to 512):
|
2661
|
-
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
2662
|
-
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
2663
|
-
prediction_type (`str`, *optional*):
|
2664
|
-
The prediction type the model was trained on. Use `'epsilon'` for all Stable Diffusion v1 models and
|
2665
|
-
the Stable Diffusion v2 base model. Use `'v_prediction'` for Stable Diffusion v2.
|
2666
|
-
num_in_channels (`int`, *optional*, defaults to `None`):
|
2667
|
-
The number of input channels. If `None`, it is automatically inferred.
|
2668
|
-
scheduler_type (`str`, *optional*, defaults to `"pndm"`):
|
2669
|
-
Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm",
|
2670
|
-
"ddim"]`.
|
2671
|
-
load_safety_checker (`bool`, *optional*, defaults to `True`):
|
2672
|
-
Whether to load the safety checker or not.
|
2673
|
-
text_encoder ([`~transformers.CLIPTextModel`], *optional*, defaults to `None`):
|
2674
|
-
An instance of `CLIPTextModel` to use, specifically the
|
2675
|
-
[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. If this
|
2676
|
-
parameter is `None`, the function loads a new instance of `CLIPTextModel` by itself if needed.
|
2677
|
-
vae (`AutoencoderKL`, *optional*, defaults to `None`):
|
2678
|
-
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. If
|
2679
|
-
this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
|
2680
|
-
tokenizer ([`~transformers.CLIPTokenizer`], *optional*, defaults to `None`):
|
2681
|
-
An instance of `CLIPTokenizer` to use. If this parameter is `None`, the function loads a new instance
|
2682
|
-
of `CLIPTokenizer` by itself if needed.
|
2683
|
-
original_config_file (`str`):
|
2684
|
-
Path to `.yaml` config file corresponding to the original architecture. If `None`, will be
|
2685
|
-
automatically inferred by looking for a key that only exists in SD2.0 models.
|
2686
|
-
kwargs (remaining dictionary of keyword arguments, *optional*):
|
2687
|
-
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
2688
|
-
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
2689
|
-
method. See example below for more information.
|
2690
|
-
|
2691
|
-
Examples:
|
2692
|
-
|
2693
|
-
```py
|
2694
|
-
>>> from diffusers import StableDiffusionPipeline
|
2695
|
-
|
2696
|
-
>>> # Download pipeline from huggingface.co and cache.
|
2697
|
-
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
2698
|
-
... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
|
2699
|
-
... )
|
2700
|
-
|
2701
|
-
>>> # Download pipeline from local file
|
2702
|
-
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
|
2703
|
-
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
|
2704
|
-
|
2705
|
-
>>> # Enable float16 and move to GPU
|
2706
|
-
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
2707
|
-
... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
|
2708
|
-
... torch_dtype=torch.float16,
|
2709
|
-
... )
|
2710
|
-
>>> pipeline.to("cuda")
|
2711
|
-
```
|
2712
|
-
"""
|
2713
|
-
# import here to avoid circular dependency
|
2714
|
-
from .pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
|
2715
|
-
|
2716
|
-
original_config_file = kwargs.pop("original_config_file", None)
|
2717
|
-
config_files = kwargs.pop("config_files", None)
|
2718
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
2719
|
-
resume_download = kwargs.pop("resume_download", False)
|
2720
|
-
force_download = kwargs.pop("force_download", False)
|
2721
|
-
proxies = kwargs.pop("proxies", None)
|
2722
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
2723
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
2724
|
-
revision = kwargs.pop("revision", None)
|
2725
|
-
extract_ema = kwargs.pop("extract_ema", False)
|
2726
|
-
image_size = kwargs.pop("image_size", None)
|
2727
|
-
scheduler_type = kwargs.pop("scheduler_type", "pndm")
|
2728
|
-
num_in_channels = kwargs.pop("num_in_channels", None)
|
2729
|
-
upcast_attention = kwargs.pop("upcast_attention", None)
|
2730
|
-
load_safety_checker = kwargs.pop("load_safety_checker", True)
|
2731
|
-
prediction_type = kwargs.pop("prediction_type", None)
|
2732
|
-
text_encoder = kwargs.pop("text_encoder", None)
|
2733
|
-
vae = kwargs.pop("vae", None)
|
2734
|
-
controlnet = kwargs.pop("controlnet", None)
|
2735
|
-
adapter = kwargs.pop("adapter", None)
|
2736
|
-
tokenizer = kwargs.pop("tokenizer", None)
|
2737
|
-
|
2738
|
-
torch_dtype = kwargs.pop("torch_dtype", None)
|
2739
|
-
|
2740
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
2741
|
-
|
2742
|
-
pipeline_name = cls.__name__
|
2743
|
-
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
2744
|
-
from_safetensors = file_extension == "safetensors"
|
2745
|
-
|
2746
|
-
if from_safetensors and use_safetensors is False:
|
2747
|
-
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
2748
|
-
|
2749
|
-
# TODO: For now we only support stable diffusion
|
2750
|
-
stable_unclip = None
|
2751
|
-
model_type = None
|
2752
|
-
|
2753
|
-
if pipeline_name in [
|
2754
|
-
"StableDiffusionControlNetPipeline",
|
2755
|
-
"StableDiffusionControlNetImg2ImgPipeline",
|
2756
|
-
"StableDiffusionControlNetInpaintPipeline",
|
2757
|
-
]:
|
2758
|
-
from .models.controlnet import ControlNetModel
|
2759
|
-
from .pipelines.controlnet.multicontrolnet import MultiControlNetModel
|
2760
|
-
|
2761
|
-
# list/tuple or a single instance of ControlNetModel or MultiControlNetModel
|
2762
|
-
if not (
|
2763
|
-
isinstance(controlnet, (ControlNetModel, MultiControlNetModel))
|
2764
|
-
or isinstance(controlnet, (list, tuple))
|
2765
|
-
and isinstance(controlnet[0], ControlNetModel)
|
2766
|
-
):
|
2767
|
-
raise ValueError("ControlNet needs to be passed if loading from ControlNet pipeline.")
|
2768
|
-
elif "StableDiffusion" in pipeline_name:
|
2769
|
-
# Model type will be inferred from the checkpoint.
|
2770
|
-
pass
|
2771
|
-
elif pipeline_name == "StableUnCLIPPipeline":
|
2772
|
-
model_type = "FrozenOpenCLIPEmbedder"
|
2773
|
-
stable_unclip = "txt2img"
|
2774
|
-
elif pipeline_name == "StableUnCLIPImg2ImgPipeline":
|
2775
|
-
model_type = "FrozenOpenCLIPEmbedder"
|
2776
|
-
stable_unclip = "img2img"
|
2777
|
-
elif pipeline_name == "PaintByExamplePipeline":
|
2778
|
-
model_type = "PaintByExample"
|
2779
|
-
elif pipeline_name == "LDMTextToImagePipeline":
|
2780
|
-
model_type = "LDMTextToImage"
|
2781
|
-
else:
|
2782
|
-
raise ValueError(f"Unhandled pipeline class: {pipeline_name}")
|
2783
|
-
|
2784
|
-
# remove huggingface url
|
2785
|
-
has_valid_url_prefix = False
|
2786
|
-
valid_url_prefixes = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
|
2787
|
-
for prefix in valid_url_prefixes:
|
2788
|
-
if pretrained_model_link_or_path.startswith(prefix):
|
2789
|
-
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
2790
|
-
has_valid_url_prefix = True
|
2791
|
-
|
2792
|
-
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
2793
|
-
ckpt_path = Path(pretrained_model_link_or_path)
|
2794
|
-
if not ckpt_path.is_file():
|
2795
|
-
if not has_valid_url_prefix:
|
2796
|
-
raise ValueError(
|
2797
|
-
f"The provided path is either not a file or a valid huggingface URL was not provided. Valid URLs begin with {', '.join(valid_url_prefixes)}"
|
2798
|
-
)
|
2799
|
-
|
2800
|
-
# get repo_id and (potentially nested) file path of ckpt in repo
|
2801
|
-
repo_id = "/".join(ckpt_path.parts[:2])
|
2802
|
-
file_path = "/".join(ckpt_path.parts[2:])
|
2803
|
-
|
2804
|
-
if file_path.startswith("blob/"):
|
2805
|
-
file_path = file_path[len("blob/") :]
|
2806
|
-
|
2807
|
-
if file_path.startswith("main/"):
|
2808
|
-
file_path = file_path[len("main/") :]
|
2809
|
-
|
2810
|
-
pretrained_model_link_or_path = hf_hub_download(
|
2811
|
-
repo_id,
|
2812
|
-
filename=file_path,
|
2813
|
-
cache_dir=cache_dir,
|
2814
|
-
resume_download=resume_download,
|
2815
|
-
proxies=proxies,
|
2816
|
-
local_files_only=local_files_only,
|
2817
|
-
use_auth_token=use_auth_token,
|
2818
|
-
revision=revision,
|
2819
|
-
force_download=force_download,
|
2820
|
-
)
|
2821
|
-
|
2822
|
-
pipe = download_from_original_stable_diffusion_ckpt(
|
2823
|
-
pretrained_model_link_or_path,
|
2824
|
-
pipeline_class=cls,
|
2825
|
-
model_type=model_type,
|
2826
|
-
stable_unclip=stable_unclip,
|
2827
|
-
controlnet=controlnet,
|
2828
|
-
adapter=adapter,
|
2829
|
-
from_safetensors=from_safetensors,
|
2830
|
-
extract_ema=extract_ema,
|
2831
|
-
image_size=image_size,
|
2832
|
-
scheduler_type=scheduler_type,
|
2833
|
-
num_in_channels=num_in_channels,
|
2834
|
-
upcast_attention=upcast_attention,
|
2835
|
-
load_safety_checker=load_safety_checker,
|
2836
|
-
prediction_type=prediction_type,
|
2837
|
-
text_encoder=text_encoder,
|
2838
|
-
vae=vae,
|
2839
|
-
tokenizer=tokenizer,
|
2840
|
-
original_config_file=original_config_file,
|
2841
|
-
config_files=config_files,
|
2842
|
-
local_files_only=local_files_only,
|
2843
|
-
)
|
2844
|
-
|
2845
|
-
if torch_dtype is not None:
|
2846
|
-
pipe.to(torch_dtype=torch_dtype)
|
2847
|
-
|
2848
|
-
return pipe
|
2849
|
-
|
2850
|
-
|
2851
|
-
class FromOriginalVAEMixin:
|
2852
|
-
@classmethod
|
2853
|
-
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
2854
|
-
r"""
|
2855
|
-
Instantiate a [`AutoencoderKL`] from pretrained controlnet weights saved in the original `.ckpt` or
|
2856
|
-
`.safetensors` format. The pipeline is format. The pipeline is set in evaluation mode (`model.eval()`) by
|
2857
|
-
default.
|
2858
|
-
|
2859
|
-
Parameters:
|
2860
|
-
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
2861
|
-
Can be either:
|
2862
|
-
- A link to the `.ckpt` file (for example
|
2863
|
-
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
2864
|
-
- A path to a *file* containing all pipeline weights.
|
2865
|
-
torch_dtype (`str` or `torch.dtype`, *optional*):
|
2866
|
-
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
2867
|
-
dtype is automatically derived from the model's weights.
|
2868
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
2869
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
2870
|
-
cached versions if they exist.
|
2871
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
2872
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
2873
|
-
is not used.
|
2874
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
2875
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
2876
|
-
incompletely downloaded files are deleted.
|
2877
|
-
proxies (`Dict[str, str]`, *optional*):
|
2878
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
2879
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
2880
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
2881
|
-
Whether to only load local model weights and configuration files or not. If set to True, the model
|
2882
|
-
won't be downloaded from the Hub.
|
2883
|
-
use_auth_token (`str` or *bool*, *optional*):
|
2884
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
2885
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
2886
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
2887
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
2888
|
-
allowed by Git.
|
2889
|
-
image_size (`int`, *optional*, defaults to 512):
|
2890
|
-
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
2891
|
-
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
2892
|
-
use_safetensors (`bool`, *optional*, defaults to `None`):
|
2893
|
-
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
2894
|
-
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
2895
|
-
weights. If set to `False`, safetensors weights are not loaded.
|
2896
|
-
upcast_attention (`bool`, *optional*, defaults to `None`):
|
2897
|
-
Whether the attention computation should always be upcasted.
|
2898
|
-
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
2899
|
-
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
2900
|
-
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
2901
|
-
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
2902
|
-
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
|
2903
|
-
= 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
|
2904
|
-
Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
2905
|
-
kwargs (remaining dictionary of keyword arguments, *optional*):
|
2906
|
-
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
2907
|
-
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
2908
|
-
method. See example below for more information.
|
2909
|
-
|
2910
|
-
<Tip warning={true}>
|
2911
|
-
|
2912
|
-
Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you want to load
|
2913
|
-
a VAE that does accompany a stable diffusion model of v2 or higher or SDXL.
|
2914
|
-
|
2915
|
-
</Tip>
|
2916
|
-
|
2917
|
-
Examples:
|
2918
|
-
|
2919
|
-
```py
|
2920
|
-
from diffusers import AutoencoderKL
|
2921
|
-
|
2922
|
-
url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
|
2923
|
-
model = AutoencoderKL.from_single_file(url)
|
2924
|
-
```
|
2925
|
-
"""
|
2926
|
-
if not is_omegaconf_available():
|
2927
|
-
raise ValueError(BACKENDS_MAPPING["omegaconf"][1])
|
2928
|
-
|
2929
|
-
from omegaconf import OmegaConf
|
2930
|
-
|
2931
|
-
from .models import AutoencoderKL
|
2932
|
-
|
2933
|
-
# import here to avoid circular dependency
|
2934
|
-
from .pipelines.stable_diffusion.convert_from_ckpt import (
|
2935
|
-
convert_ldm_vae_checkpoint,
|
2936
|
-
create_vae_diffusers_config,
|
2937
|
-
)
|
2938
|
-
|
2939
|
-
config_file = kwargs.pop("config_file", None)
|
2940
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
2941
|
-
resume_download = kwargs.pop("resume_download", False)
|
2942
|
-
force_download = kwargs.pop("force_download", False)
|
2943
|
-
proxies = kwargs.pop("proxies", None)
|
2944
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
2945
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
2946
|
-
revision = kwargs.pop("revision", None)
|
2947
|
-
image_size = kwargs.pop("image_size", None)
|
2948
|
-
scaling_factor = kwargs.pop("scaling_factor", None)
|
2949
|
-
kwargs.pop("upcast_attention", None)
|
2950
|
-
|
2951
|
-
torch_dtype = kwargs.pop("torch_dtype", None)
|
2952
|
-
|
2953
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
2954
|
-
|
2955
|
-
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
2956
|
-
from_safetensors = file_extension == "safetensors"
|
2957
|
-
|
2958
|
-
if from_safetensors and use_safetensors is False:
|
2959
|
-
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
2960
|
-
|
2961
|
-
# remove huggingface url
|
2962
|
-
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
2963
|
-
if pretrained_model_link_or_path.startswith(prefix):
|
2964
|
-
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
2965
|
-
|
2966
|
-
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
2967
|
-
ckpt_path = Path(pretrained_model_link_or_path)
|
2968
|
-
if not ckpt_path.is_file():
|
2969
|
-
# get repo_id and (potentially nested) file path of ckpt in repo
|
2970
|
-
repo_id = "/".join(ckpt_path.parts[:2])
|
2971
|
-
file_path = "/".join(ckpt_path.parts[2:])
|
2972
|
-
|
2973
|
-
if file_path.startswith("blob/"):
|
2974
|
-
file_path = file_path[len("blob/") :]
|
2975
|
-
|
2976
|
-
if file_path.startswith("main/"):
|
2977
|
-
file_path = file_path[len("main/") :]
|
2978
|
-
|
2979
|
-
pretrained_model_link_or_path = hf_hub_download(
|
2980
|
-
repo_id,
|
2981
|
-
filename=file_path,
|
2982
|
-
cache_dir=cache_dir,
|
2983
|
-
resume_download=resume_download,
|
2984
|
-
proxies=proxies,
|
2985
|
-
local_files_only=local_files_only,
|
2986
|
-
use_auth_token=use_auth_token,
|
2987
|
-
revision=revision,
|
2988
|
-
force_download=force_download,
|
2989
|
-
)
|
2990
|
-
|
2991
|
-
if from_safetensors:
|
2992
|
-
from safetensors import safe_open
|
2993
|
-
|
2994
|
-
checkpoint = {}
|
2995
|
-
with safe_open(pretrained_model_link_or_path, framework="pt", device="cpu") as f:
|
2996
|
-
for key in f.keys():
|
2997
|
-
checkpoint[key] = f.get_tensor(key)
|
2998
|
-
else:
|
2999
|
-
checkpoint = torch.load(pretrained_model_link_or_path, map_location="cpu")
|
3000
|
-
|
3001
|
-
if "state_dict" in checkpoint:
|
3002
|
-
checkpoint = checkpoint["state_dict"]
|
3003
|
-
|
3004
|
-
if config_file is None:
|
3005
|
-
config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
|
3006
|
-
config_file = BytesIO(requests.get(config_url).content)
|
3007
|
-
|
3008
|
-
original_config = OmegaConf.load(config_file)
|
3009
|
-
|
3010
|
-
# default to sd-v1-5
|
3011
|
-
image_size = image_size or 512
|
3012
|
-
|
3013
|
-
vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
|
3014
|
-
converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
|
3015
|
-
|
3016
|
-
if scaling_factor is None:
|
3017
|
-
if (
|
3018
|
-
"model" in original_config
|
3019
|
-
and "params" in original_config.model
|
3020
|
-
and "scale_factor" in original_config.model.params
|
3021
|
-
):
|
3022
|
-
vae_scaling_factor = original_config.model.params.scale_factor
|
3023
|
-
else:
|
3024
|
-
vae_scaling_factor = 0.18215 # default SD scaling factor
|
3025
|
-
|
3026
|
-
vae_config["scaling_factor"] = vae_scaling_factor
|
3027
|
-
|
3028
|
-
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
3029
|
-
with ctx():
|
3030
|
-
vae = AutoencoderKL(**vae_config)
|
3031
|
-
|
3032
|
-
if is_accelerate_available():
|
3033
|
-
load_model_dict_into_meta(vae, converted_vae_checkpoint, device="cpu")
|
3034
|
-
else:
|
3035
|
-
vae.load_state_dict(converted_vae_checkpoint)
|
3036
|
-
|
3037
|
-
if torch_dtype is not None:
|
3038
|
-
vae.to(dtype=torch_dtype)
|
3039
|
-
|
3040
|
-
return vae
|
3041
|
-
|
3042
|
-
|
3043
|
-
class FromOriginalControlnetMixin:
|
3044
|
-
@classmethod
|
3045
|
-
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
3046
|
-
r"""
|
3047
|
-
Instantiate a [`ControlNetModel`] from pretrained controlnet weights saved in the original `.ckpt` or
|
3048
|
-
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
3049
|
-
|
3050
|
-
Parameters:
|
3051
|
-
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
3052
|
-
Can be either:
|
3053
|
-
- A link to the `.ckpt` file (for example
|
3054
|
-
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
3055
|
-
- A path to a *file* containing all pipeline weights.
|
3056
|
-
torch_dtype (`str` or `torch.dtype`, *optional*):
|
3057
|
-
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
3058
|
-
dtype is automatically derived from the model's weights.
|
3059
|
-
force_download (`bool`, *optional*, defaults to `False`):
|
3060
|
-
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
3061
|
-
cached versions if they exist.
|
3062
|
-
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
3063
|
-
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
3064
|
-
is not used.
|
3065
|
-
resume_download (`bool`, *optional*, defaults to `False`):
|
3066
|
-
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
3067
|
-
incompletely downloaded files are deleted.
|
3068
|
-
proxies (`Dict[str, str]`, *optional*):
|
3069
|
-
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
3070
|
-
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
3071
|
-
local_files_only (`bool`, *optional*, defaults to `False`):
|
3072
|
-
Whether to only load local model weights and configuration files or not. If set to True, the model
|
3073
|
-
won't be downloaded from the Hub.
|
3074
|
-
use_auth_token (`str` or *bool*, *optional*):
|
3075
|
-
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
3076
|
-
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
3077
|
-
revision (`str`, *optional*, defaults to `"main"`):
|
3078
|
-
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
3079
|
-
allowed by Git.
|
3080
|
-
use_safetensors (`bool`, *optional*, defaults to `None`):
|
3081
|
-
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
3082
|
-
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
3083
|
-
weights. If set to `False`, safetensors weights are not loaded.
|
3084
|
-
image_size (`int`, *optional*, defaults to 512):
|
3085
|
-
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
3086
|
-
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
3087
|
-
upcast_attention (`bool`, *optional*, defaults to `None`):
|
3088
|
-
Whether the attention computation should always be upcasted.
|
3089
|
-
kwargs (remaining dictionary of keyword arguments, *optional*):
|
3090
|
-
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
3091
|
-
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
3092
|
-
method. See example below for more information.
|
3093
|
-
|
3094
|
-
Examples:
|
3095
|
-
|
3096
|
-
```py
|
3097
|
-
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
3098
|
-
|
3099
|
-
url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
|
3100
|
-
model = ControlNetModel.from_single_file(url)
|
3101
|
-
|
3102
|
-
url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
|
3103
|
-
pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
|
3104
|
-
```
|
3105
|
-
"""
|
3106
|
-
# import here to avoid circular dependency
|
3107
|
-
from .pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
|
3108
|
-
|
3109
|
-
config_file = kwargs.pop("config_file", None)
|
3110
|
-
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
3111
|
-
resume_download = kwargs.pop("resume_download", False)
|
3112
|
-
force_download = kwargs.pop("force_download", False)
|
3113
|
-
proxies = kwargs.pop("proxies", None)
|
3114
|
-
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
3115
|
-
use_auth_token = kwargs.pop("use_auth_token", None)
|
3116
|
-
num_in_channels = kwargs.pop("num_in_channels", None)
|
3117
|
-
use_linear_projection = kwargs.pop("use_linear_projection", None)
|
3118
|
-
revision = kwargs.pop("revision", None)
|
3119
|
-
extract_ema = kwargs.pop("extract_ema", False)
|
3120
|
-
image_size = kwargs.pop("image_size", None)
|
3121
|
-
upcast_attention = kwargs.pop("upcast_attention", None)
|
3122
|
-
|
3123
|
-
torch_dtype = kwargs.pop("torch_dtype", None)
|
3124
|
-
|
3125
|
-
use_safetensors = kwargs.pop("use_safetensors", None)
|
3126
|
-
|
3127
|
-
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
3128
|
-
from_safetensors = file_extension == "safetensors"
|
3129
|
-
|
3130
|
-
if from_safetensors and use_safetensors is False:
|
3131
|
-
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
3132
|
-
|
3133
|
-
# remove huggingface url
|
3134
|
-
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
3135
|
-
if pretrained_model_link_or_path.startswith(prefix):
|
3136
|
-
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
3137
|
-
|
3138
|
-
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
3139
|
-
ckpt_path = Path(pretrained_model_link_or_path)
|
3140
|
-
if not ckpt_path.is_file():
|
3141
|
-
# get repo_id and (potentially nested) file path of ckpt in repo
|
3142
|
-
repo_id = "/".join(ckpt_path.parts[:2])
|
3143
|
-
file_path = "/".join(ckpt_path.parts[2:])
|
3144
|
-
|
3145
|
-
if file_path.startswith("blob/"):
|
3146
|
-
file_path = file_path[len("blob/") :]
|
3147
|
-
|
3148
|
-
if file_path.startswith("main/"):
|
3149
|
-
file_path = file_path[len("main/") :]
|
3150
|
-
|
3151
|
-
pretrained_model_link_or_path = hf_hub_download(
|
3152
|
-
repo_id,
|
3153
|
-
filename=file_path,
|
3154
|
-
cache_dir=cache_dir,
|
3155
|
-
resume_download=resume_download,
|
3156
|
-
proxies=proxies,
|
3157
|
-
local_files_only=local_files_only,
|
3158
|
-
use_auth_token=use_auth_token,
|
3159
|
-
revision=revision,
|
3160
|
-
force_download=force_download,
|
3161
|
-
)
|
3162
|
-
|
3163
|
-
if config_file is None:
|
3164
|
-
config_url = "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml"
|
3165
|
-
config_file = BytesIO(requests.get(config_url).content)
|
3166
|
-
|
3167
|
-
image_size = image_size or 512
|
3168
|
-
|
3169
|
-
controlnet = download_controlnet_from_original_ckpt(
|
3170
|
-
pretrained_model_link_or_path,
|
3171
|
-
original_config_file=config_file,
|
3172
|
-
image_size=image_size,
|
3173
|
-
extract_ema=extract_ema,
|
3174
|
-
num_in_channels=num_in_channels,
|
3175
|
-
upcast_attention=upcast_attention,
|
3176
|
-
from_safetensors=from_safetensors,
|
3177
|
-
use_linear_projection=use_linear_projection,
|
3178
|
-
)
|
3179
|
-
|
3180
|
-
if torch_dtype is not None:
|
3181
|
-
controlnet.to(dtype=torch_dtype)
|
3182
|
-
|
3183
|
-
return controlnet
|
3184
|
-
|
3185
|
-
|
3186
|
-
class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
|
3187
|
-
"""This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
|
3188
|
-
|
3189
|
-
# Overrride to properly handle the loading and unloading of the additional text encoder.
|
3190
|
-
def load_lora_weights(
|
3191
|
-
self,
|
3192
|
-
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
3193
|
-
adapter_name: Optional[str] = None,
|
3194
|
-
**kwargs,
|
3195
|
-
):
|
3196
|
-
"""
|
3197
|
-
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
3198
|
-
`self.text_encoder`.
|
3199
|
-
|
3200
|
-
All kwargs are forwarded to `self.lora_state_dict`.
|
3201
|
-
|
3202
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
3203
|
-
|
3204
|
-
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
3205
|
-
`self.unet`.
|
3206
|
-
|
3207
|
-
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
3208
|
-
into `self.text_encoder`.
|
3209
|
-
|
3210
|
-
Parameters:
|
3211
|
-
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
3212
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
3213
|
-
adapter_name (`str`, *optional*):
|
3214
|
-
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
3215
|
-
`default_{i}` where i is the total number of adapters being loaded.
|
3216
|
-
kwargs (`dict`, *optional*):
|
3217
|
-
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
3218
|
-
"""
|
3219
|
-
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
3220
|
-
# it here explicitly to be able to tell that it's coming from an SDXL
|
3221
|
-
# pipeline.
|
3222
|
-
|
3223
|
-
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
3224
|
-
state_dict, network_alphas = self.lora_state_dict(
|
3225
|
-
pretrained_model_name_or_path_or_dict,
|
3226
|
-
unet_config=self.unet.config,
|
3227
|
-
**kwargs,
|
3228
|
-
)
|
3229
|
-
is_correct_format = all("lora" in key for key in state_dict.keys())
|
3230
|
-
if not is_correct_format:
|
3231
|
-
raise ValueError("Invalid LoRA checkpoint.")
|
3232
|
-
|
3233
|
-
self.load_lora_into_unet(
|
3234
|
-
state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
|
3235
|
-
)
|
3236
|
-
text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
|
3237
|
-
if len(text_encoder_state_dict) > 0:
|
3238
|
-
self.load_lora_into_text_encoder(
|
3239
|
-
text_encoder_state_dict,
|
3240
|
-
network_alphas=network_alphas,
|
3241
|
-
text_encoder=self.text_encoder,
|
3242
|
-
prefix="text_encoder",
|
3243
|
-
lora_scale=self.lora_scale,
|
3244
|
-
adapter_name=adapter_name,
|
3245
|
-
_pipeline=self,
|
3246
|
-
)
|
3247
|
-
|
3248
|
-
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
|
3249
|
-
if len(text_encoder_2_state_dict) > 0:
|
3250
|
-
self.load_lora_into_text_encoder(
|
3251
|
-
text_encoder_2_state_dict,
|
3252
|
-
network_alphas=network_alphas,
|
3253
|
-
text_encoder=self.text_encoder_2,
|
3254
|
-
prefix="text_encoder_2",
|
3255
|
-
lora_scale=self.lora_scale,
|
3256
|
-
adapter_name=adapter_name,
|
3257
|
-
_pipeline=self,
|
3258
|
-
)
|
3259
|
-
|
3260
|
-
@classmethod
|
3261
|
-
def save_lora_weights(
|
3262
|
-
cls,
|
3263
|
-
save_directory: Union[str, os.PathLike],
|
3264
|
-
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
3265
|
-
text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
3266
|
-
text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
3267
|
-
is_main_process: bool = True,
|
3268
|
-
weight_name: str = None,
|
3269
|
-
save_function: Callable = None,
|
3270
|
-
safe_serialization: bool = True,
|
3271
|
-
):
|
3272
|
-
r"""
|
3273
|
-
Save the LoRA parameters corresponding to the UNet and text encoder.
|
3274
|
-
|
3275
|
-
Arguments:
|
3276
|
-
save_directory (`str` or `os.PathLike`):
|
3277
|
-
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
3278
|
-
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
3279
|
-
State dict of the LoRA layers corresponding to the `unet`.
|
3280
|
-
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
3281
|
-
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
3282
|
-
encoder LoRA state dict because it comes from 🤗 Transformers.
|
3283
|
-
is_main_process (`bool`, *optional*, defaults to `True`):
|
3284
|
-
Whether the process calling this is the main process or not. Useful during distributed training and you
|
3285
|
-
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
3286
|
-
process to avoid race conditions.
|
3287
|
-
save_function (`Callable`):
|
3288
|
-
The function to use to save the state dictionary. Useful during distributed training when you need to
|
3289
|
-
replace `torch.save` with another method. Can be configured with the environment variable
|
3290
|
-
`DIFFUSERS_SAVE_MODE`.
|
3291
|
-
safe_serialization (`bool`, *optional*, defaults to `True`):
|
3292
|
-
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
3293
|
-
"""
|
3294
|
-
state_dict = {}
|
3295
|
-
|
3296
|
-
def pack_weights(layers, prefix):
|
3297
|
-
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
3298
|
-
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
3299
|
-
return layers_state_dict
|
3300
|
-
|
3301
|
-
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
|
3302
|
-
raise ValueError(
|
3303
|
-
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
3304
|
-
)
|
3305
|
-
|
3306
|
-
if unet_lora_layers:
|
3307
|
-
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
3308
|
-
|
3309
|
-
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
3310
|
-
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
3311
|
-
state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
|
3312
|
-
|
3313
|
-
cls.write_lora_layers(
|
3314
|
-
state_dict=state_dict,
|
3315
|
-
save_directory=save_directory,
|
3316
|
-
is_main_process=is_main_process,
|
3317
|
-
weight_name=weight_name,
|
3318
|
-
save_function=save_function,
|
3319
|
-
safe_serialization=safe_serialization,
|
3320
|
-
)
|
3321
|
-
|
3322
|
-
def _remove_text_encoder_monkey_patch(self):
|
3323
|
-
if USE_PEFT_BACKEND:
|
3324
|
-
recurse_remove_peft_layers(self.text_encoder)
|
3325
|
-
# TODO: @younesbelkada handle this in transformers side
|
3326
|
-
if getattr(self.text_encoder, "peft_config", None) is not None:
|
3327
|
-
del self.text_encoder.peft_config
|
3328
|
-
self.text_encoder._hf_peft_config_loaded = None
|
3329
|
-
|
3330
|
-
recurse_remove_peft_layers(self.text_encoder_2)
|
3331
|
-
if getattr(self.text_encoder_2, "peft_config", None) is not None:
|
3332
|
-
del self.text_encoder_2.peft_config
|
3333
|
-
self.text_encoder_2._hf_peft_config_loaded = None
|
3334
|
-
else:
|
3335
|
-
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
|
3336
|
-
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
|