diffusers 0.23.0__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 (177) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +1 -14
  4. diffusers/dependency_versions_table.py +5 -4
  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 +11 -6
  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/utils/versions.py +117 -0
  171. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/METADATA +83 -64
  172. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/RECORD +176 -157
  173. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/WHEEL +1 -1
  174. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +1 -0
  175. diffusers/loaders.py +0 -3336
  176. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  177. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -118,6 +118,51 @@ def _preprocess_adapter_image(image, height, width):
118
118
  return image
119
119
 
120
120
 
121
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
122
+ def retrieve_timesteps(
123
+ scheduler,
124
+ num_inference_steps: Optional[int] = None,
125
+ device: Optional[Union[str, torch.device]] = None,
126
+ timesteps: Optional[List[int]] = None,
127
+ **kwargs,
128
+ ):
129
+ """
130
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
131
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
132
+
133
+ Args:
134
+ scheduler (`SchedulerMixin`):
135
+ The scheduler to get timesteps from.
136
+ num_inference_steps (`int`):
137
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
138
+ `timesteps` must be `None`.
139
+ device (`str` or `torch.device`, *optional*):
140
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
141
+ timesteps (`List[int]`, *optional*):
142
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
143
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
144
+ must be `None`.
145
+
146
+ Returns:
147
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
148
+ second element is the number of inference steps.
149
+ """
150
+ if timesteps is not None:
151
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
152
+ if not accepts_timesteps:
153
+ raise ValueError(
154
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
155
+ f" timestep schedules. Please check whether you are using the correct scheduler."
156
+ )
157
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
158
+ timesteps = scheduler.timesteps
159
+ num_inference_steps = len(timesteps)
160
+ else:
161
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
162
+ timesteps = scheduler.timesteps
163
+ return timesteps, num_inference_steps
164
+
165
+
121
166
  class StableDiffusionAdapterPipeline(DiffusionPipeline):
122
167
  r"""
123
168
  Pipeline for text-to-image generation using Stable Diffusion augmented with T2I-Adapter
@@ -152,6 +197,7 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
152
197
  feature_extractor ([`CLIPFeatureExtractor`]):
153
198
  Model that extracts features from generated images to be used as inputs for the `safety_checker`.
154
199
  """
200
+
155
201
  model_cpu_offload_seq = "text_encoder->adapter->unet->vae"
156
202
  _optional_components = ["safety_checker", "feature_extractor"]
157
203
 
@@ -610,6 +656,46 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
610
656
  """Disables the FreeU mechanism if enabled."""
611
657
  self.unet.disable_freeu()
612
658
 
659
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
660
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
661
+ """
662
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
663
+
664
+ Args:
665
+ timesteps (`torch.Tensor`):
666
+ generate embedding vectors at these timesteps
667
+ embedding_dim (`int`, *optional*, defaults to 512):
668
+ dimension of the embeddings to generate
669
+ dtype:
670
+ data type of the generated embeddings
671
+
672
+ Returns:
673
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
674
+ """
675
+ assert len(w.shape) == 1
676
+ w = w * 1000.0
677
+
678
+ half_dim = embedding_dim // 2
679
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
680
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
681
+ emb = w.to(dtype)[:, None] * emb[None, :]
682
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
683
+ if embedding_dim % 2 == 1: # zero pad
684
+ emb = torch.nn.functional.pad(emb, (0, 1))
685
+ assert emb.shape == (w.shape[0], embedding_dim)
686
+ return emb
687
+
688
+ @property
689
+ def guidance_scale(self):
690
+ return self._guidance_scale
691
+
692
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
693
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
694
+ # corresponds to doing no classifier free guidance.
695
+ @property
696
+ def do_classifier_free_guidance(self):
697
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
698
+
613
699
  @torch.no_grad()
614
700
  @replace_example_docstring(EXAMPLE_DOC_STRING)
615
701
  def __call__(
@@ -619,6 +705,7 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
619
705
  height: Optional[int] = None,
620
706
  width: Optional[int] = None,
621
707
  num_inference_steps: int = 50,
708
+ timesteps: List[int] = None,
622
709
  guidance_scale: float = 7.5,
623
710
  negative_prompt: Optional[Union[str, List[str]]] = None,
624
711
  num_images_per_prompt: Optional[int] = 1,
@@ -653,6 +740,10 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
653
740
  num_inference_steps (`int`, *optional*, defaults to 50):
654
741
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
655
742
  expense of slower inference.
743
+ timesteps (`List[int]`, *optional*):
744
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
745
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
746
+ passed will be used. Must be in descending order.
656
747
  guidance_scale (`float`, *optional*, defaults to 7.5):
657
748
  Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
658
749
  `guidance_scale` is defined as `w` of equation 2. of [Imagen
@@ -723,6 +814,8 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
723
814
  prompt, height, width, callback_steps, image, negative_prompt, prompt_embeds, negative_prompt_embeds
724
815
  )
725
816
 
817
+ self._guidance_scale = guidance_scale
818
+
726
819
  if isinstance(self.adapter, MultiAdapter):
727
820
  adapter_input = []
728
821
 
@@ -742,17 +835,12 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
742
835
  else:
743
836
  batch_size = prompt_embeds.shape[0]
744
837
 
745
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
746
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
747
- # corresponds to doing no classifier free guidance.
748
- do_classifier_free_guidance = guidance_scale > 1.0
749
-
750
838
  # 3. Encode input prompt
751
839
  prompt_embeds, negative_prompt_embeds = self.encode_prompt(
752
840
  prompt,
753
841
  device,
754
842
  num_images_per_prompt,
755
- do_classifier_free_guidance,
843
+ self.do_classifier_free_guidance,
756
844
  negative_prompt,
757
845
  prompt_embeds=prompt_embeds,
758
846
  negative_prompt_embeds=negative_prompt_embeds,
@@ -761,12 +849,11 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
761
849
  # For classifier free guidance, we need to do two forward passes.
762
850
  # Here we concatenate the unconditional and text embeddings into a single batch
763
851
  # to avoid doing two forward passes
764
- if do_classifier_free_guidance:
852
+ if self.do_classifier_free_guidance:
765
853
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
766
854
 
767
855
  # 4. Prepare timesteps
768
- self.scheduler.set_timesteps(num_inference_steps, device=device)
769
- timesteps = self.scheduler.timesteps
856
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
770
857
 
771
858
  # 5. Prepare latent variables
772
859
  num_channels_latents = self.unet.config.in_channels
@@ -784,6 +871,14 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
784
871
  # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
785
872
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
786
873
 
874
+ # 6.5 Optionally get Guidance Scale Embedding
875
+ timestep_cond = None
876
+ if self.unet.config.time_cond_proj_dim is not None:
877
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
878
+ timestep_cond = self.get_guidance_scale_embedding(
879
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
880
+ ).to(device=device, dtype=latents.dtype)
881
+
787
882
  # 7. Denoising loop
788
883
  if isinstance(self.adapter, MultiAdapter):
789
884
  adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
@@ -796,7 +891,7 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
796
891
  if num_images_per_prompt > 1:
797
892
  for k, v in enumerate(adapter_state):
798
893
  adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
799
- if do_classifier_free_guidance:
894
+ if self.do_classifier_free_guidance:
800
895
  for k, v in enumerate(adapter_state):
801
896
  adapter_state[k] = torch.cat([v] * 2, dim=0)
802
897
 
@@ -804,7 +899,7 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
804
899
  with self.progress_bar(total=num_inference_steps) as progress_bar:
805
900
  for i, t in enumerate(timesteps):
806
901
  # expand the latents if we are doing classifier free guidance
807
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
902
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
808
903
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
809
904
 
810
905
  # predict the noise residual
@@ -812,13 +907,14 @@ class StableDiffusionAdapterPipeline(DiffusionPipeline):
812
907
  latent_model_input,
813
908
  t,
814
909
  encoder_hidden_states=prompt_embeds,
910
+ timestep_cond=timestep_cond,
815
911
  cross_attention_kwargs=cross_attention_kwargs,
816
912
  down_intrablock_additional_residuals=[state.clone() for state in adapter_state],
817
913
  return_dict=False,
818
914
  )[0]
819
915
 
820
916
  # perform guidance
821
- if do_classifier_free_guidance:
917
+ if self.do_classifier_free_guidance:
822
918
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
823
919
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
824
920
 
@@ -123,6 +123,51 @@ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
123
123
  return noise_cfg
124
124
 
125
125
 
126
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
127
+ def retrieve_timesteps(
128
+ scheduler,
129
+ num_inference_steps: Optional[int] = None,
130
+ device: Optional[Union[str, torch.device]] = None,
131
+ timesteps: Optional[List[int]] = None,
132
+ **kwargs,
133
+ ):
134
+ """
135
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
136
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
137
+
138
+ Args:
139
+ scheduler (`SchedulerMixin`):
140
+ The scheduler to get timesteps from.
141
+ num_inference_steps (`int`):
142
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
143
+ `timesteps` must be `None`.
144
+ device (`str` or `torch.device`, *optional*):
145
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
146
+ timesteps (`List[int]`, *optional*):
147
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
148
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
149
+ must be `None`.
150
+
151
+ Returns:
152
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
153
+ second element is the number of inference steps.
154
+ """
155
+ if timesteps is not None:
156
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
157
+ if not accepts_timesteps:
158
+ raise ValueError(
159
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
160
+ f" timestep schedules. Please check whether you are using the correct scheduler."
161
+ )
162
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
163
+ timesteps = scheduler.timesteps
164
+ num_inference_steps = len(timesteps)
165
+ else:
166
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
167
+ timesteps = scheduler.timesteps
168
+ return timesteps, num_inference_steps
169
+
170
+
126
171
  class StableDiffusionXLAdapterPipeline(
127
172
  DiffusionPipeline, FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
128
173
  ):
@@ -159,6 +204,7 @@ class StableDiffusionXLAdapterPipeline(
159
204
  feature_extractor ([`CLIPFeatureExtractor`]):
160
205
  Model that extracts features from generated images to be used as inputs for the `safety_checker`.
161
206
  """
207
+
162
208
  model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
163
209
  _optional_components = ["tokenizer", "tokenizer_2", "text_encoder", "text_encoder_2"]
164
210
 
@@ -670,6 +716,46 @@ class StableDiffusionXLAdapterPipeline(
670
716
  """Disables the FreeU mechanism if enabled."""
671
717
  self.unet.disable_freeu()
672
718
 
719
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
720
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
721
+ """
722
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
723
+
724
+ Args:
725
+ timesteps (`torch.Tensor`):
726
+ generate embedding vectors at these timesteps
727
+ embedding_dim (`int`, *optional*, defaults to 512):
728
+ dimension of the embeddings to generate
729
+ dtype:
730
+ data type of the generated embeddings
731
+
732
+ Returns:
733
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
734
+ """
735
+ assert len(w.shape) == 1
736
+ w = w * 1000.0
737
+
738
+ half_dim = embedding_dim // 2
739
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
740
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
741
+ emb = w.to(dtype)[:, None] * emb[None, :]
742
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
743
+ if embedding_dim % 2 == 1: # zero pad
744
+ emb = torch.nn.functional.pad(emb, (0, 1))
745
+ assert emb.shape == (w.shape[0], embedding_dim)
746
+ return emb
747
+
748
+ @property
749
+ def guidance_scale(self):
750
+ return self._guidance_scale
751
+
752
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
753
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
754
+ # corresponds to doing no classifier free guidance.
755
+ @property
756
+ def do_classifier_free_guidance(self):
757
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
758
+
673
759
  @torch.no_grad()
674
760
  @replace_example_docstring(EXAMPLE_DOC_STRING)
675
761
  def __call__(
@@ -680,6 +766,7 @@ class StableDiffusionXLAdapterPipeline(
680
766
  height: Optional[int] = None,
681
767
  width: Optional[int] = None,
682
768
  num_inference_steps: int = 50,
769
+ timesteps: List[int] = None,
683
770
  denoising_end: Optional[float] = None,
684
771
  guidance_scale: float = 5.0,
685
772
  negative_prompt: Optional[Union[str, List[str]]] = None,
@@ -733,6 +820,10 @@ class StableDiffusionXLAdapterPipeline(
733
820
  num_inference_steps (`int`, *optional*, defaults to 50):
734
821
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
735
822
  expense of slower inference.
823
+ timesteps (`List[int]`, *optional*):
824
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
825
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
826
+ passed will be used. Must be in descending order.
736
827
  denoising_end (`float`, *optional*):
737
828
  When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
738
829
  completed before it is intentionally prematurely terminated. As a result, the returned sample will
@@ -882,6 +973,8 @@ class StableDiffusionXLAdapterPipeline(
882
973
  negative_pooled_prompt_embeds,
883
974
  )
884
975
 
976
+ self._guidance_scale = guidance_scale
977
+
885
978
  # 2. Define call parameters
886
979
  if prompt is not None and isinstance(prompt, str):
887
980
  batch_size = 1
@@ -892,11 +985,6 @@ class StableDiffusionXLAdapterPipeline(
892
985
 
893
986
  device = self._execution_device
894
987
 
895
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
896
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
897
- # corresponds to doing no classifier free guidance.
898
- do_classifier_free_guidance = guidance_scale > 1.0
899
-
900
988
  # 3. Encode input prompt
901
989
  (
902
990
  prompt_embeds,
@@ -908,7 +996,7 @@ class StableDiffusionXLAdapterPipeline(
908
996
  prompt_2=prompt_2,
909
997
  device=device,
910
998
  num_images_per_prompt=num_images_per_prompt,
911
- do_classifier_free_guidance=do_classifier_free_guidance,
999
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
912
1000
  negative_prompt=negative_prompt,
913
1001
  negative_prompt_2=negative_prompt_2,
914
1002
  prompt_embeds=prompt_embeds,
@@ -919,9 +1007,7 @@ class StableDiffusionXLAdapterPipeline(
919
1007
  )
920
1008
 
921
1009
  # 4. Prepare timesteps
922
- self.scheduler.set_timesteps(num_inference_steps, device=device)
923
-
924
- timesteps = self.scheduler.timesteps
1010
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
925
1011
 
926
1012
  # 5. Prepare latent variables
927
1013
  num_channels_latents = self.unet.config.in_channels
@@ -939,6 +1025,14 @@ class StableDiffusionXLAdapterPipeline(
939
1025
  # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
940
1026
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
941
1027
 
1028
+ # 6.5 Optionally get Guidance Scale Embedding
1029
+ timestep_cond = None
1030
+ if self.unet.config.time_cond_proj_dim is not None:
1031
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1032
+ timestep_cond = self.get_guidance_scale_embedding(
1033
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1034
+ ).to(device=device, dtype=latents.dtype)
1035
+
942
1036
  # 7. Prepare added time ids & embeddings & adapter features
943
1037
  if isinstance(self.adapter, MultiAdapter):
944
1038
  adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
@@ -951,7 +1045,7 @@ class StableDiffusionXLAdapterPipeline(
951
1045
  if num_images_per_prompt > 1:
952
1046
  for k, v in enumerate(adapter_state):
953
1047
  adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
954
- if do_classifier_free_guidance:
1048
+ if self.do_classifier_free_guidance:
955
1049
  for k, v in enumerate(adapter_state):
956
1050
  adapter_state[k] = torch.cat([v] * 2, dim=0)
957
1051
 
@@ -979,7 +1073,7 @@ class StableDiffusionXLAdapterPipeline(
979
1073
  else:
980
1074
  negative_add_time_ids = add_time_ids
981
1075
 
982
- if do_classifier_free_guidance:
1076
+ if self.do_classifier_free_guidance:
983
1077
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
984
1078
  add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
985
1079
  add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
@@ -1005,7 +1099,7 @@ class StableDiffusionXLAdapterPipeline(
1005
1099
  with self.progress_bar(total=num_inference_steps) as progress_bar:
1006
1100
  for i, t in enumerate(timesteps):
1007
1101
  # expand the latents if we are doing classifier free guidance
1008
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1102
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1009
1103
 
1010
1104
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1011
1105
 
@@ -1021,6 +1115,7 @@ class StableDiffusionXLAdapterPipeline(
1021
1115
  latent_model_input,
1022
1116
  t,
1023
1117
  encoder_hidden_states=prompt_embeds,
1118
+ timestep_cond=timestep_cond,
1024
1119
  cross_attention_kwargs=cross_attention_kwargs,
1025
1120
  added_cond_kwargs=added_cond_kwargs,
1026
1121
  return_dict=False,
@@ -1028,11 +1123,11 @@ class StableDiffusionXLAdapterPipeline(
1028
1123
  )[0]
1029
1124
 
1030
1125
  # perform guidance
1031
- if do_classifier_free_guidance:
1126
+ if self.do_classifier_free_guidance:
1032
1127
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1033
1128
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1034
1129
 
1035
- if do_classifier_free_guidance and guidance_rescale > 0.0:
1130
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
1036
1131
  # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1037
1132
  noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1038
1133
 
@@ -25,6 +25,7 @@ else:
25
25
  _import_structure["pipeline_text_to_video_synth"] = ["TextToVideoSDPipeline"]
26
26
  _import_structure["pipeline_text_to_video_synth_img2img"] = ["VideoToVideoSDPipeline"]
27
27
  _import_structure["pipeline_text_to_video_zero"] = ["TextToVideoZeroPipeline"]
28
+ _import_structure["pipeline_text_to_video_zero_sdxl"] = ["TextToVideoZeroSDXLPipeline"]
28
29
 
29
30
 
30
31
  if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
@@ -38,6 +39,7 @@ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
38
39
  from .pipeline_text_to_video_synth import TextToVideoSDPipeline
39
40
  from .pipeline_text_to_video_synth_img2img import VideoToVideoSDPipeline
40
41
  from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
42
+ from .pipeline_text_to_video_zero_sdxl import TextToVideoZeroSDXLPipeline
41
43
 
42
44
  else:
43
45
  import sys
@@ -96,6 +96,7 @@ class TextToVideoSDPipeline(DiffusionPipeline, TextualInversionLoaderMixin, Lora
96
96
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
97
97
  [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
98
98
  """
99
+
99
100
  model_cpu_offload_seq = "text_encoder->unet->vae"
100
101
 
101
102
  def __init__(
@@ -79,6 +79,20 @@ EXAMPLE_DOC_STRING = """
79
79
  """
80
80
 
81
81
 
82
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
83
+ def retrieve_latents(
84
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
85
+ ):
86
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
87
+ return encoder_output.latent_dist.sample(generator)
88
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
89
+ return encoder_output.latent_dist.mode()
90
+ elif hasattr(encoder_output, "latents"):
91
+ return encoder_output.latents
92
+ else:
93
+ raise AttributeError("Could not access latents of provided encoder_output")
94
+
95
+
82
96
  def tensor2vid(video: torch.Tensor, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) -> List[np.ndarray]:
83
97
  # This code is copied from https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
84
98
  # reshape to ncfhw
@@ -158,6 +172,7 @@ class VideoToVideoSDPipeline(DiffusionPipeline, TextualInversionLoaderMixin, Lor
158
172
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
159
173
  [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
160
174
  """
175
+
161
176
  model_cpu_offload_seq = "text_encoder->unet->vae"
162
177
 
163
178
  def __init__(
@@ -546,14 +561,14 @@ class VideoToVideoSDPipeline(DiffusionPipeline, TextualInversionLoaderMixin, Lor
546
561
  f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
547
562
  f" size of {batch_size}. Make sure the batch size matches the length of the generators."
548
563
  )
549
-
550
564
  elif isinstance(generator, list):
551
565
  init_latents = [
552
- self.vae.encode(video[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
566
+ retrieve_latents(self.vae.encode(video[i : i + 1]), generator=generator[i])
567
+ for i in range(batch_size)
553
568
  ]
554
569
  init_latents = torch.cat(init_latents, dim=0)
555
570
  else:
556
- init_latents = self.vae.encode(video).latent_dist.sample(generator)
571
+ init_latents = retrieve_latents(self.vae.encode(video), generator=generator)
557
572
 
558
573
  init_latents = self.vae.config.scaling_factor * init_latents
559
574
 
@@ -13,6 +13,7 @@ from diffusers.models import AutoencoderKL, UNet2DConditionModel
13
13
  from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline, StableDiffusionSafetyChecker
14
14
  from diffusers.schedulers import KarrasDiffusionSchedulers
15
15
  from diffusers.utils import BaseOutput
16
+ from diffusers.utils.torch_utils import randn_tensor
16
17
 
17
18
 
18
19
  def rearrange_0(tensor, f):
@@ -135,7 +136,7 @@ class CrossFrameAttnProcessor2_0:
135
136
 
136
137
  # Cross Frame Attention
137
138
  if not is_cross_attention:
138
- video_length = key.size()[0] // self.batch_size
139
+ video_length = max(1, key.size()[0] // self.batch_size)
139
140
  first_frame_index = [0] * video_length
140
141
 
141
142
  # rearrange keys to have batch and frames in the 1st and 2nd dims respectively
@@ -183,6 +184,7 @@ class TextToVideoPipelineOutput(BaseOutput):
183
184
  List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or
184
185
  `None` if safety checking could not be performed.
185
186
  """
187
+
186
188
  images: Union[List[PIL.Image.Image], np.ndarray]
187
189
  nsfw_content_detected: Optional[List[bool]]
188
190
 
@@ -338,7 +340,7 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
338
340
  x_t1:
339
341
  Forward process applied to x_t0 from time t0 to t1.
340
342
  """
341
- eps = torch.randn(x_t0.size(), generator=generator, dtype=x_t0.dtype, device=x_t0.device)
343
+ eps = randn_tensor(x_t0.size(), generator=generator, dtype=x_t0.dtype, device=x_t0.device)
342
344
  alpha_vec = torch.prod(self.scheduler.alphas[t0:t1])
343
345
  x_t1 = torch.sqrt(alpha_vec) * x_t0 + torch.sqrt(1 - alpha_vec) * eps
344
346
  return x_t1