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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (176) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +0 -1
  4. diffusers/dependency_versions_table.py +4 -5
  5. diffusers/image_processor.py +186 -14
  6. diffusers/loaders/__init__.py +82 -0
  7. diffusers/loaders/ip_adapter.py +157 -0
  8. diffusers/loaders/lora.py +1415 -0
  9. diffusers/loaders/lora_conversion_utils.py +284 -0
  10. diffusers/loaders/single_file.py +631 -0
  11. diffusers/loaders/textual_inversion.py +459 -0
  12. diffusers/loaders/unet.py +735 -0
  13. diffusers/loaders/utils.py +59 -0
  14. diffusers/models/__init__.py +12 -1
  15. diffusers/models/attention.py +165 -14
  16. diffusers/models/attention_flax.py +9 -1
  17. diffusers/models/attention_processor.py +286 -1
  18. diffusers/models/autoencoder_asym_kl.py +14 -9
  19. diffusers/models/autoencoder_kl.py +3 -18
  20. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  21. diffusers/models/autoencoder_tiny.py +20 -24
  22. diffusers/models/consistency_decoder_vae.py +37 -30
  23. diffusers/models/controlnet.py +59 -39
  24. diffusers/models/controlnet_flax.py +19 -18
  25. diffusers/models/embeddings_flax.py +2 -0
  26. diffusers/models/lora.py +131 -1
  27. diffusers/models/modeling_flax_utils.py +2 -1
  28. diffusers/models/modeling_outputs.py +17 -0
  29. diffusers/models/modeling_utils.py +27 -19
  30. diffusers/models/normalization.py +2 -2
  31. diffusers/models/resnet.py +390 -59
  32. diffusers/models/transformer_2d.py +20 -3
  33. diffusers/models/transformer_temporal.py +183 -1
  34. diffusers/models/unet_2d_blocks_flax.py +5 -0
  35. diffusers/models/unet_2d_condition.py +9 -0
  36. diffusers/models/unet_2d_condition_flax.py +13 -13
  37. diffusers/models/unet_3d_blocks.py +957 -173
  38. diffusers/models/unet_3d_condition.py +16 -8
  39. diffusers/models/unet_kandi3.py +589 -0
  40. diffusers/models/unet_motion_model.py +48 -33
  41. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  42. diffusers/models/vae.py +63 -13
  43. diffusers/models/vae_flax.py +7 -0
  44. diffusers/models/vq_model.py +3 -1
  45. diffusers/optimization.py +16 -9
  46. diffusers/pipelines/__init__.py +65 -12
  47. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
  48. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
  49. diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
  50. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  51. diffusers/pipelines/auto_pipeline.py +6 -0
  52. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  53. diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
  54. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
  55. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
  56. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
  57. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
  58. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
  59. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  60. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  61. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  62. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  63. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  64. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  65. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  66. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  67. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  68. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  69. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  70. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  71. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  72. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  73. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  74. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  75. diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
  76. diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
  77. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
  78. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
  79. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  80. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  81. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  82. diffusers/pipelines/pipeline_flax_utils.py +4 -2
  83. diffusers/pipelines/pipeline_utils.py +33 -13
  84. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
  85. diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
  86. diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
  87. diffusers/pipelines/stable_diffusion/__init__.py +64 -21
  88. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
  89. diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
  90. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  91. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  92. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  93. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
  94. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
  95. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
  96. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  97. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
  98. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
  107. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
  108. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
  109. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
  110. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
  111. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
  112. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
  113. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
  114. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
  115. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
  116. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
  117. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
  118. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  119. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
  120. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  121. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
  122. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  123. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
  124. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
  125. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
  126. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
  127. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
  128. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
  129. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
  130. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
  131. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  132. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  133. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  134. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  135. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
  136. diffusers/schedulers/__init__.py +2 -4
  137. diffusers/schedulers/deprecated/__init__.py +50 -0
  138. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  139. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  140. diffusers/schedulers/scheduling_ddim.py +1 -3
  141. diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
  142. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  143. diffusers/schedulers/scheduling_ddpm.py +1 -3
  144. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
  145. diffusers/schedulers/scheduling_deis_multistep.py +15 -5
  146. diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
  147. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
  148. diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
  149. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
  150. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
  151. diffusers/schedulers/scheduling_euler_discrete.py +40 -13
  152. diffusers/schedulers/scheduling_heun_discrete.py +15 -5
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
  155. diffusers/schedulers/scheduling_lcm.py +123 -29
  156. diffusers/schedulers/scheduling_lms_discrete.py +1 -3
  157. diffusers/schedulers/scheduling_pndm.py +1 -3
  158. diffusers/schedulers/scheduling_repaint.py +1 -3
  159. diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
  160. diffusers/utils/__init__.py +1 -0
  161. diffusers/utils/constants.py +8 -7
  162. diffusers/utils/dummy_pt_objects.py +45 -0
  163. diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
  164. diffusers/utils/dynamic_modules_utils.py +4 -4
  165. diffusers/utils/export_utils.py +8 -3
  166. diffusers/utils/logging.py +10 -10
  167. diffusers/utils/outputs.py +5 -5
  168. diffusers/utils/peft_utils.py +88 -44
  169. diffusers/utils/torch_utils.py +2 -2
  170. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
  171. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
  172. diffusers/loaders.py +0 -3336
  173. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
  175. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
  176. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -51,7 +51,7 @@ EXAMPLE_DOC_STRING = """
51
51
  >>> import torch
52
52
  >>> import scipy
53
53
 
54
- >>> repo_id = "cvssp/audioldm-s-full-v2"
54
+ >>> repo_id = "ucsd-reach/musicldm"
55
55
  >>> pipe = MusicLDMPipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
56
56
  >>> pipe = pipe.to("cuda")
57
57
 
@@ -35,9 +35,13 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
35
 
36
36
 
37
37
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
38
- def retrieve_latents(encoder_output, generator):
39
- if hasattr(encoder_output, "latent_dist"):
38
+ def retrieve_latents(
39
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
40
+ ):
41
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
40
42
  return encoder_output.latent_dist.sample(generator)
43
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
44
+ return encoder_output.latent_dist.mode()
41
45
  elif hasattr(encoder_output, "latents"):
42
46
  return encoder_output.latents
43
47
  else:
@@ -177,6 +181,7 @@ class PaintByExamplePipeline(DiffusionPipeline):
177
181
  A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
178
182
 
179
183
  """
184
+
180
185
  # TODO: feature_extractor is required to encode initial images (if they are in PIL format),
181
186
  # we should give a descriptive message if the pipeline doesn't have one.
182
187
 
@@ -112,6 +112,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
112
112
  - **config_name** ([`str`]) -- The configuration filename that stores the class and module names of all the
113
113
  diffusion pipeline's components.
114
114
  """
115
+
115
116
  config_name = "model_index.json"
116
117
 
117
118
  def register_modules(self, **kwargs):
@@ -537,12 +538,13 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
537
538
  model = pipeline_class(**init_kwargs, dtype=dtype)
538
539
  return model, params
539
540
 
540
- @staticmethod
541
- def _get_signature_keys(obj):
541
+ @classmethod
542
+ def _get_signature_keys(cls, obj):
542
543
  parameters = inspect.signature(obj.__init__).parameters
543
544
  required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
544
545
  optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
545
546
  expected_modules = set(required_parameters.keys()) - {"self"}
547
+
546
548
  return expected_modules, optional_parameters
547
549
 
548
550
  @property
@@ -49,6 +49,7 @@ from ..utils import (
49
49
  get_class_from_dynamic_module,
50
50
  is_accelerate_available,
51
51
  is_accelerate_version,
52
+ is_peft_available,
52
53
  is_torch_version,
53
54
  is_transformers_available,
54
55
  logging,
@@ -258,7 +259,7 @@ def warn_deprecated_model_variant(pretrained_model_name_or_path, use_auth_token,
258
259
  comp_model_filenames, _ = variant_compatible_siblings(filenames, variant=revision)
259
260
  comp_model_filenames = [".".join(f.split(".")[:1] + f.split(".")[2:]) for f in comp_model_filenames]
260
261
 
261
- if set(comp_model_filenames) == set(model_filenames):
262
+ if set(model_filenames).issubset(set(comp_model_filenames)):
262
263
  warnings.warn(
263
264
  f"You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision='{revision}'` even though you can load it via `variant=`{revision}`. Loading model variants via `revision='{revision}'` is deprecated and will be removed in diffusers v1. Please use `variant='{revision}'` instead.",
264
265
  FutureWarning,
@@ -270,6 +271,20 @@ def warn_deprecated_model_variant(pretrained_model_name_or_path, use_auth_token,
270
271
  )
271
272
 
272
273
 
274
+ def _unwrap_model(model):
275
+ """Unwraps a model."""
276
+ if is_compiled_module(model):
277
+ model = model._orig_mod
278
+
279
+ if is_peft_available():
280
+ from peft import PeftModel
281
+
282
+ if isinstance(model, PeftModel):
283
+ model = model.base_model.model
284
+
285
+ return model
286
+
287
+
273
288
  def maybe_raise_or_warn(
274
289
  library_name, library, class_name, importable_classes, passed_class_obj, name, is_pipeline_module
275
290
  ):
@@ -287,9 +302,8 @@ def maybe_raise_or_warn(
287
302
  # Dynamo wraps the original model in a private class.
288
303
  # I didn't find a public API to get the original class.
289
304
  sub_model = passed_class_obj[name]
290
- model_cls = sub_model.__class__
291
- if is_compiled_module(sub_model):
292
- model_cls = sub_model._orig_mod.__class__
305
+ unwrapped_sub_model = _unwrap_model(sub_model)
306
+ model_cls = unwrapped_sub_model.__class__
293
307
 
294
308
  if not issubclass(model_cls, expected_class_obj):
295
309
  raise ValueError(
@@ -528,6 +542,7 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
528
542
  - **_optional_components** (`List[str]`) -- List of all optional components that don't have to be passed to the
529
543
  pipeline to function (should be overridden by subclasses).
530
544
  """
545
+
531
546
  config_name = "model_index.json"
532
547
  model_cpu_offload_seq = None
533
548
  _optional_components = []
@@ -542,14 +557,11 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
542
557
 
543
558
  for name, module in kwargs.items():
544
559
  # retrieve library
545
- if module is None:
560
+ if module is None or isinstance(module, (tuple, list)) and module[0] is None:
546
561
  register_dict = {name: (None, None)}
547
562
  else:
548
563
  # register the config from the original module, not the dynamo compiled one
549
- if is_compiled_module(module):
550
- not_compiled_module = module._orig_mod
551
- else:
552
- not_compiled_module = module
564
+ not_compiled_module = _unwrap_model(module)
553
565
 
554
566
  library = not_compiled_module.__module__.split(".")[0]
555
567
 
@@ -652,7 +664,7 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
652
664
  # Dynamo wraps the original model in a private class.
653
665
  # I didn't find a public API to get the original class.
654
666
  if is_compiled_module(sub_model):
655
- sub_model = sub_model._orig_mod
667
+ sub_model = _unwrap_model(sub_model)
656
668
  model_cls = sub_model.__class__
657
669
 
658
670
  save_method_name = None
@@ -1676,7 +1688,8 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
1676
1688
  if module_candidate is None or not isinstance(module_candidate, str):
1677
1689
  continue
1678
1690
 
1679
- candidate_file = os.path.join(component, module_candidate + ".py")
1691
+ # We compute candidate file path on the Hub. Do not use `os.path.join`.
1692
+ candidate_file = f"{component}/{module_candidate}.py"
1680
1693
 
1681
1694
  if candidate_file in filenames:
1682
1695
  custom_components[component] = module_candidate
@@ -1894,12 +1907,19 @@ class DiffusionPipeline(ConfigMixin, PushToHubMixin):
1894
1907
  " above."
1895
1908
  ) from model_info_call_error
1896
1909
 
1897
- @staticmethod
1898
- def _get_signature_keys(obj):
1910
+ @classmethod
1911
+ def _get_signature_keys(cls, obj):
1899
1912
  parameters = inspect.signature(obj.__init__).parameters
1900
1913
  required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
1901
1914
  optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
1902
1915
  expected_modules = set(required_parameters.keys()) - {"self"}
1916
+
1917
+ optional_names = list(optional_parameters)
1918
+ for name in optional_names:
1919
+ if name in cls._optional_components:
1920
+ expected_modules.add(name)
1921
+ optional_parameters.remove(name)
1922
+
1903
1923
  return expected_modules, optional_parameters
1904
1924
 
1905
1925
  @property
@@ -19,6 +19,7 @@ import urllib.parse as ul
19
19
  from typing import Callable, List, Optional, Tuple, Union
20
20
 
21
21
  import torch
22
+ import torch.nn.functional as F
22
23
  from transformers import T5EncoderModel, T5Tokenizer
23
24
 
24
25
  from ...image_processor import VaeImageProcessor
@@ -26,6 +27,7 @@ from ...models import AutoencoderKL, Transformer2DModel
26
27
  from ...schedulers import DPMSolverMultistepScheduler
27
28
  from ...utils import (
28
29
  BACKENDS_MAPPING,
30
+ deprecate,
29
31
  is_bs4_available,
30
32
  is_ftfy_available,
31
33
  logging,
@@ -43,7 +45,6 @@ if is_bs4_available():
43
45
  if is_ftfy_available():
44
46
  import ftfy
45
47
 
46
-
47
48
  EXAMPLE_DOC_STRING = """
48
49
  Examples:
49
50
  ```py
@@ -60,6 +61,78 @@ EXAMPLE_DOC_STRING = """
60
61
  ```
61
62
  """
62
63
 
64
+ ASPECT_RATIO_1024_BIN = {
65
+ "0.25": [512.0, 2048.0],
66
+ "0.28": [512.0, 1856.0],
67
+ "0.32": [576.0, 1792.0],
68
+ "0.33": [576.0, 1728.0],
69
+ "0.35": [576.0, 1664.0],
70
+ "0.4": [640.0, 1600.0],
71
+ "0.42": [640.0, 1536.0],
72
+ "0.48": [704.0, 1472.0],
73
+ "0.5": [704.0, 1408.0],
74
+ "0.52": [704.0, 1344.0],
75
+ "0.57": [768.0, 1344.0],
76
+ "0.6": [768.0, 1280.0],
77
+ "0.68": [832.0, 1216.0],
78
+ "0.72": [832.0, 1152.0],
79
+ "0.78": [896.0, 1152.0],
80
+ "0.82": [896.0, 1088.0],
81
+ "0.88": [960.0, 1088.0],
82
+ "0.94": [960.0, 1024.0],
83
+ "1.0": [1024.0, 1024.0],
84
+ "1.07": [1024.0, 960.0],
85
+ "1.13": [1088.0, 960.0],
86
+ "1.21": [1088.0, 896.0],
87
+ "1.29": [1152.0, 896.0],
88
+ "1.38": [1152.0, 832.0],
89
+ "1.46": [1216.0, 832.0],
90
+ "1.67": [1280.0, 768.0],
91
+ "1.75": [1344.0, 768.0],
92
+ "2.0": [1408.0, 704.0],
93
+ "2.09": [1472.0, 704.0],
94
+ "2.4": [1536.0, 640.0],
95
+ "2.5": [1600.0, 640.0],
96
+ "3.0": [1728.0, 576.0],
97
+ "4.0": [2048.0, 512.0],
98
+ }
99
+
100
+ ASPECT_RATIO_512_BIN = {
101
+ "0.25": [256.0, 1024.0],
102
+ "0.28": [256.0, 928.0],
103
+ "0.32": [288.0, 896.0],
104
+ "0.33": [288.0, 864.0],
105
+ "0.35": [288.0, 832.0],
106
+ "0.4": [320.0, 800.0],
107
+ "0.42": [320.0, 768.0],
108
+ "0.48": [352.0, 736.0],
109
+ "0.5": [352.0, 704.0],
110
+ "0.52": [352.0, 672.0],
111
+ "0.57": [384.0, 672.0],
112
+ "0.6": [384.0, 640.0],
113
+ "0.68": [416.0, 608.0],
114
+ "0.72": [416.0, 576.0],
115
+ "0.78": [448.0, 576.0],
116
+ "0.82": [448.0, 544.0],
117
+ "0.88": [480.0, 544.0],
118
+ "0.94": [480.0, 512.0],
119
+ "1.0": [512.0, 512.0],
120
+ "1.07": [512.0, 480.0],
121
+ "1.13": [544.0, 480.0],
122
+ "1.21": [544.0, 448.0],
123
+ "1.29": [576.0, 448.0],
124
+ "1.38": [576.0, 416.0],
125
+ "1.46": [608.0, 416.0],
126
+ "1.67": [640.0, 384.0],
127
+ "1.75": [672.0, 384.0],
128
+ "2.0": [704.0, 352.0],
129
+ "2.09": [736.0, 352.0],
130
+ "2.4": [768.0, 320.0],
131
+ "2.5": [800.0, 320.0],
132
+ "3.0": [864.0, 288.0],
133
+ "4.0": [1024.0, 256.0],
134
+ }
135
+
63
136
 
64
137
  class PixArtAlphaPipeline(DiffusionPipeline):
65
138
  r"""
@@ -83,8 +156,21 @@ class PixArtAlphaPipeline(DiffusionPipeline):
83
156
  scheduler ([`SchedulerMixin`]):
84
157
  A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
85
158
  """
159
+
86
160
  bad_punct_regex = re.compile(
87
- r"[" + "#®•©™&@·º½¾¿¡§~" + "\)" + "\(" + "\]" + "\[" + "\}" + "\{" + "\|" + "\\" + "\/" + "\*" + r"]{1,}"
161
+ r"["
162
+ + "#®•©™&@·º½¾¿¡§~"
163
+ + r"\)"
164
+ + r"\("
165
+ + r"\]"
166
+ + r"\["
167
+ + r"\}"
168
+ + r"\{"
169
+ + r"\|"
170
+ + "\\"
171
+ + r"\/"
172
+ + r"\*"
173
+ + r"]{1,}"
88
174
  ) # noqa
89
175
 
90
176
  _optional_components = ["tokenizer", "text_encoder"]
@@ -126,8 +212,10 @@ class PixArtAlphaPipeline(DiffusionPipeline):
126
212
  device: Optional[torch.device] = None,
127
213
  prompt_embeds: Optional[torch.FloatTensor] = None,
128
214
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
215
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
216
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
129
217
  clean_caption: bool = False,
130
- mask_feature: bool = True,
218
+ **kwargs,
131
219
  ):
132
220
  r"""
133
221
  Encodes the prompt into text encoder hidden states.
@@ -153,10 +241,11 @@ class PixArtAlphaPipeline(DiffusionPipeline):
153
241
  string.
154
242
  clean_caption (bool, defaults to `False`):
155
243
  If `True`, the function will preprocess and clean the provided caption before encoding.
156
- mask_feature: (bool, defaults to `True`):
157
- If `True`, the function will mask the text embeddings.
158
244
  """
159
- embeds_initially_provided = prompt_embeds is not None and negative_prompt_embeds is not None
245
+
246
+ if "mask_feature" in kwargs:
247
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
248
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
160
249
 
161
250
  if device is None:
162
251
  device = self._execution_device
@@ -193,13 +282,11 @@ class PixArtAlphaPipeline(DiffusionPipeline):
193
282
  f" {max_length} tokens: {removed_text}"
194
283
  )
195
284
 
196
- attention_mask = text_inputs.attention_mask.to(device)
197
- prompt_embeds_attention_mask = attention_mask
285
+ prompt_attention_mask = text_inputs.attention_mask
286
+ prompt_attention_mask = prompt_attention_mask.to(device)
198
287
 
199
- prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
288
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)
200
289
  prompt_embeds = prompt_embeds[0]
201
- else:
202
- prompt_embeds_attention_mask = torch.ones_like(prompt_embeds)
203
290
 
204
291
  if self.text_encoder is not None:
205
292
  dtype = self.text_encoder.dtype
@@ -214,8 +301,8 @@ class PixArtAlphaPipeline(DiffusionPipeline):
214
301
  # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
215
302
  prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
216
303
  prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
217
- prompt_embeds_attention_mask = prompt_embeds_attention_mask.view(bs_embed, -1)
218
- prompt_embeds_attention_mask = prompt_embeds_attention_mask.repeat(num_images_per_prompt, 1)
304
+ prompt_attention_mask = prompt_attention_mask.view(bs_embed, -1)
305
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
219
306
 
220
307
  # get unconditional embeddings for classifier free guidance
221
308
  if do_classifier_free_guidance and negative_prompt_embeds is None:
@@ -231,11 +318,11 @@ class PixArtAlphaPipeline(DiffusionPipeline):
231
318
  add_special_tokens=True,
232
319
  return_tensors="pt",
233
320
  )
234
- attention_mask = uncond_input.attention_mask.to(device)
321
+ negative_prompt_attention_mask = uncond_input.attention_mask
322
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(device)
235
323
 
236
324
  negative_prompt_embeds = self.text_encoder(
237
- uncond_input.input_ids.to(device),
238
- attention_mask=attention_mask,
325
+ uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask
239
326
  )
240
327
  negative_prompt_embeds = negative_prompt_embeds[0]
241
328
 
@@ -248,23 +335,13 @@ class PixArtAlphaPipeline(DiffusionPipeline):
248
335
  negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
249
336
  negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
250
337
 
251
- # For classifier free guidance, we need to do two forward passes.
252
- # Here we concatenate the unconditional and text embeddings into a single batch
253
- # to avoid doing two forward passes
338
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed, -1)
339
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
254
340
  else:
255
341
  negative_prompt_embeds = None
342
+ negative_prompt_attention_mask = None
256
343
 
257
- # Perform additional masking.
258
- if mask_feature and not embeds_initially_provided:
259
- prompt_embeds = prompt_embeds.unsqueeze(1)
260
- masked_prompt_embeds, keep_indices = self.mask_text_embeddings(prompt_embeds, prompt_embeds_attention_mask)
261
- masked_prompt_embeds = masked_prompt_embeds.squeeze(1)
262
- masked_negative_prompt_embeds = (
263
- negative_prompt_embeds[:, :keep_indices, :] if negative_prompt_embeds is not None else None
264
- )
265
- return masked_prompt_embeds, masked_negative_prompt_embeds
266
-
267
- return prompt_embeds, negative_prompt_embeds
344
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
268
345
 
269
346
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
270
347
  def prepare_extra_step_kwargs(self, generator, eta):
@@ -293,6 +370,8 @@ class PixArtAlphaPipeline(DiffusionPipeline):
293
370
  callback_steps,
294
371
  prompt_embeds=None,
295
372
  negative_prompt_embeds=None,
373
+ prompt_attention_mask=None,
374
+ negative_prompt_attention_mask=None,
296
375
  ):
297
376
  if height % 8 != 0 or width % 8 != 0:
298
377
  raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
@@ -329,6 +408,12 @@ class PixArtAlphaPipeline(DiffusionPipeline):
329
408
  f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
330
409
  )
331
410
 
411
+ if prompt_embeds is not None and prompt_attention_mask is None:
412
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
413
+
414
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
415
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
416
+
332
417
  if prompt_embeds is not None and negative_prompt_embeds is not None:
333
418
  if prompt_embeds.shape != negative_prompt_embeds.shape:
334
419
  raise ValueError(
@@ -336,6 +421,12 @@ class PixArtAlphaPipeline(DiffusionPipeline):
336
421
  f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
337
422
  f" {negative_prompt_embeds.shape}."
338
423
  )
424
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
425
+ raise ValueError(
426
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
427
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
428
+ f" {negative_prompt_attention_mask.shape}."
429
+ )
339
430
 
340
431
  # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
341
432
  def _text_preprocessing(self, text, clean_caption=False):
@@ -495,6 +586,38 @@ class PixArtAlphaPipeline(DiffusionPipeline):
495
586
  latents = latents * self.scheduler.init_noise_sigma
496
587
  return latents
497
588
 
589
+ @staticmethod
590
+ def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
591
+ """Returns binned height and width."""
592
+ ar = float(height / width)
593
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
594
+ default_hw = ratios[closest_ratio]
595
+ return int(default_hw[0]), int(default_hw[1])
596
+
597
+ @staticmethod
598
+ def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int) -> torch.Tensor:
599
+ orig_height, orig_width = samples.shape[2], samples.shape[3]
600
+
601
+ # Check if resizing is needed
602
+ if orig_height != new_height or orig_width != new_width:
603
+ ratio = max(new_height / orig_height, new_width / orig_width)
604
+ resized_width = int(orig_width * ratio)
605
+ resized_height = int(orig_height * ratio)
606
+
607
+ # Resize
608
+ samples = F.interpolate(
609
+ samples, size=(resized_height, resized_width), mode="bilinear", align_corners=False
610
+ )
611
+
612
+ # Center Crop
613
+ start_x = (resized_width - new_width) // 2
614
+ end_x = start_x + new_width
615
+ start_y = (resized_height - new_height) // 2
616
+ end_y = start_y + new_height
617
+ samples = samples[:, :, start_y:end_y, start_x:end_x]
618
+
619
+ return samples
620
+
498
621
  @torch.no_grad()
499
622
  @replace_example_docstring(EXAMPLE_DOC_STRING)
500
623
  def __call__(
@@ -511,13 +634,16 @@ class PixArtAlphaPipeline(DiffusionPipeline):
511
634
  generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
512
635
  latents: Optional[torch.FloatTensor] = None,
513
636
  prompt_embeds: Optional[torch.FloatTensor] = None,
637
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
514
638
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
639
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
515
640
  output_type: Optional[str] = "pil",
516
641
  return_dict: bool = True,
517
642
  callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
518
643
  callback_steps: int = 1,
519
644
  clean_caption: bool = True,
520
- mask_feature: bool = True,
645
+ use_resolution_binning: bool = True,
646
+ **kwargs,
521
647
  ) -> Union[ImagePipelineOutput, Tuple]:
522
648
  """
523
649
  Function invoked when calling the pipeline for generation.
@@ -536,7 +662,7 @@ class PixArtAlphaPipeline(DiffusionPipeline):
536
662
  timesteps (`List[int]`, *optional*):
537
663
  Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
538
664
  timesteps are used. Must be in descending order.
539
- guidance_scale (`float`, *optional*, defaults to 7.0):
665
+ guidance_scale (`float`, *optional*, defaults to 4.5):
540
666
  Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
541
667
  `guidance_scale` is defined as `w` of equation 2. of [Imagen
542
668
  Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
@@ -561,9 +687,12 @@ class PixArtAlphaPipeline(DiffusionPipeline):
561
687
  prompt_embeds (`torch.FloatTensor`, *optional*):
562
688
  Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
563
689
  provided, text embeddings will be generated from `prompt` input argument.
690
+ prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
564
691
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
565
692
  Pre-generated negative text embeddings. For PixArt-Alpha this negative prompt should be "". If not
566
693
  provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
694
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
695
+ Pre-generated attention mask for negative text embeddings.
567
696
  output_type (`str`, *optional*, defaults to `"pil"`):
568
697
  The output format of the generate image. Choose between
569
698
  [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
@@ -579,7 +708,10 @@ class PixArtAlphaPipeline(DiffusionPipeline):
579
708
  Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
580
709
  be installed. If the dependencies are not installed, the embeddings will be created from the raw
581
710
  prompt.
582
- mask_feature (`bool` defaults to `True`): If set to `True`, the text embeddings will be masked.
711
+ use_resolution_binning (`bool` defaults to `True`):
712
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
713
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
714
+ the requested resolution. Useful for generating non-square images.
583
715
 
584
716
  Examples:
585
717
 
@@ -588,11 +720,29 @@ class PixArtAlphaPipeline(DiffusionPipeline):
588
720
  If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
589
721
  returned where the first element is a list with the generated images
590
722
  """
723
+ if "mask_feature" in kwargs:
724
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
725
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
591
726
  # 1. Check inputs. Raise error if not correct
592
727
  height = height or self.transformer.config.sample_size * self.vae_scale_factor
593
728
  width = width or self.transformer.config.sample_size * self.vae_scale_factor
729
+ if use_resolution_binning:
730
+ aspect_ratio_bin = (
731
+ ASPECT_RATIO_1024_BIN if self.transformer.config.sample_size == 128 else ASPECT_RATIO_512_BIN
732
+ )
733
+ orig_height, orig_width = height, width
734
+ height, width = self.classify_height_width_bin(height, width, ratios=aspect_ratio_bin)
735
+
594
736
  self.check_inputs(
595
- prompt, height, width, negative_prompt, callback_steps, prompt_embeds, negative_prompt_embeds
737
+ prompt,
738
+ height,
739
+ width,
740
+ negative_prompt,
741
+ callback_steps,
742
+ prompt_embeds,
743
+ negative_prompt_embeds,
744
+ prompt_attention_mask,
745
+ negative_prompt_attention_mask,
596
746
  )
597
747
 
598
748
  # 2. Default height and width to transformer
@@ -611,7 +761,12 @@ class PixArtAlphaPipeline(DiffusionPipeline):
611
761
  do_classifier_free_guidance = guidance_scale > 1.0
612
762
 
613
763
  # 3. Encode input prompt
614
- prompt_embeds, negative_prompt_embeds = self.encode_prompt(
764
+ (
765
+ prompt_embeds,
766
+ prompt_attention_mask,
767
+ negative_prompt_embeds,
768
+ negative_prompt_attention_mask,
769
+ ) = self.encode_prompt(
615
770
  prompt,
616
771
  do_classifier_free_guidance,
617
772
  negative_prompt=negative_prompt,
@@ -619,11 +774,13 @@ class PixArtAlphaPipeline(DiffusionPipeline):
619
774
  device=device,
620
775
  prompt_embeds=prompt_embeds,
621
776
  negative_prompt_embeds=negative_prompt_embeds,
777
+ prompt_attention_mask=prompt_attention_mask,
778
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
622
779
  clean_caption=clean_caption,
623
- mask_feature=mask_feature,
624
780
  )
625
781
  if do_classifier_free_guidance:
626
782
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
783
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
627
784
 
628
785
  # 4. Prepare timesteps
629
786
  self.scheduler.set_timesteps(num_inference_steps, device=device)
@@ -681,6 +838,7 @@ class PixArtAlphaPipeline(DiffusionPipeline):
681
838
  noise_pred = self.transformer(
682
839
  latent_model_input,
683
840
  encoder_hidden_states=prompt_embeds,
841
+ encoder_attention_mask=prompt_attention_mask,
684
842
  timestep=current_timestep,
685
843
  added_cond_kwargs=added_cond_kwargs,
686
844
  return_dict=False,
@@ -709,6 +867,8 @@ class PixArtAlphaPipeline(DiffusionPipeline):
709
867
 
710
868
  if not output_type == "latent":
711
869
  image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
870
+ if use_resolution_binning:
871
+ image = self.resize_and_crop_tensor(image, orig_width, orig_height)
712
872
  else:
713
873
  image = latents
714
874
 
@@ -35,6 +35,7 @@ class ScoreSdeVePipeline(DiffusionPipeline):
35
35
  scheduler ([`ScoreSdeVeScheduler`]):
36
36
  A `ScoreSdeVeScheduler` to be used in combination with `unet` to denoise the encoded image.
37
37
  """
38
+
38
39
  unet: UNet2DModel
39
40
  scheduler: ScoreSdeVeScheduler
40
41
 
@@ -54,6 +54,7 @@ class SpectrogramDiffusionPipeline(DiffusionPipeline):
54
54
  A scheduler to be used in combination with `decoder` to denoise the encoded audio latents.
55
55
  melgan ([`OnnxRuntimeModel`]):
56
56
  """
57
+
57
58
  _optional_components = ["melgan"]
58
59
 
59
60
  def __init__(