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
@@ -0,0 +1,637 @@
|
|
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
|
+
from contextlib import nullcontext
|
15
|
+
from io import BytesIO
|
16
|
+
from pathlib import Path
|
17
|
+
|
18
|
+
import requests
|
19
|
+
import torch
|
20
|
+
from huggingface_hub import hf_hub_download
|
21
|
+
from huggingface_hub.utils import validate_hf_hub_args
|
22
|
+
|
23
|
+
from ..utils import (
|
24
|
+
deprecate,
|
25
|
+
is_accelerate_available,
|
26
|
+
is_omegaconf_available,
|
27
|
+
is_transformers_available,
|
28
|
+
logging,
|
29
|
+
)
|
30
|
+
from ..utils.import_utils import BACKENDS_MAPPING
|
31
|
+
|
32
|
+
|
33
|
+
if is_transformers_available():
|
34
|
+
pass
|
35
|
+
|
36
|
+
if is_accelerate_available():
|
37
|
+
from accelerate import init_empty_weights
|
38
|
+
|
39
|
+
logger = logging.get_logger(__name__)
|
40
|
+
|
41
|
+
|
42
|
+
class FromSingleFileMixin:
|
43
|
+
"""
|
44
|
+
Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
|
45
|
+
"""
|
46
|
+
|
47
|
+
@classmethod
|
48
|
+
def from_ckpt(cls, *args, **kwargs):
|
49
|
+
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."
|
50
|
+
deprecate("from_ckpt", "0.21.0", deprecation_message, standard_warn=False)
|
51
|
+
return cls.from_single_file(*args, **kwargs)
|
52
|
+
|
53
|
+
@classmethod
|
54
|
+
@validate_hf_hub_args
|
55
|
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
56
|
+
r"""
|
57
|
+
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
|
58
|
+
format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
59
|
+
|
60
|
+
Parameters:
|
61
|
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
62
|
+
Can be either:
|
63
|
+
- A link to the `.ckpt` file (for example
|
64
|
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
65
|
+
- A path to a *file* containing all pipeline weights.
|
66
|
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
67
|
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
68
|
+
dtype is automatically derived from the model's weights.
|
69
|
+
force_download (`bool`, *optional*, defaults to `False`):
|
70
|
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
71
|
+
cached versions if they exist.
|
72
|
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
73
|
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
74
|
+
is not used.
|
75
|
+
resume_download (`bool`, *optional*, defaults to `False`):
|
76
|
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
77
|
+
incompletely downloaded files are deleted.
|
78
|
+
proxies (`Dict[str, str]`, *optional*):
|
79
|
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
80
|
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
81
|
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
82
|
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
83
|
+
won't be downloaded from the Hub.
|
84
|
+
token (`str` or *bool*, *optional*):
|
85
|
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
86
|
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
87
|
+
revision (`str`, *optional*, defaults to `"main"`):
|
88
|
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
89
|
+
allowed by Git.
|
90
|
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
91
|
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
92
|
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
93
|
+
weights. If set to `False`, safetensors weights are not loaded.
|
94
|
+
extract_ema (`bool`, *optional*, defaults to `False`):
|
95
|
+
Whether to extract the EMA weights or not. Pass `True` to extract the EMA weights which usually yield
|
96
|
+
higher quality images for inference. Non-EMA weights are usually better for continuing finetuning.
|
97
|
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
98
|
+
Whether the attention computation should always be upcasted.
|
99
|
+
image_size (`int`, *optional*, defaults to 512):
|
100
|
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
101
|
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
102
|
+
prediction_type (`str`, *optional*):
|
103
|
+
The prediction type the model was trained on. Use `'epsilon'` for all Stable Diffusion v1 models and
|
104
|
+
the Stable Diffusion v2 base model. Use `'v_prediction'` for Stable Diffusion v2.
|
105
|
+
num_in_channels (`int`, *optional*, defaults to `None`):
|
106
|
+
The number of input channels. If `None`, it is automatically inferred.
|
107
|
+
scheduler_type (`str`, *optional*, defaults to `"pndm"`):
|
108
|
+
Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm",
|
109
|
+
"ddim"]`.
|
110
|
+
load_safety_checker (`bool`, *optional*, defaults to `True`):
|
111
|
+
Whether to load the safety checker or not.
|
112
|
+
text_encoder ([`~transformers.CLIPTextModel`], *optional*, defaults to `None`):
|
113
|
+
An instance of `CLIPTextModel` to use, specifically the
|
114
|
+
[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. If this
|
115
|
+
parameter is `None`, the function loads a new instance of `CLIPTextModel` by itself if needed.
|
116
|
+
vae (`AutoencoderKL`, *optional*, defaults to `None`):
|
117
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. If
|
118
|
+
this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
|
119
|
+
tokenizer ([`~transformers.CLIPTokenizer`], *optional*, defaults to `None`):
|
120
|
+
An instance of `CLIPTokenizer` to use. If this parameter is `None`, the function loads a new instance
|
121
|
+
of `CLIPTokenizer` by itself if needed.
|
122
|
+
original_config_file (`str`):
|
123
|
+
Path to `.yaml` config file corresponding to the original architecture. If `None`, will be
|
124
|
+
automatically inferred by looking for a key that only exists in SD2.0 models.
|
125
|
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
126
|
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
127
|
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
128
|
+
method. See example below for more information.
|
129
|
+
|
130
|
+
Examples:
|
131
|
+
|
132
|
+
```py
|
133
|
+
>>> from diffusers import StableDiffusionPipeline
|
134
|
+
|
135
|
+
>>> # Download pipeline from huggingface.co and cache.
|
136
|
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
137
|
+
... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
|
138
|
+
... )
|
139
|
+
|
140
|
+
>>> # Download pipeline from local file
|
141
|
+
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
|
142
|
+
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
|
143
|
+
|
144
|
+
>>> # Enable float16 and move to GPU
|
145
|
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
146
|
+
... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
|
147
|
+
... torch_dtype=torch.float16,
|
148
|
+
... )
|
149
|
+
>>> pipeline.to("cuda")
|
150
|
+
```
|
151
|
+
"""
|
152
|
+
# import here to avoid circular dependency
|
153
|
+
from ..pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
|
154
|
+
|
155
|
+
original_config_file = kwargs.pop("original_config_file", None)
|
156
|
+
config_files = kwargs.pop("config_files", None)
|
157
|
+
cache_dir = kwargs.pop("cache_dir", None)
|
158
|
+
resume_download = kwargs.pop("resume_download", False)
|
159
|
+
force_download = kwargs.pop("force_download", False)
|
160
|
+
proxies = kwargs.pop("proxies", None)
|
161
|
+
local_files_only = kwargs.pop("local_files_only", None)
|
162
|
+
token = kwargs.pop("token", None)
|
163
|
+
revision = kwargs.pop("revision", None)
|
164
|
+
extract_ema = kwargs.pop("extract_ema", False)
|
165
|
+
image_size = kwargs.pop("image_size", None)
|
166
|
+
scheduler_type = kwargs.pop("scheduler_type", "pndm")
|
167
|
+
num_in_channels = kwargs.pop("num_in_channels", None)
|
168
|
+
upcast_attention = kwargs.pop("upcast_attention", None)
|
169
|
+
load_safety_checker = kwargs.pop("load_safety_checker", True)
|
170
|
+
prediction_type = kwargs.pop("prediction_type", None)
|
171
|
+
text_encoder = kwargs.pop("text_encoder", None)
|
172
|
+
text_encoder_2 = kwargs.pop("text_encoder_2", None)
|
173
|
+
vae = kwargs.pop("vae", None)
|
174
|
+
controlnet = kwargs.pop("controlnet", None)
|
175
|
+
adapter = kwargs.pop("adapter", None)
|
176
|
+
tokenizer = kwargs.pop("tokenizer", None)
|
177
|
+
tokenizer_2 = kwargs.pop("tokenizer_2", None)
|
178
|
+
|
179
|
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
180
|
+
|
181
|
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
182
|
+
|
183
|
+
pipeline_name = cls.__name__
|
184
|
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
185
|
+
from_safetensors = file_extension == "safetensors"
|
186
|
+
|
187
|
+
if from_safetensors and use_safetensors is False:
|
188
|
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
189
|
+
|
190
|
+
# TODO: For now we only support stable diffusion
|
191
|
+
stable_unclip = None
|
192
|
+
model_type = None
|
193
|
+
|
194
|
+
if pipeline_name in [
|
195
|
+
"StableDiffusionControlNetPipeline",
|
196
|
+
"StableDiffusionControlNetImg2ImgPipeline",
|
197
|
+
"StableDiffusionControlNetInpaintPipeline",
|
198
|
+
]:
|
199
|
+
from ..models.controlnet import ControlNetModel
|
200
|
+
from ..pipelines.controlnet.multicontrolnet import MultiControlNetModel
|
201
|
+
|
202
|
+
# list/tuple or a single instance of ControlNetModel or MultiControlNetModel
|
203
|
+
if not (
|
204
|
+
isinstance(controlnet, (ControlNetModel, MultiControlNetModel))
|
205
|
+
or isinstance(controlnet, (list, tuple))
|
206
|
+
and isinstance(controlnet[0], ControlNetModel)
|
207
|
+
):
|
208
|
+
raise ValueError("ControlNet needs to be passed if loading from ControlNet pipeline.")
|
209
|
+
elif "StableDiffusion" in pipeline_name:
|
210
|
+
# Model type will be inferred from the checkpoint.
|
211
|
+
pass
|
212
|
+
elif pipeline_name == "StableUnCLIPPipeline":
|
213
|
+
model_type = "FrozenOpenCLIPEmbedder"
|
214
|
+
stable_unclip = "txt2img"
|
215
|
+
elif pipeline_name == "StableUnCLIPImg2ImgPipeline":
|
216
|
+
model_type = "FrozenOpenCLIPEmbedder"
|
217
|
+
stable_unclip = "img2img"
|
218
|
+
elif pipeline_name == "PaintByExamplePipeline":
|
219
|
+
model_type = "PaintByExample"
|
220
|
+
elif pipeline_name == "LDMTextToImagePipeline":
|
221
|
+
model_type = "LDMTextToImage"
|
222
|
+
else:
|
223
|
+
raise ValueError(f"Unhandled pipeline class: {pipeline_name}")
|
224
|
+
|
225
|
+
# remove huggingface url
|
226
|
+
has_valid_url_prefix = False
|
227
|
+
valid_url_prefixes = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
|
228
|
+
for prefix in valid_url_prefixes:
|
229
|
+
if pretrained_model_link_or_path.startswith(prefix):
|
230
|
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
231
|
+
has_valid_url_prefix = True
|
232
|
+
|
233
|
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
234
|
+
ckpt_path = Path(pretrained_model_link_or_path)
|
235
|
+
if not ckpt_path.is_file():
|
236
|
+
if not has_valid_url_prefix:
|
237
|
+
raise ValueError(
|
238
|
+
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)}"
|
239
|
+
)
|
240
|
+
|
241
|
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
242
|
+
repo_id = "/".join(ckpt_path.parts[:2])
|
243
|
+
file_path = "/".join(ckpt_path.parts[2:])
|
244
|
+
|
245
|
+
if file_path.startswith("blob/"):
|
246
|
+
file_path = file_path[len("blob/") :]
|
247
|
+
|
248
|
+
if file_path.startswith("main/"):
|
249
|
+
file_path = file_path[len("main/") :]
|
250
|
+
|
251
|
+
pretrained_model_link_or_path = hf_hub_download(
|
252
|
+
repo_id,
|
253
|
+
filename=file_path,
|
254
|
+
cache_dir=cache_dir,
|
255
|
+
resume_download=resume_download,
|
256
|
+
proxies=proxies,
|
257
|
+
local_files_only=local_files_only,
|
258
|
+
token=token,
|
259
|
+
revision=revision,
|
260
|
+
force_download=force_download,
|
261
|
+
)
|
262
|
+
|
263
|
+
pipe = download_from_original_stable_diffusion_ckpt(
|
264
|
+
pretrained_model_link_or_path,
|
265
|
+
pipeline_class=cls,
|
266
|
+
model_type=model_type,
|
267
|
+
stable_unclip=stable_unclip,
|
268
|
+
controlnet=controlnet,
|
269
|
+
adapter=adapter,
|
270
|
+
from_safetensors=from_safetensors,
|
271
|
+
extract_ema=extract_ema,
|
272
|
+
image_size=image_size,
|
273
|
+
scheduler_type=scheduler_type,
|
274
|
+
num_in_channels=num_in_channels,
|
275
|
+
upcast_attention=upcast_attention,
|
276
|
+
load_safety_checker=load_safety_checker,
|
277
|
+
prediction_type=prediction_type,
|
278
|
+
text_encoder=text_encoder,
|
279
|
+
text_encoder_2=text_encoder_2,
|
280
|
+
vae=vae,
|
281
|
+
tokenizer=tokenizer,
|
282
|
+
tokenizer_2=tokenizer_2,
|
283
|
+
original_config_file=original_config_file,
|
284
|
+
config_files=config_files,
|
285
|
+
local_files_only=local_files_only,
|
286
|
+
)
|
287
|
+
|
288
|
+
if torch_dtype is not None:
|
289
|
+
pipe.to(dtype=torch_dtype)
|
290
|
+
|
291
|
+
return pipe
|
292
|
+
|
293
|
+
|
294
|
+
class FromOriginalVAEMixin:
|
295
|
+
"""
|
296
|
+
Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into an [`AutoencoderKL`].
|
297
|
+
"""
|
298
|
+
|
299
|
+
@classmethod
|
300
|
+
@validate_hf_hub_args
|
301
|
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
302
|
+
r"""
|
303
|
+
Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
304
|
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
305
|
+
|
306
|
+
Parameters:
|
307
|
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
308
|
+
Can be either:
|
309
|
+
- A link to the `.ckpt` file (for example
|
310
|
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
311
|
+
- A path to a *file* containing all pipeline weights.
|
312
|
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
313
|
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
314
|
+
dtype is automatically derived from the model's weights.
|
315
|
+
force_download (`bool`, *optional*, defaults to `False`):
|
316
|
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
317
|
+
cached versions if they exist.
|
318
|
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
319
|
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
320
|
+
is not used.
|
321
|
+
resume_download (`bool`, *optional*, defaults to `False`):
|
322
|
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
323
|
+
incompletely downloaded files are deleted.
|
324
|
+
proxies (`Dict[str, str]`, *optional*):
|
325
|
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
326
|
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
327
|
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
328
|
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
329
|
+
won't be downloaded from the Hub.
|
330
|
+
token (`str` or *bool*, *optional*):
|
331
|
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
332
|
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
333
|
+
revision (`str`, *optional*, defaults to `"main"`):
|
334
|
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
335
|
+
allowed by Git.
|
336
|
+
image_size (`int`, *optional*, defaults to 512):
|
337
|
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
338
|
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
339
|
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
340
|
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
341
|
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
342
|
+
weights. If set to `False`, safetensors weights are not loaded.
|
343
|
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
344
|
+
Whether the attention computation should always be upcasted.
|
345
|
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
346
|
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
347
|
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
348
|
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
349
|
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
|
350
|
+
= 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
|
351
|
+
Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
352
|
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
353
|
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
354
|
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
355
|
+
method. See example below for more information.
|
356
|
+
|
357
|
+
<Tip warning={true}>
|
358
|
+
|
359
|
+
Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
|
360
|
+
a VAE from SDXL or a Stable Diffusion v2 model or higher.
|
361
|
+
|
362
|
+
</Tip>
|
363
|
+
|
364
|
+
Examples:
|
365
|
+
|
366
|
+
```py
|
367
|
+
from diffusers import AutoencoderKL
|
368
|
+
|
369
|
+
url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
|
370
|
+
model = AutoencoderKL.from_single_file(url)
|
371
|
+
```
|
372
|
+
"""
|
373
|
+
if not is_omegaconf_available():
|
374
|
+
raise ValueError(BACKENDS_MAPPING["omegaconf"][1])
|
375
|
+
|
376
|
+
from omegaconf import OmegaConf
|
377
|
+
|
378
|
+
from ..models import AutoencoderKL
|
379
|
+
|
380
|
+
# import here to avoid circular dependency
|
381
|
+
from ..pipelines.stable_diffusion.convert_from_ckpt import (
|
382
|
+
convert_ldm_vae_checkpoint,
|
383
|
+
create_vae_diffusers_config,
|
384
|
+
)
|
385
|
+
|
386
|
+
config_file = kwargs.pop("config_file", None)
|
387
|
+
cache_dir = kwargs.pop("cache_dir", None)
|
388
|
+
resume_download = kwargs.pop("resume_download", False)
|
389
|
+
force_download = kwargs.pop("force_download", False)
|
390
|
+
proxies = kwargs.pop("proxies", None)
|
391
|
+
local_files_only = kwargs.pop("local_files_only", None)
|
392
|
+
token = kwargs.pop("token", None)
|
393
|
+
revision = kwargs.pop("revision", None)
|
394
|
+
image_size = kwargs.pop("image_size", None)
|
395
|
+
scaling_factor = kwargs.pop("scaling_factor", None)
|
396
|
+
kwargs.pop("upcast_attention", None)
|
397
|
+
|
398
|
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
399
|
+
|
400
|
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
401
|
+
|
402
|
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
403
|
+
from_safetensors = file_extension == "safetensors"
|
404
|
+
|
405
|
+
if from_safetensors and use_safetensors is False:
|
406
|
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
407
|
+
|
408
|
+
# remove huggingface url
|
409
|
+
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
410
|
+
if pretrained_model_link_or_path.startswith(prefix):
|
411
|
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
412
|
+
|
413
|
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
414
|
+
ckpt_path = Path(pretrained_model_link_or_path)
|
415
|
+
if not ckpt_path.is_file():
|
416
|
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
417
|
+
repo_id = "/".join(ckpt_path.parts[:2])
|
418
|
+
file_path = "/".join(ckpt_path.parts[2:])
|
419
|
+
|
420
|
+
if file_path.startswith("blob/"):
|
421
|
+
file_path = file_path[len("blob/") :]
|
422
|
+
|
423
|
+
if file_path.startswith("main/"):
|
424
|
+
file_path = file_path[len("main/") :]
|
425
|
+
|
426
|
+
pretrained_model_link_or_path = hf_hub_download(
|
427
|
+
repo_id,
|
428
|
+
filename=file_path,
|
429
|
+
cache_dir=cache_dir,
|
430
|
+
resume_download=resume_download,
|
431
|
+
proxies=proxies,
|
432
|
+
local_files_only=local_files_only,
|
433
|
+
token=token,
|
434
|
+
revision=revision,
|
435
|
+
force_download=force_download,
|
436
|
+
)
|
437
|
+
|
438
|
+
if from_safetensors:
|
439
|
+
from safetensors import safe_open
|
440
|
+
|
441
|
+
checkpoint = {}
|
442
|
+
with safe_open(pretrained_model_link_or_path, framework="pt", device="cpu") as f:
|
443
|
+
for key in f.keys():
|
444
|
+
checkpoint[key] = f.get_tensor(key)
|
445
|
+
else:
|
446
|
+
checkpoint = torch.load(pretrained_model_link_or_path, map_location="cpu")
|
447
|
+
|
448
|
+
if "state_dict" in checkpoint:
|
449
|
+
checkpoint = checkpoint["state_dict"]
|
450
|
+
|
451
|
+
if config_file is None:
|
452
|
+
config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
|
453
|
+
config_file = BytesIO(requests.get(config_url).content)
|
454
|
+
|
455
|
+
original_config = OmegaConf.load(config_file)
|
456
|
+
|
457
|
+
# default to sd-v1-5
|
458
|
+
image_size = image_size or 512
|
459
|
+
|
460
|
+
vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
|
461
|
+
converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
|
462
|
+
|
463
|
+
if scaling_factor is None:
|
464
|
+
if (
|
465
|
+
"model" in original_config
|
466
|
+
and "params" in original_config.model
|
467
|
+
and "scale_factor" in original_config.model.params
|
468
|
+
):
|
469
|
+
vae_scaling_factor = original_config.model.params.scale_factor
|
470
|
+
else:
|
471
|
+
vae_scaling_factor = 0.18215 # default SD scaling factor
|
472
|
+
|
473
|
+
vae_config["scaling_factor"] = vae_scaling_factor
|
474
|
+
|
475
|
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
476
|
+
with ctx():
|
477
|
+
vae = AutoencoderKL(**vae_config)
|
478
|
+
|
479
|
+
if is_accelerate_available():
|
480
|
+
from ..models.modeling_utils import load_model_dict_into_meta
|
481
|
+
|
482
|
+
load_model_dict_into_meta(vae, converted_vae_checkpoint, device="cpu")
|
483
|
+
else:
|
484
|
+
vae.load_state_dict(converted_vae_checkpoint)
|
485
|
+
|
486
|
+
if torch_dtype is not None:
|
487
|
+
vae.to(dtype=torch_dtype)
|
488
|
+
|
489
|
+
return vae
|
490
|
+
|
491
|
+
|
492
|
+
class FromOriginalControlnetMixin:
|
493
|
+
"""
|
494
|
+
Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
|
495
|
+
"""
|
496
|
+
|
497
|
+
@classmethod
|
498
|
+
@validate_hf_hub_args
|
499
|
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
500
|
+
r"""
|
501
|
+
Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
502
|
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
503
|
+
|
504
|
+
Parameters:
|
505
|
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
506
|
+
Can be either:
|
507
|
+
- A link to the `.ckpt` file (for example
|
508
|
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
509
|
+
- A path to a *file* containing all pipeline weights.
|
510
|
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
511
|
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
512
|
+
dtype is automatically derived from the model's weights.
|
513
|
+
force_download (`bool`, *optional*, defaults to `False`):
|
514
|
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
515
|
+
cached versions if they exist.
|
516
|
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
517
|
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
518
|
+
is not used.
|
519
|
+
resume_download (`bool`, *optional*, defaults to `False`):
|
520
|
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
521
|
+
incompletely downloaded files are deleted.
|
522
|
+
proxies (`Dict[str, str]`, *optional*):
|
523
|
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
524
|
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
525
|
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
526
|
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
527
|
+
won't be downloaded from the Hub.
|
528
|
+
token (`str` or *bool*, *optional*):
|
529
|
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
530
|
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
531
|
+
revision (`str`, *optional*, defaults to `"main"`):
|
532
|
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
533
|
+
allowed by Git.
|
534
|
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
535
|
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
536
|
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
537
|
+
weights. If set to `False`, safetensors weights are not loaded.
|
538
|
+
image_size (`int`, *optional*, defaults to 512):
|
539
|
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
540
|
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
541
|
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
542
|
+
Whether the attention computation should always be upcasted.
|
543
|
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
544
|
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
545
|
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
546
|
+
method. See example below for more information.
|
547
|
+
|
548
|
+
Examples:
|
549
|
+
|
550
|
+
```py
|
551
|
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
552
|
+
|
553
|
+
url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
|
554
|
+
model = ControlNetModel.from_single_file(url)
|
555
|
+
|
556
|
+
url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
|
557
|
+
pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
|
558
|
+
```
|
559
|
+
"""
|
560
|
+
# import here to avoid circular dependency
|
561
|
+
from ..pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
|
562
|
+
|
563
|
+
config_file = kwargs.pop("config_file", None)
|
564
|
+
cache_dir = kwargs.pop("cache_dir", None)
|
565
|
+
resume_download = kwargs.pop("resume_download", False)
|
566
|
+
force_download = kwargs.pop("force_download", False)
|
567
|
+
proxies = kwargs.pop("proxies", None)
|
568
|
+
local_files_only = kwargs.pop("local_files_only", None)
|
569
|
+
token = kwargs.pop("token", None)
|
570
|
+
num_in_channels = kwargs.pop("num_in_channels", None)
|
571
|
+
use_linear_projection = kwargs.pop("use_linear_projection", None)
|
572
|
+
revision = kwargs.pop("revision", None)
|
573
|
+
extract_ema = kwargs.pop("extract_ema", False)
|
574
|
+
image_size = kwargs.pop("image_size", None)
|
575
|
+
upcast_attention = kwargs.pop("upcast_attention", None)
|
576
|
+
|
577
|
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
578
|
+
|
579
|
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
580
|
+
|
581
|
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
582
|
+
from_safetensors = file_extension == "safetensors"
|
583
|
+
|
584
|
+
if from_safetensors and use_safetensors is False:
|
585
|
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
586
|
+
|
587
|
+
# remove huggingface url
|
588
|
+
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
589
|
+
if pretrained_model_link_or_path.startswith(prefix):
|
590
|
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
591
|
+
|
592
|
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
593
|
+
ckpt_path = Path(pretrained_model_link_or_path)
|
594
|
+
if not ckpt_path.is_file():
|
595
|
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
596
|
+
repo_id = "/".join(ckpt_path.parts[:2])
|
597
|
+
file_path = "/".join(ckpt_path.parts[2:])
|
598
|
+
|
599
|
+
if file_path.startswith("blob/"):
|
600
|
+
file_path = file_path[len("blob/") :]
|
601
|
+
|
602
|
+
if file_path.startswith("main/"):
|
603
|
+
file_path = file_path[len("main/") :]
|
604
|
+
|
605
|
+
pretrained_model_link_or_path = hf_hub_download(
|
606
|
+
repo_id,
|
607
|
+
filename=file_path,
|
608
|
+
cache_dir=cache_dir,
|
609
|
+
resume_download=resume_download,
|
610
|
+
proxies=proxies,
|
611
|
+
local_files_only=local_files_only,
|
612
|
+
token=token,
|
613
|
+
revision=revision,
|
614
|
+
force_download=force_download,
|
615
|
+
)
|
616
|
+
|
617
|
+
if config_file is None:
|
618
|
+
config_url = "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml"
|
619
|
+
config_file = BytesIO(requests.get(config_url).content)
|
620
|
+
|
621
|
+
image_size = image_size or 512
|
622
|
+
|
623
|
+
controlnet = download_controlnet_from_original_ckpt(
|
624
|
+
pretrained_model_link_or_path,
|
625
|
+
original_config_file=config_file,
|
626
|
+
image_size=image_size,
|
627
|
+
extract_ema=extract_ema,
|
628
|
+
num_in_channels=num_in_channels,
|
629
|
+
upcast_attention=upcast_attention,
|
630
|
+
from_safetensors=from_safetensors,
|
631
|
+
use_linear_projection=use_linear_projection,
|
632
|
+
)
|
633
|
+
|
634
|
+
if torch_dtype is not None:
|
635
|
+
controlnet.to(dtype=torch_dtype)
|
636
|
+
|
637
|
+
return controlnet
|