diffusers 0.23.1__py3-none-any.whl → 0.24.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (176) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +0 -1
  4. diffusers/dependency_versions_table.py +4 -5
  5. diffusers/image_processor.py +186 -14
  6. diffusers/loaders/__init__.py +82 -0
  7. diffusers/loaders/ip_adapter.py +157 -0
  8. diffusers/loaders/lora.py +1415 -0
  9. diffusers/loaders/lora_conversion_utils.py +284 -0
  10. diffusers/loaders/single_file.py +631 -0
  11. diffusers/loaders/textual_inversion.py +459 -0
  12. diffusers/loaders/unet.py +735 -0
  13. diffusers/loaders/utils.py +59 -0
  14. diffusers/models/__init__.py +12 -1
  15. diffusers/models/attention.py +165 -14
  16. diffusers/models/attention_flax.py +9 -1
  17. diffusers/models/attention_processor.py +286 -1
  18. diffusers/models/autoencoder_asym_kl.py +14 -9
  19. diffusers/models/autoencoder_kl.py +3 -18
  20. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  21. diffusers/models/autoencoder_tiny.py +20 -24
  22. diffusers/models/consistency_decoder_vae.py +37 -30
  23. diffusers/models/controlnet.py +59 -39
  24. diffusers/models/controlnet_flax.py +19 -18
  25. diffusers/models/embeddings_flax.py +2 -0
  26. diffusers/models/lora.py +131 -1
  27. diffusers/models/modeling_flax_utils.py +2 -1
  28. diffusers/models/modeling_outputs.py +17 -0
  29. diffusers/models/modeling_utils.py +27 -19
  30. diffusers/models/normalization.py +2 -2
  31. diffusers/models/resnet.py +390 -59
  32. diffusers/models/transformer_2d.py +20 -3
  33. diffusers/models/transformer_temporal.py +183 -1
  34. diffusers/models/unet_2d_blocks_flax.py +5 -0
  35. diffusers/models/unet_2d_condition.py +9 -0
  36. diffusers/models/unet_2d_condition_flax.py +13 -13
  37. diffusers/models/unet_3d_blocks.py +957 -173
  38. diffusers/models/unet_3d_condition.py +16 -8
  39. diffusers/models/unet_kandi3.py +589 -0
  40. diffusers/models/unet_motion_model.py +48 -33
  41. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  42. diffusers/models/vae.py +63 -13
  43. diffusers/models/vae_flax.py +7 -0
  44. diffusers/models/vq_model.py +3 -1
  45. diffusers/optimization.py +16 -9
  46. diffusers/pipelines/__init__.py +65 -12
  47. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
  48. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
  49. diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
  50. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  51. diffusers/pipelines/auto_pipeline.py +6 -0
  52. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  53. diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
  54. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
  55. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
  56. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
  57. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
  58. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
  59. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  60. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  61. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  62. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  63. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  64. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  65. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  66. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  67. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  68. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  69. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  70. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  71. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  72. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  73. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  74. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  75. diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
  76. diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
  77. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
  78. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
  79. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  80. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  81. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  82. diffusers/pipelines/pipeline_flax_utils.py +4 -2
  83. diffusers/pipelines/pipeline_utils.py +33 -13
  84. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
  85. diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
  86. diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
  87. diffusers/pipelines/stable_diffusion/__init__.py +64 -21
  88. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
  89. diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
  90. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  91. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  92. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  93. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
  94. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
  95. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
  96. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  97. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
  98. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
  107. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
  108. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
  109. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
  110. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
  111. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
  112. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
  113. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
  114. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
  115. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
  116. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
  117. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
  118. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  119. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
  120. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  121. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
  122. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  123. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
  124. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
  125. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
  126. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
  127. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
  128. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
  129. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
  130. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
  131. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  132. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  133. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  134. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  135. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
  136. diffusers/schedulers/__init__.py +2 -4
  137. diffusers/schedulers/deprecated/__init__.py +50 -0
  138. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  139. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  140. diffusers/schedulers/scheduling_ddim.py +1 -3
  141. diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
  142. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  143. diffusers/schedulers/scheduling_ddpm.py +1 -3
  144. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
  145. diffusers/schedulers/scheduling_deis_multistep.py +15 -5
  146. diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
  147. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
  148. diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
  149. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
  150. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
  151. diffusers/schedulers/scheduling_euler_discrete.py +40 -13
  152. diffusers/schedulers/scheduling_heun_discrete.py +15 -5
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
  155. diffusers/schedulers/scheduling_lcm.py +123 -29
  156. diffusers/schedulers/scheduling_lms_discrete.py +1 -3
  157. diffusers/schedulers/scheduling_pndm.py +1 -3
  158. diffusers/schedulers/scheduling_repaint.py +1 -3
  159. diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
  160. diffusers/utils/__init__.py +1 -0
  161. diffusers/utils/constants.py +8 -7
  162. diffusers/utils/dummy_pt_objects.py +45 -0
  163. diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
  164. diffusers/utils/dynamic_modules_utils.py +4 -4
  165. diffusers/utils/export_utils.py +8 -3
  166. diffusers/utils/logging.py +10 -10
  167. diffusers/utils/outputs.py +5 -5
  168. diffusers/utils/peft_utils.py +88 -44
  169. diffusers/utils/torch_utils.py +2 -2
  170. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
  171. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
  172. diffusers/loaders.py +0 -3336
  173. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
  175. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
  176. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,631 @@
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
+
22
+ from ..utils import (
23
+ DIFFUSERS_CACHE,
24
+ HF_HUB_OFFLINE,
25
+ deprecate,
26
+ is_accelerate_available,
27
+ is_omegaconf_available,
28
+ is_transformers_available,
29
+ logging,
30
+ )
31
+ from ..utils.import_utils import BACKENDS_MAPPING
32
+
33
+
34
+ if is_transformers_available():
35
+ pass
36
+
37
+ if is_accelerate_available():
38
+ from accelerate import init_empty_weights
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class FromSingleFileMixin:
44
+ """
45
+ Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
46
+ """
47
+
48
+ @classmethod
49
+ def from_ckpt(cls, *args, **kwargs):
50
+ 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."
51
+ deprecate("from_ckpt", "0.21.0", deprecation_message, standard_warn=False)
52
+ return cls.from_single_file(*args, **kwargs)
53
+
54
+ @classmethod
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
+ use_auth_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", DIFFUSERS_CACHE)
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", HF_HUB_OFFLINE)
162
+ use_auth_token = kwargs.pop("use_auth_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
+ vae = kwargs.pop("vae", None)
173
+ controlnet = kwargs.pop("controlnet", None)
174
+ adapter = kwargs.pop("adapter", None)
175
+ tokenizer = kwargs.pop("tokenizer", None)
176
+
177
+ torch_dtype = kwargs.pop("torch_dtype", None)
178
+
179
+ use_safetensors = kwargs.pop("use_safetensors", None)
180
+
181
+ pipeline_name = cls.__name__
182
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
183
+ from_safetensors = file_extension == "safetensors"
184
+
185
+ if from_safetensors and use_safetensors is False:
186
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
187
+
188
+ # TODO: For now we only support stable diffusion
189
+ stable_unclip = None
190
+ model_type = None
191
+
192
+ if pipeline_name in [
193
+ "StableDiffusionControlNetPipeline",
194
+ "StableDiffusionControlNetImg2ImgPipeline",
195
+ "StableDiffusionControlNetInpaintPipeline",
196
+ ]:
197
+ from ..models.controlnet import ControlNetModel
198
+ from ..pipelines.controlnet.multicontrolnet import MultiControlNetModel
199
+
200
+ # list/tuple or a single instance of ControlNetModel or MultiControlNetModel
201
+ if not (
202
+ isinstance(controlnet, (ControlNetModel, MultiControlNetModel))
203
+ or isinstance(controlnet, (list, tuple))
204
+ and isinstance(controlnet[0], ControlNetModel)
205
+ ):
206
+ raise ValueError("ControlNet needs to be passed if loading from ControlNet pipeline.")
207
+ elif "StableDiffusion" in pipeline_name:
208
+ # Model type will be inferred from the checkpoint.
209
+ pass
210
+ elif pipeline_name == "StableUnCLIPPipeline":
211
+ model_type = "FrozenOpenCLIPEmbedder"
212
+ stable_unclip = "txt2img"
213
+ elif pipeline_name == "StableUnCLIPImg2ImgPipeline":
214
+ model_type = "FrozenOpenCLIPEmbedder"
215
+ stable_unclip = "img2img"
216
+ elif pipeline_name == "PaintByExamplePipeline":
217
+ model_type = "PaintByExample"
218
+ elif pipeline_name == "LDMTextToImagePipeline":
219
+ model_type = "LDMTextToImage"
220
+ else:
221
+ raise ValueError(f"Unhandled pipeline class: {pipeline_name}")
222
+
223
+ # remove huggingface url
224
+ has_valid_url_prefix = False
225
+ valid_url_prefixes = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
226
+ for prefix in valid_url_prefixes:
227
+ if pretrained_model_link_or_path.startswith(prefix):
228
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
229
+ has_valid_url_prefix = True
230
+
231
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
232
+ ckpt_path = Path(pretrained_model_link_or_path)
233
+ if not ckpt_path.is_file():
234
+ if not has_valid_url_prefix:
235
+ raise ValueError(
236
+ 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)}"
237
+ )
238
+
239
+ # get repo_id and (potentially nested) file path of ckpt in repo
240
+ repo_id = "/".join(ckpt_path.parts[:2])
241
+ file_path = "/".join(ckpt_path.parts[2:])
242
+
243
+ if file_path.startswith("blob/"):
244
+ file_path = file_path[len("blob/") :]
245
+
246
+ if file_path.startswith("main/"):
247
+ file_path = file_path[len("main/") :]
248
+
249
+ pretrained_model_link_or_path = hf_hub_download(
250
+ repo_id,
251
+ filename=file_path,
252
+ cache_dir=cache_dir,
253
+ resume_download=resume_download,
254
+ proxies=proxies,
255
+ local_files_only=local_files_only,
256
+ use_auth_token=use_auth_token,
257
+ revision=revision,
258
+ force_download=force_download,
259
+ )
260
+
261
+ pipe = download_from_original_stable_diffusion_ckpt(
262
+ pretrained_model_link_or_path,
263
+ pipeline_class=cls,
264
+ model_type=model_type,
265
+ stable_unclip=stable_unclip,
266
+ controlnet=controlnet,
267
+ adapter=adapter,
268
+ from_safetensors=from_safetensors,
269
+ extract_ema=extract_ema,
270
+ image_size=image_size,
271
+ scheduler_type=scheduler_type,
272
+ num_in_channels=num_in_channels,
273
+ upcast_attention=upcast_attention,
274
+ load_safety_checker=load_safety_checker,
275
+ prediction_type=prediction_type,
276
+ text_encoder=text_encoder,
277
+ vae=vae,
278
+ tokenizer=tokenizer,
279
+ original_config_file=original_config_file,
280
+ config_files=config_files,
281
+ local_files_only=local_files_only,
282
+ )
283
+
284
+ if torch_dtype is not None:
285
+ pipe.to(torch_dtype=torch_dtype)
286
+
287
+ return pipe
288
+
289
+
290
+ class FromOriginalVAEMixin:
291
+ """
292
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into an [`AutoencoderKL`].
293
+ """
294
+
295
+ @classmethod
296
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
297
+ r"""
298
+ Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
299
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
300
+
301
+ Parameters:
302
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
303
+ Can be either:
304
+ - A link to the `.ckpt` file (for example
305
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
306
+ - A path to a *file* containing all pipeline weights.
307
+ torch_dtype (`str` or `torch.dtype`, *optional*):
308
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
309
+ dtype is automatically derived from the model's weights.
310
+ force_download (`bool`, *optional*, defaults to `False`):
311
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
312
+ cached versions if they exist.
313
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
314
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
315
+ is not used.
316
+ resume_download (`bool`, *optional*, defaults to `False`):
317
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
318
+ incompletely downloaded files are deleted.
319
+ proxies (`Dict[str, str]`, *optional*):
320
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
321
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
322
+ local_files_only (`bool`, *optional*, defaults to `False`):
323
+ Whether to only load local model weights and configuration files or not. If set to True, the model
324
+ won't be downloaded from the Hub.
325
+ use_auth_token (`str` or *bool*, *optional*):
326
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
327
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
328
+ revision (`str`, *optional*, defaults to `"main"`):
329
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
330
+ allowed by Git.
331
+ image_size (`int`, *optional*, defaults to 512):
332
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
333
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
334
+ use_safetensors (`bool`, *optional*, defaults to `None`):
335
+ If set to `None`, the safetensors weights are downloaded if they're available **and** if the
336
+ safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
337
+ weights. If set to `False`, safetensors weights are not loaded.
338
+ upcast_attention (`bool`, *optional*, defaults to `None`):
339
+ Whether the attention computation should always be upcasted.
340
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
341
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
342
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
343
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
344
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
345
+ = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
346
+ Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
347
+ kwargs (remaining dictionary of keyword arguments, *optional*):
348
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
349
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
350
+ method. See example below for more information.
351
+
352
+ <Tip warning={true}>
353
+
354
+ Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
355
+ a VAE from SDXL or a Stable Diffusion v2 model or higher.
356
+
357
+ </Tip>
358
+
359
+ Examples:
360
+
361
+ ```py
362
+ from diffusers import AutoencoderKL
363
+
364
+ url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
365
+ model = AutoencoderKL.from_single_file(url)
366
+ ```
367
+ """
368
+ if not is_omegaconf_available():
369
+ raise ValueError(BACKENDS_MAPPING["omegaconf"][1])
370
+
371
+ from omegaconf import OmegaConf
372
+
373
+ from ..models import AutoencoderKL
374
+
375
+ # import here to avoid circular dependency
376
+ from ..pipelines.stable_diffusion.convert_from_ckpt import (
377
+ convert_ldm_vae_checkpoint,
378
+ create_vae_diffusers_config,
379
+ )
380
+
381
+ config_file = kwargs.pop("config_file", None)
382
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
383
+ resume_download = kwargs.pop("resume_download", False)
384
+ force_download = kwargs.pop("force_download", False)
385
+ proxies = kwargs.pop("proxies", None)
386
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
387
+ use_auth_token = kwargs.pop("use_auth_token", None)
388
+ revision = kwargs.pop("revision", None)
389
+ image_size = kwargs.pop("image_size", None)
390
+ scaling_factor = kwargs.pop("scaling_factor", None)
391
+ kwargs.pop("upcast_attention", None)
392
+
393
+ torch_dtype = kwargs.pop("torch_dtype", None)
394
+
395
+ use_safetensors = kwargs.pop("use_safetensors", None)
396
+
397
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
398
+ from_safetensors = file_extension == "safetensors"
399
+
400
+ if from_safetensors and use_safetensors is False:
401
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
402
+
403
+ # remove huggingface url
404
+ for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
405
+ if pretrained_model_link_or_path.startswith(prefix):
406
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
407
+
408
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
409
+ ckpt_path = Path(pretrained_model_link_or_path)
410
+ if not ckpt_path.is_file():
411
+ # get repo_id and (potentially nested) file path of ckpt in repo
412
+ repo_id = "/".join(ckpt_path.parts[:2])
413
+ file_path = "/".join(ckpt_path.parts[2:])
414
+
415
+ if file_path.startswith("blob/"):
416
+ file_path = file_path[len("blob/") :]
417
+
418
+ if file_path.startswith("main/"):
419
+ file_path = file_path[len("main/") :]
420
+
421
+ pretrained_model_link_or_path = hf_hub_download(
422
+ repo_id,
423
+ filename=file_path,
424
+ cache_dir=cache_dir,
425
+ resume_download=resume_download,
426
+ proxies=proxies,
427
+ local_files_only=local_files_only,
428
+ use_auth_token=use_auth_token,
429
+ revision=revision,
430
+ force_download=force_download,
431
+ )
432
+
433
+ if from_safetensors:
434
+ from safetensors import safe_open
435
+
436
+ checkpoint = {}
437
+ with safe_open(pretrained_model_link_or_path, framework="pt", device="cpu") as f:
438
+ for key in f.keys():
439
+ checkpoint[key] = f.get_tensor(key)
440
+ else:
441
+ checkpoint = torch.load(pretrained_model_link_or_path, map_location="cpu")
442
+
443
+ if "state_dict" in checkpoint:
444
+ checkpoint = checkpoint["state_dict"]
445
+
446
+ if config_file is None:
447
+ config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
448
+ config_file = BytesIO(requests.get(config_url).content)
449
+
450
+ original_config = OmegaConf.load(config_file)
451
+
452
+ # default to sd-v1-5
453
+ image_size = image_size or 512
454
+
455
+ vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
456
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
457
+
458
+ if scaling_factor is None:
459
+ if (
460
+ "model" in original_config
461
+ and "params" in original_config.model
462
+ and "scale_factor" in original_config.model.params
463
+ ):
464
+ vae_scaling_factor = original_config.model.params.scale_factor
465
+ else:
466
+ vae_scaling_factor = 0.18215 # default SD scaling factor
467
+
468
+ vae_config["scaling_factor"] = vae_scaling_factor
469
+
470
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
471
+ with ctx():
472
+ vae = AutoencoderKL(**vae_config)
473
+
474
+ if is_accelerate_available():
475
+ from ..models.modeling_utils import load_model_dict_into_meta
476
+
477
+ load_model_dict_into_meta(vae, converted_vae_checkpoint, device="cpu")
478
+ else:
479
+ vae.load_state_dict(converted_vae_checkpoint)
480
+
481
+ if torch_dtype is not None:
482
+ vae.to(dtype=torch_dtype)
483
+
484
+ return vae
485
+
486
+
487
+ class FromOriginalControlnetMixin:
488
+ """
489
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
490
+ """
491
+
492
+ @classmethod
493
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
494
+ r"""
495
+ Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
496
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
497
+
498
+ Parameters:
499
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
500
+ Can be either:
501
+ - A link to the `.ckpt` file (for example
502
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
503
+ - A path to a *file* containing all pipeline weights.
504
+ torch_dtype (`str` or `torch.dtype`, *optional*):
505
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
506
+ dtype is automatically derived from the model's weights.
507
+ force_download (`bool`, *optional*, defaults to `False`):
508
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
509
+ cached versions if they exist.
510
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
511
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
512
+ is not used.
513
+ resume_download (`bool`, *optional*, defaults to `False`):
514
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
515
+ incompletely downloaded files are deleted.
516
+ proxies (`Dict[str, str]`, *optional*):
517
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
518
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
519
+ local_files_only (`bool`, *optional*, defaults to `False`):
520
+ Whether to only load local model weights and configuration files or not. If set to True, the model
521
+ won't be downloaded from the Hub.
522
+ use_auth_token (`str` or *bool*, *optional*):
523
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
524
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
525
+ revision (`str`, *optional*, defaults to `"main"`):
526
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
527
+ allowed by Git.
528
+ use_safetensors (`bool`, *optional*, defaults to `None`):
529
+ If set to `None`, the safetensors weights are downloaded if they're available **and** if the
530
+ safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
531
+ weights. If set to `False`, safetensors weights are not loaded.
532
+ image_size (`int`, *optional*, defaults to 512):
533
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
534
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
535
+ upcast_attention (`bool`, *optional*, defaults to `None`):
536
+ Whether the attention computation should always be upcasted.
537
+ kwargs (remaining dictionary of keyword arguments, *optional*):
538
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
539
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
540
+ method. See example below for more information.
541
+
542
+ Examples:
543
+
544
+ ```py
545
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
546
+
547
+ url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
548
+ model = ControlNetModel.from_single_file(url)
549
+
550
+ url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
551
+ pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
552
+ ```
553
+ """
554
+ # import here to avoid circular dependency
555
+ from ..pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
556
+
557
+ config_file = kwargs.pop("config_file", None)
558
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
559
+ resume_download = kwargs.pop("resume_download", False)
560
+ force_download = kwargs.pop("force_download", False)
561
+ proxies = kwargs.pop("proxies", None)
562
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
563
+ use_auth_token = kwargs.pop("use_auth_token", None)
564
+ num_in_channels = kwargs.pop("num_in_channels", None)
565
+ use_linear_projection = kwargs.pop("use_linear_projection", None)
566
+ revision = kwargs.pop("revision", None)
567
+ extract_ema = kwargs.pop("extract_ema", False)
568
+ image_size = kwargs.pop("image_size", None)
569
+ upcast_attention = kwargs.pop("upcast_attention", None)
570
+
571
+ torch_dtype = kwargs.pop("torch_dtype", None)
572
+
573
+ use_safetensors = kwargs.pop("use_safetensors", None)
574
+
575
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
576
+ from_safetensors = file_extension == "safetensors"
577
+
578
+ if from_safetensors and use_safetensors is False:
579
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
580
+
581
+ # remove huggingface url
582
+ for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
583
+ if pretrained_model_link_or_path.startswith(prefix):
584
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
585
+
586
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
587
+ ckpt_path = Path(pretrained_model_link_or_path)
588
+ if not ckpt_path.is_file():
589
+ # get repo_id and (potentially nested) file path of ckpt in repo
590
+ repo_id = "/".join(ckpt_path.parts[:2])
591
+ file_path = "/".join(ckpt_path.parts[2:])
592
+
593
+ if file_path.startswith("blob/"):
594
+ file_path = file_path[len("blob/") :]
595
+
596
+ if file_path.startswith("main/"):
597
+ file_path = file_path[len("main/") :]
598
+
599
+ pretrained_model_link_or_path = hf_hub_download(
600
+ repo_id,
601
+ filename=file_path,
602
+ cache_dir=cache_dir,
603
+ resume_download=resume_download,
604
+ proxies=proxies,
605
+ local_files_only=local_files_only,
606
+ use_auth_token=use_auth_token,
607
+ revision=revision,
608
+ force_download=force_download,
609
+ )
610
+
611
+ if config_file is None:
612
+ config_url = "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml"
613
+ config_file = BytesIO(requests.get(config_url).content)
614
+
615
+ image_size = image_size or 512
616
+
617
+ controlnet = download_controlnet_from_original_ckpt(
618
+ pretrained_model_link_or_path,
619
+ original_config_file=config_file,
620
+ image_size=image_size,
621
+ extract_ema=extract_ema,
622
+ num_in_channels=num_in_channels,
623
+ upcast_attention=upcast_attention,
624
+ from_safetensors=from_safetensors,
625
+ use_linear_projection=use_linear_projection,
626
+ )
627
+
628
+ if torch_dtype is not None:
629
+ controlnet.to(dtype=torch_dtype)
630
+
631
+ return controlnet