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.
Files changed (238) hide show
  1. diffusers/__init__.py +26 -2
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +13 -8
  4. diffusers/dependency_versions_check.py +0 -1
  5. diffusers/dependency_versions_table.py +5 -5
  6. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  7. diffusers/image_processor.py +463 -51
  8. diffusers/loaders/__init__.py +82 -0
  9. diffusers/loaders/ip_adapter.py +159 -0
  10. diffusers/loaders/lora.py +1553 -0
  11. diffusers/loaders/lora_conversion_utils.py +284 -0
  12. diffusers/loaders/single_file.py +637 -0
  13. diffusers/loaders/textual_inversion.py +455 -0
  14. diffusers/loaders/unet.py +828 -0
  15. diffusers/loaders/utils.py +59 -0
  16. diffusers/models/__init__.py +26 -9
  17. diffusers/models/activations.py +9 -6
  18. diffusers/models/attention.py +301 -29
  19. diffusers/models/attention_flax.py +9 -1
  20. diffusers/models/attention_processor.py +378 -6
  21. diffusers/models/autoencoders/__init__.py +5 -0
  22. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
  23. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
  24. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
  25. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
  26. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
  27. diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
  28. diffusers/models/controlnet.py +59 -39
  29. diffusers/models/controlnet_flax.py +19 -18
  30. diffusers/models/downsampling.py +338 -0
  31. diffusers/models/embeddings.py +112 -29
  32. diffusers/models/embeddings_flax.py +2 -0
  33. diffusers/models/lora.py +131 -1
  34. diffusers/models/modeling_flax_utils.py +14 -8
  35. diffusers/models/modeling_outputs.py +17 -0
  36. diffusers/models/modeling_utils.py +37 -29
  37. diffusers/models/normalization.py +110 -4
  38. diffusers/models/resnet.py +299 -652
  39. diffusers/models/transformer_2d.py +22 -5
  40. diffusers/models/transformer_temporal.py +183 -1
  41. diffusers/models/unet_2d_blocks_flax.py +5 -0
  42. diffusers/models/unet_2d_condition.py +46 -0
  43. diffusers/models/unet_2d_condition_flax.py +13 -13
  44. diffusers/models/unet_3d_blocks.py +957 -173
  45. diffusers/models/unet_3d_condition.py +16 -8
  46. diffusers/models/unet_kandinsky3.py +535 -0
  47. diffusers/models/unet_motion_model.py +48 -33
  48. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  49. diffusers/models/upsampling.py +454 -0
  50. diffusers/models/uvit_2d.py +471 -0
  51. diffusers/models/vae_flax.py +7 -0
  52. diffusers/models/vq_model.py +12 -3
  53. diffusers/optimization.py +16 -9
  54. diffusers/pipelines/__init__.py +137 -76
  55. diffusers/pipelines/amused/__init__.py +62 -0
  56. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  57. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  58. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  59. diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
  60. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  61. diffusers/pipelines/auto_pipeline.py +23 -13
  62. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  63. diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
  64. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
  65. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
  66. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
  67. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
  68. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
  69. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  70. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  71. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  72. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  73. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  74. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  75. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  76. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  77. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  78. diffusers/pipelines/deprecated/__init__.py +153 -0
  79. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  80. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
  81. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
  82. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  83. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  84. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  85. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  86. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  87. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  88. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  89. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  90. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  91. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  92. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  93. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
  94. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  95. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  96. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  97. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  98. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  100. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
  101. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
  102. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
  103. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
  104. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
  105. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
  106. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  107. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  108. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  109. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
  110. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  111. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
  112. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
  113. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
  114. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  115. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  116. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  117. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  118. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  119. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  120. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  122. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  123. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  124. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
  125. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
  126. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
  127. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
  128. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  129. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  130. diffusers/pipelines/onnx_utils.py +8 -5
  131. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  132. diffusers/pipelines/pipeline_flax_utils.py +11 -8
  133. diffusers/pipelines/pipeline_utils.py +63 -42
  134. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
  135. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  136. diffusers/pipelines/stable_diffusion/__init__.py +37 -65
  137. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
  138. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  139. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  140. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  141. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
  142. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  143. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  144. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
  145. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
  146. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
  147. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  151. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  152. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
  153. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  154. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
  155. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  156. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
  157. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  158. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  159. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
  160. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  161. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
  162. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  163. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
  164. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  165. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  166. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
  171. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  172. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
  175. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
  179. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
  180. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  181. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  182. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  183. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  184. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  185. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  186. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  187. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
  188. diffusers/schedulers/__init__.py +4 -4
  189. diffusers/schedulers/deprecated/__init__.py +50 -0
  190. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  191. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  192. diffusers/schedulers/scheduling_amused.py +162 -0
  193. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  194. diffusers/schedulers/scheduling_ddim.py +1 -3
  195. diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
  196. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  197. diffusers/schedulers/scheduling_ddpm.py +47 -3
  198. diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
  199. diffusers/schedulers/scheduling_deis_multistep.py +28 -6
  200. diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
  201. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
  202. diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
  203. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
  204. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
  205. diffusers/schedulers/scheduling_euler_discrete.py +102 -16
  206. diffusers/schedulers/scheduling_heun_discrete.py +17 -5
  207. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
  208. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
  209. diffusers/schedulers/scheduling_lcm.py +123 -29
  210. diffusers/schedulers/scheduling_lms_discrete.py +3 -3
  211. diffusers/schedulers/scheduling_pndm.py +1 -3
  212. diffusers/schedulers/scheduling_repaint.py +1 -3
  213. diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
  214. diffusers/schedulers/scheduling_utils.py +3 -1
  215. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  216. diffusers/training_utils.py +1 -1
  217. diffusers/utils/__init__.py +1 -2
  218. diffusers/utils/constants.py +10 -12
  219. diffusers/utils/dummy_pt_objects.py +75 -0
  220. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  221. diffusers/utils/dynamic_modules_utils.py +18 -22
  222. diffusers/utils/export_utils.py +8 -3
  223. diffusers/utils/hub_utils.py +24 -36
  224. diffusers/utils/logging.py +11 -11
  225. diffusers/utils/outputs.py +5 -5
  226. diffusers/utils/peft_utils.py +88 -44
  227. diffusers/utils/state_dict_utils.py +8 -0
  228. diffusers/utils/testing_utils.py +199 -1
  229. diffusers/utils/torch_utils.py +4 -4
  230. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
  231. diffusers-0.25.0.dist-info/RECORD +360 -0
  232. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  233. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  234. diffusers/loaders.py +0 -3336
  235. diffusers-0.23.1.dist-info/RECORD +0 -323
  236. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  237. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  238. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,455 @@
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 typing import Dict, List, Optional, Union
15
+
16
+ import safetensors
17
+ import torch
18
+ from huggingface_hub.utils import validate_hf_hub_args
19
+ from torch import nn
20
+
21
+ from ..utils import _get_model_file, is_accelerate_available, is_transformers_available, logging
22
+
23
+
24
+ if is_transformers_available():
25
+ from transformers import PreTrainedModel, PreTrainedTokenizer
26
+
27
+ if is_accelerate_available():
28
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ TEXT_INVERSION_NAME = "learned_embeds.bin"
33
+ TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
34
+
35
+
36
+ @validate_hf_hub_args
37
+ def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
38
+ cache_dir = kwargs.pop("cache_dir", None)
39
+ force_download = kwargs.pop("force_download", False)
40
+ resume_download = kwargs.pop("resume_download", False)
41
+ proxies = kwargs.pop("proxies", None)
42
+ local_files_only = kwargs.pop("local_files_only", None)
43
+ token = kwargs.pop("token", None)
44
+ revision = kwargs.pop("revision", None)
45
+ subfolder = kwargs.pop("subfolder", None)
46
+ weight_name = kwargs.pop("weight_name", None)
47
+ use_safetensors = kwargs.pop("use_safetensors", None)
48
+
49
+ allow_pickle = False
50
+ if use_safetensors is None:
51
+ use_safetensors = True
52
+ allow_pickle = True
53
+
54
+ user_agent = {
55
+ "file_type": "text_inversion",
56
+ "framework": "pytorch",
57
+ }
58
+ state_dicts = []
59
+ for pretrained_model_name_or_path in pretrained_model_name_or_paths:
60
+ if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
61
+ # 3.1. Load textual inversion file
62
+ model_file = None
63
+
64
+ # Let's first try to load .safetensors weights
65
+ if (use_safetensors and weight_name is None) or (
66
+ weight_name is not None and weight_name.endswith(".safetensors")
67
+ ):
68
+ try:
69
+ model_file = _get_model_file(
70
+ pretrained_model_name_or_path,
71
+ weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
72
+ cache_dir=cache_dir,
73
+ force_download=force_download,
74
+ resume_download=resume_download,
75
+ proxies=proxies,
76
+ local_files_only=local_files_only,
77
+ token=token,
78
+ revision=revision,
79
+ subfolder=subfolder,
80
+ user_agent=user_agent,
81
+ )
82
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
83
+ except Exception as e:
84
+ if not allow_pickle:
85
+ raise e
86
+
87
+ model_file = None
88
+
89
+ if model_file is None:
90
+ model_file = _get_model_file(
91
+ pretrained_model_name_or_path,
92
+ weights_name=weight_name or TEXT_INVERSION_NAME,
93
+ cache_dir=cache_dir,
94
+ force_download=force_download,
95
+ resume_download=resume_download,
96
+ proxies=proxies,
97
+ local_files_only=local_files_only,
98
+ token=token,
99
+ revision=revision,
100
+ subfolder=subfolder,
101
+ user_agent=user_agent,
102
+ )
103
+ state_dict = torch.load(model_file, map_location="cpu")
104
+ else:
105
+ state_dict = pretrained_model_name_or_path
106
+
107
+ state_dicts.append(state_dict)
108
+
109
+ return state_dicts
110
+
111
+
112
+ class TextualInversionLoaderMixin:
113
+ r"""
114
+ Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
115
+ """
116
+
117
+ def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
118
+ r"""
119
+ Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
120
+ be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
121
+ inversion token or if the textual inversion token is a single vector, the input prompt is returned.
122
+
123
+ Parameters:
124
+ prompt (`str` or list of `str`):
125
+ The prompt or prompts to guide the image generation.
126
+ tokenizer (`PreTrainedTokenizer`):
127
+ The tokenizer responsible for encoding the prompt into input tokens.
128
+
129
+ Returns:
130
+ `str` or list of `str`: The converted prompt
131
+ """
132
+ if not isinstance(prompt, List):
133
+ prompts = [prompt]
134
+ else:
135
+ prompts = prompt
136
+
137
+ prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
138
+
139
+ if not isinstance(prompt, List):
140
+ return prompts[0]
141
+
142
+ return prompts
143
+
144
+ def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
145
+ r"""
146
+ Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
147
+ to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
148
+ is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
149
+ inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
150
+
151
+ Parameters:
152
+ prompt (`str`):
153
+ The prompt to guide the image generation.
154
+ tokenizer (`PreTrainedTokenizer`):
155
+ The tokenizer responsible for encoding the prompt into input tokens.
156
+
157
+ Returns:
158
+ `str`: The converted prompt
159
+ """
160
+ tokens = tokenizer.tokenize(prompt)
161
+ unique_tokens = set(tokens)
162
+ for token in unique_tokens:
163
+ if token in tokenizer.added_tokens_encoder:
164
+ replacement = token
165
+ i = 1
166
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
167
+ replacement += f" {token}_{i}"
168
+ i += 1
169
+
170
+ prompt = prompt.replace(token, replacement)
171
+
172
+ return prompt
173
+
174
+ def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
175
+ if tokenizer is None:
176
+ raise ValueError(
177
+ f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
178
+ f" `{self.load_textual_inversion.__name__}`"
179
+ )
180
+
181
+ if text_encoder is None:
182
+ raise ValueError(
183
+ f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
184
+ f" `{self.load_textual_inversion.__name__}`"
185
+ )
186
+
187
+ if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
188
+ raise ValueError(
189
+ f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
190
+ f"Make sure both lists have the same length."
191
+ )
192
+
193
+ valid_tokens = [t for t in tokens if t is not None]
194
+ if len(set(valid_tokens)) < len(valid_tokens):
195
+ raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
196
+
197
+ @staticmethod
198
+ def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
199
+ all_tokens = []
200
+ all_embeddings = []
201
+ for state_dict, token in zip(state_dicts, tokens):
202
+ if isinstance(state_dict, torch.Tensor):
203
+ if token is None:
204
+ raise ValueError(
205
+ "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=...`."
206
+ )
207
+ loaded_token = token
208
+ embedding = state_dict
209
+ elif len(state_dict) == 1:
210
+ # diffusers
211
+ loaded_token, embedding = next(iter(state_dict.items()))
212
+ elif "string_to_param" in state_dict:
213
+ # A1111
214
+ loaded_token = state_dict["name"]
215
+ embedding = state_dict["string_to_param"]["*"]
216
+ else:
217
+ raise ValueError(
218
+ f"Loaded state dictonary is incorrect: {state_dict}. \n\n"
219
+ "Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
220
+ " input key."
221
+ )
222
+
223
+ if token is not None and loaded_token != token:
224
+ logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
225
+ else:
226
+ token = loaded_token
227
+
228
+ if token in tokenizer.get_vocab():
229
+ raise ValueError(
230
+ f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
231
+ )
232
+
233
+ all_tokens.append(token)
234
+ all_embeddings.append(embedding)
235
+
236
+ return all_tokens, all_embeddings
237
+
238
+ @staticmethod
239
+ def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
240
+ all_tokens = []
241
+ all_embeddings = []
242
+
243
+ for embedding, token in zip(embeddings, tokens):
244
+ if f"{token}_1" in tokenizer.get_vocab():
245
+ multi_vector_tokens = [token]
246
+ i = 1
247
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
248
+ multi_vector_tokens.append(f"{token}_{i}")
249
+ i += 1
250
+
251
+ raise ValueError(
252
+ 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."
253
+ )
254
+
255
+ is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
256
+ if is_multi_vector:
257
+ all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
258
+ all_embeddings += [e for e in embedding] # noqa: C416
259
+ else:
260
+ all_tokens += [token]
261
+ all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
262
+
263
+ return all_tokens, all_embeddings
264
+
265
+ @validate_hf_hub_args
266
+ def load_textual_inversion(
267
+ self,
268
+ pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
269
+ token: Optional[Union[str, List[str]]] = None,
270
+ tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
271
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
272
+ **kwargs,
273
+ ):
274
+ r"""
275
+ Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
276
+ Automatic1111 formats are supported).
277
+
278
+ Parameters:
279
+ pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
280
+ Can be either one of the following or a list of them:
281
+
282
+ - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
283
+ pretrained model hosted on the Hub.
284
+ - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
285
+ inversion weights.
286
+ - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
287
+ - A [torch state
288
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
289
+
290
+ token (`str` or `List[str]`, *optional*):
291
+ Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
292
+ list, then `token` must also be a list of equal length.
293
+ text_encoder ([`~transformers.CLIPTextModel`], *optional*):
294
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
295
+ If not specified, function will take self.tokenizer.
296
+ tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
297
+ A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
298
+ weight_name (`str`, *optional*):
299
+ Name of a custom weight file. This should be used when:
300
+
301
+ - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
302
+ name such as `text_inv.bin`.
303
+ - The saved textual inversion file is in the Automatic1111 format.
304
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
305
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
306
+ is not used.
307
+ force_download (`bool`, *optional*, defaults to `False`):
308
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
309
+ cached versions if they exist.
310
+ resume_download (`bool`, *optional*, defaults to `False`):
311
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
312
+ incompletely downloaded files are deleted.
313
+ proxies (`Dict[str, str]`, *optional*):
314
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
315
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
316
+ local_files_only (`bool`, *optional*, defaults to `False`):
317
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
318
+ won't be downloaded from the Hub.
319
+ token (`str` or *bool*, *optional*):
320
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
321
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
322
+ revision (`str`, *optional*, defaults to `"main"`):
323
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
324
+ allowed by Git.
325
+ subfolder (`str`, *optional*, defaults to `""`):
326
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
327
+ mirror (`str`, *optional*):
328
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
329
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
330
+ information.
331
+
332
+ Example:
333
+
334
+ To load a Textual Inversion embedding vector in 🤗 Diffusers format:
335
+
336
+ ```py
337
+ from diffusers import StableDiffusionPipeline
338
+ import torch
339
+
340
+ model_id = "runwayml/stable-diffusion-v1-5"
341
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
342
+
343
+ pipe.load_textual_inversion("sd-concepts-library/cat-toy")
344
+
345
+ prompt = "A <cat-toy> backpack"
346
+
347
+ image = pipe(prompt, num_inference_steps=50).images[0]
348
+ image.save("cat-backpack.png")
349
+ ```
350
+
351
+ To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
352
+ (for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
353
+ locally:
354
+
355
+ ```py
356
+ from diffusers import StableDiffusionPipeline
357
+ import torch
358
+
359
+ model_id = "runwayml/stable-diffusion-v1-5"
360
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
361
+
362
+ pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
363
+
364
+ 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."
365
+
366
+ image = pipe(prompt, num_inference_steps=50).images[0]
367
+ image.save("character.png")
368
+ ```
369
+
370
+ """
371
+ # 1. Set correct tokenizer and text encoder
372
+ tokenizer = tokenizer or getattr(self, "tokenizer", None)
373
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
374
+
375
+ # 2. Normalize inputs
376
+ pretrained_model_name_or_paths = (
377
+ [pretrained_model_name_or_path]
378
+ if not isinstance(pretrained_model_name_or_path, list)
379
+ else pretrained_model_name_or_path
380
+ )
381
+ tokens = [token] if not isinstance(token, list) else token
382
+ if tokens[0] is None:
383
+ tokens = tokens * len(pretrained_model_name_or_paths)
384
+
385
+ # 3. Check inputs
386
+ self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
387
+
388
+ # 4. Load state dicts of textual embeddings
389
+ state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
390
+
391
+ # 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
392
+ if len(tokens) > 1 and len(state_dicts) == 1:
393
+ if isinstance(state_dicts[0], torch.Tensor):
394
+ state_dicts = list(state_dicts[0])
395
+ if len(tokens) != len(state_dicts):
396
+ raise ValueError(
397
+ f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
398
+ f"Make sure both have the same length."
399
+ )
400
+
401
+ # 4. Retrieve tokens and embeddings
402
+ tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
403
+
404
+ # 5. Extend tokens and embeddings for multi vector
405
+ tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
406
+
407
+ # 6. Make sure all embeddings have the correct size
408
+ expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
409
+ if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
410
+ raise ValueError(
411
+ "Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
412
+ "to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
413
+ )
414
+
415
+ # 7. Now we can be sure that loading the embedding matrix works
416
+ # < Unsafe code:
417
+
418
+ # 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
419
+ is_model_cpu_offload = False
420
+ is_sequential_cpu_offload = False
421
+ for _, component in self.components.items():
422
+ if isinstance(component, nn.Module):
423
+ if hasattr(component, "_hf_hook"):
424
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
425
+ is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
426
+ logger.info(
427
+ "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."
428
+ )
429
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
430
+
431
+ # 7.2 save expected device and dtype
432
+ device = text_encoder.device
433
+ dtype = text_encoder.dtype
434
+
435
+ # 7.3 Increase token embedding matrix
436
+ text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
437
+ input_embeddings = text_encoder.get_input_embeddings().weight
438
+
439
+ # 7.4 Load token and embedding
440
+ for token, embedding in zip(tokens, embeddings):
441
+ # add tokens and get ids
442
+ tokenizer.add_tokens(token)
443
+ token_id = tokenizer.convert_tokens_to_ids(token)
444
+ input_embeddings.data[token_id] = embedding
445
+ logger.info(f"Loaded textual inversion embedding for {token}.")
446
+
447
+ input_embeddings.to(dtype=dtype, device=device)
448
+
449
+ # 7.5 Offload the model again
450
+ if is_model_cpu_offload:
451
+ self.enable_model_cpu_offload()
452
+ elif is_sequential_cpu_offload:
453
+ self.enable_sequential_cpu_offload()
454
+
455
+ # / Unsafe Code >