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,328 @@
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
+
15
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
19
+
20
+ from ...image_processor import VaeImageProcessor
21
+ from ...models import UVit2DModel, VQModel
22
+ from ...schedulers import AmusedScheduler
23
+ from ...utils import replace_example_docstring
24
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
25
+
26
+
27
+ EXAMPLE_DOC_STRING = """
28
+ Examples:
29
+ ```py
30
+ >>> import torch
31
+ >>> from diffusers import AmusedPipeline
32
+
33
+ >>> pipe = AmusedPipeline.from_pretrained(
34
+ ... "amused/amused-512", variant="fp16", torch_dtype=torch.float16
35
+ ... )
36
+ >>> pipe = pipe.to("cuda")
37
+
38
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
39
+ >>> image = pipe(prompt).images[0]
40
+ ```
41
+ """
42
+
43
+
44
+ class AmusedPipeline(DiffusionPipeline):
45
+ image_processor: VaeImageProcessor
46
+ vqvae: VQModel
47
+ tokenizer: CLIPTokenizer
48
+ text_encoder: CLIPTextModelWithProjection
49
+ transformer: UVit2DModel
50
+ scheduler: AmusedScheduler
51
+
52
+ model_cpu_offload_seq = "text_encoder->transformer->vqvae"
53
+
54
+ def __init__(
55
+ self,
56
+ vqvae: VQModel,
57
+ tokenizer: CLIPTokenizer,
58
+ text_encoder: CLIPTextModelWithProjection,
59
+ transformer: UVit2DModel,
60
+ scheduler: AmusedScheduler,
61
+ ):
62
+ super().__init__()
63
+
64
+ self.register_modules(
65
+ vqvae=vqvae,
66
+ tokenizer=tokenizer,
67
+ text_encoder=text_encoder,
68
+ transformer=transformer,
69
+ scheduler=scheduler,
70
+ )
71
+ self.vae_scale_factor = 2 ** (len(self.vqvae.config.block_out_channels) - 1)
72
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_normalize=False)
73
+
74
+ @torch.no_grad()
75
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
76
+ def __call__(
77
+ self,
78
+ prompt: Optional[Union[List[str], str]] = None,
79
+ height: Optional[int] = None,
80
+ width: Optional[int] = None,
81
+ num_inference_steps: int = 12,
82
+ guidance_scale: float = 10.0,
83
+ negative_prompt: Optional[Union[str, List[str]]] = None,
84
+ num_images_per_prompt: Optional[int] = 1,
85
+ generator: Optional[torch.Generator] = None,
86
+ latents: Optional[torch.IntTensor] = None,
87
+ prompt_embeds: Optional[torch.Tensor] = None,
88
+ encoder_hidden_states: Optional[torch.Tensor] = None,
89
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
90
+ negative_encoder_hidden_states: Optional[torch.Tensor] = None,
91
+ output_type="pil",
92
+ return_dict: bool = True,
93
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
94
+ callback_steps: int = 1,
95
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
96
+ micro_conditioning_aesthetic_score: int = 6,
97
+ micro_conditioning_crop_coord: Tuple[int, int] = (0, 0),
98
+ temperature: Union[int, Tuple[int, int], List[int]] = (2, 0),
99
+ ):
100
+ """
101
+ The call function to the pipeline for generation.
102
+
103
+ Args:
104
+ prompt (`str` or `List[str]`, *optional*):
105
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
106
+ height (`int`, *optional*, defaults to `self.transformer.config.sample_size * self.vae_scale_factor`):
107
+ The height in pixels of the generated image.
108
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
109
+ The width in pixels of the generated image.
110
+ num_inference_steps (`int`, *optional*, defaults to 16):
111
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
112
+ expense of slower inference.
113
+ guidance_scale (`float`, *optional*, defaults to 10.0):
114
+ A higher guidance scale value encourages the model to generate images closely linked to the text
115
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
116
+ negative_prompt (`str` or `List[str]`, *optional*):
117
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
118
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
119
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
120
+ The number of images to generate per prompt.
121
+ generator (`torch.Generator`, *optional*):
122
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
123
+ generation deterministic.
124
+ latents (`torch.IntTensor`, *optional*):
125
+ Pre-generated tokens representing latent vectors in `self.vqvae`, to be used as inputs for image
126
+ gneration. If not provided, the starting latents will be completely masked.
127
+ prompt_embeds (`torch.FloatTensor`, *optional*):
128
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
129
+ provided, text embeddings are generated from the `prompt` input argument. A single vector from the
130
+ pooled and projected final hidden states.
131
+ encoder_hidden_states (`torch.FloatTensor`, *optional*):
132
+ Pre-generated penultimate hidden states from the text encoder providing additional text conditioning.
133
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
134
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
135
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
136
+ negative_encoder_hidden_states (`torch.FloatTensor`, *optional*):
137
+ Analogous to `encoder_hidden_states` for the positive prompt.
138
+ output_type (`str`, *optional*, defaults to `"pil"`):
139
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
140
+ return_dict (`bool`, *optional*, defaults to `True`):
141
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
142
+ plain tuple.
143
+ callback (`Callable`, *optional*):
144
+ A function that calls every `callback_steps` steps during inference. The function is called with the
145
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
146
+ callback_steps (`int`, *optional*, defaults to 1):
147
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
148
+ every step.
149
+ cross_attention_kwargs (`dict`, *optional*):
150
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
151
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
152
+ micro_conditioning_aesthetic_score (`int`, *optional*, defaults to 6):
153
+ The targeted aesthetic score according to the laion aesthetic classifier. See https://laion.ai/blog/laion-aesthetics/
154
+ and the micro-conditioning section of https://arxiv.org/abs/2307.01952.
155
+ micro_conditioning_crop_coord (`Tuple[int]`, *optional*, defaults to (0, 0)):
156
+ The targeted height, width crop coordinates. See the micro-conditioning section of https://arxiv.org/abs/2307.01952.
157
+ temperature (`Union[int, Tuple[int, int], List[int]]`, *optional*, defaults to (2, 0)):
158
+ Configures the temperature scheduler on `self.scheduler` see `AmusedScheduler#set_timesteps`.
159
+
160
+ Examples:
161
+
162
+ Returns:
163
+ [`~pipelines.pipeline_utils.ImagePipelineOutput`] or `tuple`:
164
+ If `return_dict` is `True`, [`~pipelines.pipeline_utils.ImagePipelineOutput`] is returned, otherwise a
165
+ `tuple` is returned where the first element is a list with the generated images.
166
+ """
167
+ if (prompt_embeds is not None and encoder_hidden_states is None) or (
168
+ prompt_embeds is None and encoder_hidden_states is not None
169
+ ):
170
+ raise ValueError("pass either both `prompt_embeds` and `encoder_hidden_states` or neither")
171
+
172
+ if (negative_prompt_embeds is not None and negative_encoder_hidden_states is None) or (
173
+ negative_prompt_embeds is None and negative_encoder_hidden_states is not None
174
+ ):
175
+ raise ValueError(
176
+ "pass either both `negatve_prompt_embeds` and `negative_encoder_hidden_states` or neither"
177
+ )
178
+
179
+ if (prompt is None and prompt_embeds is None) or (prompt is not None and prompt_embeds is not None):
180
+ raise ValueError("pass only one of `prompt` or `prompt_embeds`")
181
+
182
+ if isinstance(prompt, str):
183
+ prompt = [prompt]
184
+
185
+ if prompt is not None:
186
+ batch_size = len(prompt)
187
+ else:
188
+ batch_size = prompt_embeds.shape[0]
189
+
190
+ batch_size = batch_size * num_images_per_prompt
191
+
192
+ if height is None:
193
+ height = self.transformer.config.sample_size * self.vae_scale_factor
194
+
195
+ if width is None:
196
+ width = self.transformer.config.sample_size * self.vae_scale_factor
197
+
198
+ if prompt_embeds is None:
199
+ input_ids = self.tokenizer(
200
+ prompt,
201
+ return_tensors="pt",
202
+ padding="max_length",
203
+ truncation=True,
204
+ max_length=self.tokenizer.model_max_length,
205
+ ).input_ids.to(self._execution_device)
206
+
207
+ outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
208
+ prompt_embeds = outputs.text_embeds
209
+ encoder_hidden_states = outputs.hidden_states[-2]
210
+
211
+ prompt_embeds = prompt_embeds.repeat(num_images_per_prompt, 1)
212
+ encoder_hidden_states = encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
213
+
214
+ if guidance_scale > 1.0:
215
+ if negative_prompt_embeds is None:
216
+ if negative_prompt is None:
217
+ negative_prompt = [""] * len(prompt)
218
+
219
+ if isinstance(negative_prompt, str):
220
+ negative_prompt = [negative_prompt]
221
+
222
+ input_ids = self.tokenizer(
223
+ negative_prompt,
224
+ return_tensors="pt",
225
+ padding="max_length",
226
+ truncation=True,
227
+ max_length=self.tokenizer.model_max_length,
228
+ ).input_ids.to(self._execution_device)
229
+
230
+ outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
231
+ negative_prompt_embeds = outputs.text_embeds
232
+ negative_encoder_hidden_states = outputs.hidden_states[-2]
233
+
234
+ negative_prompt_embeds = negative_prompt_embeds.repeat(num_images_per_prompt, 1)
235
+ negative_encoder_hidden_states = negative_encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
236
+
237
+ prompt_embeds = torch.concat([negative_prompt_embeds, prompt_embeds])
238
+ encoder_hidden_states = torch.concat([negative_encoder_hidden_states, encoder_hidden_states])
239
+
240
+ # Note that the micro conditionings _do_ flip the order of width, height for the original size
241
+ # and the crop coordinates. This is how it was done in the original code base
242
+ micro_conds = torch.tensor(
243
+ [
244
+ width,
245
+ height,
246
+ micro_conditioning_crop_coord[0],
247
+ micro_conditioning_crop_coord[1],
248
+ micro_conditioning_aesthetic_score,
249
+ ],
250
+ device=self._execution_device,
251
+ dtype=encoder_hidden_states.dtype,
252
+ )
253
+ micro_conds = micro_conds.unsqueeze(0)
254
+ micro_conds = micro_conds.expand(2 * batch_size if guidance_scale > 1.0 else batch_size, -1)
255
+
256
+ shape = (batch_size, height // self.vae_scale_factor, width // self.vae_scale_factor)
257
+
258
+ if latents is None:
259
+ latents = torch.full(
260
+ shape, self.scheduler.config.mask_token_id, dtype=torch.long, device=self._execution_device
261
+ )
262
+
263
+ self.scheduler.set_timesteps(num_inference_steps, temperature, self._execution_device)
264
+
265
+ num_warmup_steps = len(self.scheduler.timesteps) - num_inference_steps * self.scheduler.order
266
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
267
+ for i, timestep in enumerate(self.scheduler.timesteps):
268
+ if guidance_scale > 1.0:
269
+ model_input = torch.cat([latents] * 2)
270
+ else:
271
+ model_input = latents
272
+
273
+ model_output = self.transformer(
274
+ model_input,
275
+ micro_conds=micro_conds,
276
+ pooled_text_emb=prompt_embeds,
277
+ encoder_hidden_states=encoder_hidden_states,
278
+ cross_attention_kwargs=cross_attention_kwargs,
279
+ )
280
+
281
+ if guidance_scale > 1.0:
282
+ uncond_logits, cond_logits = model_output.chunk(2)
283
+ model_output = uncond_logits + guidance_scale * (cond_logits - uncond_logits)
284
+
285
+ latents = self.scheduler.step(
286
+ model_output=model_output,
287
+ timestep=timestep,
288
+ sample=latents,
289
+ generator=generator,
290
+ ).prev_sample
291
+
292
+ if i == len(self.scheduler.timesteps) - 1 or (
293
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
294
+ ):
295
+ progress_bar.update()
296
+ if callback is not None and i % callback_steps == 0:
297
+ step_idx = i // getattr(self.scheduler, "order", 1)
298
+ callback(step_idx, timestep, latents)
299
+
300
+ if output_type == "latent":
301
+ output = latents
302
+ else:
303
+ needs_upcasting = self.vqvae.dtype == torch.float16 and self.vqvae.config.force_upcast
304
+
305
+ if needs_upcasting:
306
+ self.vqvae.float()
307
+
308
+ output = self.vqvae.decode(
309
+ latents,
310
+ force_not_quantize=True,
311
+ shape=(
312
+ batch_size,
313
+ height // self.vae_scale_factor,
314
+ width // self.vae_scale_factor,
315
+ self.vqvae.config.latent_channels,
316
+ ),
317
+ ).sample.clip(0, 1)
318
+ output = self.image_processor.postprocess(output, output_type)
319
+
320
+ if needs_upcasting:
321
+ self.vqvae.half()
322
+
323
+ self.maybe_free_model_hooks()
324
+
325
+ if not return_dict:
326
+ return (output,)
327
+
328
+ return ImagePipelineOutput(output)
@@ -0,0 +1,347 @@
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
+
15
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
19
+
20
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
21
+ from ...models import UVit2DModel, VQModel
22
+ from ...schedulers import AmusedScheduler
23
+ from ...utils import replace_example_docstring
24
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
25
+
26
+
27
+ EXAMPLE_DOC_STRING = """
28
+ Examples:
29
+ ```py
30
+ >>> import torch
31
+ >>> from diffusers import AmusedImg2ImgPipeline
32
+ >>> from diffusers.utils import load_image
33
+
34
+ >>> pipe = AmusedImg2ImgPipeline.from_pretrained(
35
+ ... "amused/amused-512", variant="fp16", torch_dtype=torch.float16
36
+ ... )
37
+ >>> pipe = pipe.to("cuda")
38
+
39
+ >>> prompt = "winter mountains"
40
+ >>> input_image = (
41
+ ... load_image(
42
+ ... "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains.jpg"
43
+ ... )
44
+ ... .resize((512, 512))
45
+ ... .convert("RGB")
46
+ ... )
47
+ >>> image = pipe(prompt, input_image).images[0]
48
+ ```
49
+ """
50
+
51
+
52
+ class AmusedImg2ImgPipeline(DiffusionPipeline):
53
+ image_processor: VaeImageProcessor
54
+ vqvae: VQModel
55
+ tokenizer: CLIPTokenizer
56
+ text_encoder: CLIPTextModelWithProjection
57
+ transformer: UVit2DModel
58
+ scheduler: AmusedScheduler
59
+
60
+ model_cpu_offload_seq = "text_encoder->transformer->vqvae"
61
+
62
+ # TODO - when calling self.vqvae.quantize, it uses self.vqvae.quantize.embedding.weight before
63
+ # the forward method of self.vqvae.quantize, so the hook doesn't get called to move the parameter
64
+ # off the meta device. There should be a way to fix this instead of just not offloading it
65
+ _exclude_from_cpu_offload = ["vqvae"]
66
+
67
+ def __init__(
68
+ self,
69
+ vqvae: VQModel,
70
+ tokenizer: CLIPTokenizer,
71
+ text_encoder: CLIPTextModelWithProjection,
72
+ transformer: UVit2DModel,
73
+ scheduler: AmusedScheduler,
74
+ ):
75
+ super().__init__()
76
+
77
+ self.register_modules(
78
+ vqvae=vqvae,
79
+ tokenizer=tokenizer,
80
+ text_encoder=text_encoder,
81
+ transformer=transformer,
82
+ scheduler=scheduler,
83
+ )
84
+ self.vae_scale_factor = 2 ** (len(self.vqvae.config.block_out_channels) - 1)
85
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_normalize=False)
86
+
87
+ @torch.no_grad()
88
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
89
+ def __call__(
90
+ self,
91
+ prompt: Optional[Union[List[str], str]] = None,
92
+ image: PipelineImageInput = None,
93
+ strength: float = 0.5,
94
+ num_inference_steps: int = 12,
95
+ guidance_scale: float = 10.0,
96
+ negative_prompt: Optional[Union[str, List[str]]] = None,
97
+ num_images_per_prompt: Optional[int] = 1,
98
+ generator: Optional[torch.Generator] = None,
99
+ prompt_embeds: Optional[torch.Tensor] = None,
100
+ encoder_hidden_states: Optional[torch.Tensor] = None,
101
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
102
+ negative_encoder_hidden_states: Optional[torch.Tensor] = None,
103
+ output_type="pil",
104
+ return_dict: bool = True,
105
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
106
+ callback_steps: int = 1,
107
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
108
+ micro_conditioning_aesthetic_score: int = 6,
109
+ micro_conditioning_crop_coord: Tuple[int, int] = (0, 0),
110
+ temperature: Union[int, Tuple[int, int], List[int]] = (2, 0),
111
+ ):
112
+ """
113
+ The call function to the pipeline for generation.
114
+
115
+ Args:
116
+ prompt (`str` or `List[str]`, *optional*):
117
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
118
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
119
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
120
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
121
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
122
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
123
+ latents as `image`, but if passing latents directly it is not encoded again.
124
+ strength (`float`, *optional*, defaults to 0.5):
125
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
126
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
127
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
128
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
129
+ essentially ignores `image`.
130
+ num_inference_steps (`int`, *optional*, defaults to 16):
131
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
132
+ expense of slower inference.
133
+ guidance_scale (`float`, *optional*, defaults to 10.0):
134
+ A higher guidance scale value encourages the model to generate images closely linked to the text
135
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
136
+ negative_prompt (`str` or `List[str]`, *optional*):
137
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
138
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
139
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
140
+ The number of images to generate per prompt.
141
+ generator (`torch.Generator`, *optional*):
142
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
143
+ generation deterministic.
144
+ prompt_embeds (`torch.FloatTensor`, *optional*):
145
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
146
+ provided, text embeddings are generated from the `prompt` input argument. A single vector from the
147
+ pooled and projected final hidden states.
148
+ encoder_hidden_states (`torch.FloatTensor`, *optional*):
149
+ Pre-generated penultimate hidden states from the text encoder providing additional text conditioning.
150
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
151
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
152
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
153
+ negative_encoder_hidden_states (`torch.FloatTensor`, *optional*):
154
+ Analogous to `encoder_hidden_states` for the positive prompt.
155
+ output_type (`str`, *optional*, defaults to `"pil"`):
156
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
157
+ return_dict (`bool`, *optional*, defaults to `True`):
158
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
159
+ plain tuple.
160
+ callback (`Callable`, *optional*):
161
+ A function that calls every `callback_steps` steps during inference. The function is called with the
162
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
163
+ callback_steps (`int`, *optional*, defaults to 1):
164
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
165
+ every step.
166
+ cross_attention_kwargs (`dict`, *optional*):
167
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
168
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
169
+ micro_conditioning_aesthetic_score (`int`, *optional*, defaults to 6):
170
+ The targeted aesthetic score according to the laion aesthetic classifier. See https://laion.ai/blog/laion-aesthetics/
171
+ and the micro-conditioning section of https://arxiv.org/abs/2307.01952.
172
+ micro_conditioning_crop_coord (`Tuple[int]`, *optional*, defaults to (0, 0)):
173
+ The targeted height, width crop coordinates. See the micro-conditioning section of https://arxiv.org/abs/2307.01952.
174
+ temperature (`Union[int, Tuple[int, int], List[int]]`, *optional*, defaults to (2, 0)):
175
+ Configures the temperature scheduler on `self.scheduler` see `AmusedScheduler#set_timesteps`.
176
+
177
+ Examples:
178
+
179
+ Returns:
180
+ [`~pipelines.pipeline_utils.ImagePipelineOutput`] or `tuple`:
181
+ If `return_dict` is `True`, [`~pipelines.pipeline_utils.ImagePipelineOutput`] is returned, otherwise a
182
+ `tuple` is returned where the first element is a list with the generated images.
183
+ """
184
+
185
+ if (prompt_embeds is not None and encoder_hidden_states is None) or (
186
+ prompt_embeds is None and encoder_hidden_states is not None
187
+ ):
188
+ raise ValueError("pass either both `prompt_embeds` and `encoder_hidden_states` or neither")
189
+
190
+ if (negative_prompt_embeds is not None and negative_encoder_hidden_states is None) or (
191
+ negative_prompt_embeds is None and negative_encoder_hidden_states is not None
192
+ ):
193
+ raise ValueError(
194
+ "pass either both `negatve_prompt_embeds` and `negative_encoder_hidden_states` or neither"
195
+ )
196
+
197
+ if (prompt is None and prompt_embeds is None) or (prompt is not None and prompt_embeds is not None):
198
+ raise ValueError("pass only one of `prompt` or `prompt_embeds`")
199
+
200
+ if isinstance(prompt, str):
201
+ prompt = [prompt]
202
+
203
+ if prompt is not None:
204
+ batch_size = len(prompt)
205
+ else:
206
+ batch_size = prompt_embeds.shape[0]
207
+
208
+ batch_size = batch_size * num_images_per_prompt
209
+
210
+ if prompt_embeds is None:
211
+ input_ids = self.tokenizer(
212
+ prompt,
213
+ return_tensors="pt",
214
+ padding="max_length",
215
+ truncation=True,
216
+ max_length=self.tokenizer.model_max_length,
217
+ ).input_ids.to(self._execution_device)
218
+
219
+ outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
220
+ prompt_embeds = outputs.text_embeds
221
+ encoder_hidden_states = outputs.hidden_states[-2]
222
+
223
+ prompt_embeds = prompt_embeds.repeat(num_images_per_prompt, 1)
224
+ encoder_hidden_states = encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
225
+
226
+ if guidance_scale > 1.0:
227
+ if negative_prompt_embeds is None:
228
+ if negative_prompt is None:
229
+ negative_prompt = [""] * len(prompt)
230
+
231
+ if isinstance(negative_prompt, str):
232
+ negative_prompt = [negative_prompt]
233
+
234
+ input_ids = self.tokenizer(
235
+ negative_prompt,
236
+ return_tensors="pt",
237
+ padding="max_length",
238
+ truncation=True,
239
+ max_length=self.tokenizer.model_max_length,
240
+ ).input_ids.to(self._execution_device)
241
+
242
+ outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
243
+ negative_prompt_embeds = outputs.text_embeds
244
+ negative_encoder_hidden_states = outputs.hidden_states[-2]
245
+
246
+ negative_prompt_embeds = negative_prompt_embeds.repeat(num_images_per_prompt, 1)
247
+ negative_encoder_hidden_states = negative_encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
248
+
249
+ prompt_embeds = torch.concat([negative_prompt_embeds, prompt_embeds])
250
+ encoder_hidden_states = torch.concat([negative_encoder_hidden_states, encoder_hidden_states])
251
+
252
+ image = self.image_processor.preprocess(image)
253
+
254
+ height, width = image.shape[-2:]
255
+
256
+ # Note that the micro conditionings _do_ flip the order of width, height for the original size
257
+ # and the crop coordinates. This is how it was done in the original code base
258
+ micro_conds = torch.tensor(
259
+ [
260
+ width,
261
+ height,
262
+ micro_conditioning_crop_coord[0],
263
+ micro_conditioning_crop_coord[1],
264
+ micro_conditioning_aesthetic_score,
265
+ ],
266
+ device=self._execution_device,
267
+ dtype=encoder_hidden_states.dtype,
268
+ )
269
+
270
+ micro_conds = micro_conds.unsqueeze(0)
271
+ micro_conds = micro_conds.expand(2 * batch_size if guidance_scale > 1.0 else batch_size, -1)
272
+
273
+ self.scheduler.set_timesteps(num_inference_steps, temperature, self._execution_device)
274
+ num_inference_steps = int(len(self.scheduler.timesteps) * strength)
275
+ start_timestep_idx = len(self.scheduler.timesteps) - num_inference_steps
276
+
277
+ needs_upcasting = self.vqvae.dtype == torch.float16 and self.vqvae.config.force_upcast
278
+
279
+ if needs_upcasting:
280
+ self.vqvae.float()
281
+
282
+ latents = self.vqvae.encode(image.to(dtype=self.vqvae.dtype, device=self._execution_device)).latents
283
+ latents_bsz, channels, latents_height, latents_width = latents.shape
284
+ latents = self.vqvae.quantize(latents)[2][2].reshape(latents_bsz, latents_height, latents_width)
285
+ latents = self.scheduler.add_noise(
286
+ latents, self.scheduler.timesteps[start_timestep_idx - 1], generator=generator
287
+ )
288
+ latents = latents.repeat(num_images_per_prompt, 1, 1)
289
+
290
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
291
+ for i in range(start_timestep_idx, len(self.scheduler.timesteps)):
292
+ timestep = self.scheduler.timesteps[i]
293
+
294
+ if guidance_scale > 1.0:
295
+ model_input = torch.cat([latents] * 2)
296
+ else:
297
+ model_input = latents
298
+
299
+ model_output = self.transformer(
300
+ model_input,
301
+ micro_conds=micro_conds,
302
+ pooled_text_emb=prompt_embeds,
303
+ encoder_hidden_states=encoder_hidden_states,
304
+ cross_attention_kwargs=cross_attention_kwargs,
305
+ )
306
+
307
+ if guidance_scale > 1.0:
308
+ uncond_logits, cond_logits = model_output.chunk(2)
309
+ model_output = uncond_logits + guidance_scale * (cond_logits - uncond_logits)
310
+
311
+ latents = self.scheduler.step(
312
+ model_output=model_output,
313
+ timestep=timestep,
314
+ sample=latents,
315
+ generator=generator,
316
+ ).prev_sample
317
+
318
+ if i == len(self.scheduler.timesteps) - 1 or ((i + 1) % self.scheduler.order == 0):
319
+ progress_bar.update()
320
+ if callback is not None and i % callback_steps == 0:
321
+ step_idx = i // getattr(self.scheduler, "order", 1)
322
+ callback(step_idx, timestep, latents)
323
+
324
+ if output_type == "latent":
325
+ output = latents
326
+ else:
327
+ output = self.vqvae.decode(
328
+ latents,
329
+ force_not_quantize=True,
330
+ shape=(
331
+ batch_size,
332
+ height // self.vae_scale_factor,
333
+ width // self.vae_scale_factor,
334
+ self.vqvae.config.latent_channels,
335
+ ),
336
+ ).sample.clip(0, 1)
337
+ output = self.image_processor.postprocess(output, output_type)
338
+
339
+ if needs_upcasting:
340
+ self.vqvae.half()
341
+
342
+ self.maybe_free_model_hooks()
343
+
344
+ if not return_dict:
345
+ return (output,)
346
+
347
+ return ImagePipelineOutput(output)