diffusers 0.31.0__py3-none-any.whl → 0.32.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. diffusers/__init__.py +66 -5
  2. diffusers/callbacks.py +56 -3
  3. diffusers/configuration_utils.py +1 -1
  4. diffusers/dependency_versions_table.py +1 -1
  5. diffusers/image_processor.py +25 -17
  6. diffusers/loaders/__init__.py +22 -3
  7. diffusers/loaders/ip_adapter.py +538 -15
  8. diffusers/loaders/lora_base.py +124 -118
  9. diffusers/loaders/lora_conversion_utils.py +318 -3
  10. diffusers/loaders/lora_pipeline.py +1688 -368
  11. diffusers/loaders/peft.py +379 -0
  12. diffusers/loaders/single_file_model.py +71 -4
  13. diffusers/loaders/single_file_utils.py +519 -9
  14. diffusers/loaders/textual_inversion.py +3 -3
  15. diffusers/loaders/transformer_flux.py +181 -0
  16. diffusers/loaders/transformer_sd3.py +89 -0
  17. diffusers/loaders/unet.py +17 -4
  18. diffusers/models/__init__.py +47 -14
  19. diffusers/models/activations.py +22 -9
  20. diffusers/models/attention.py +13 -4
  21. diffusers/models/attention_flax.py +1 -1
  22. diffusers/models/attention_processor.py +2059 -281
  23. diffusers/models/autoencoders/__init__.py +5 -0
  24. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  25. diffusers/models/autoencoders/autoencoder_kl.py +2 -1
  26. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  27. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +36 -27
  28. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  29. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  30. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  31. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +3 -10
  32. diffusers/models/autoencoders/autoencoder_tiny.py +4 -2
  33. diffusers/models/autoencoders/vae.py +18 -5
  34. diffusers/models/controlnet.py +47 -802
  35. diffusers/models/controlnet_flux.py +29 -495
  36. diffusers/models/controlnet_sd3.py +25 -379
  37. diffusers/models/controlnet_sparsectrl.py +46 -718
  38. diffusers/models/controlnets/__init__.py +23 -0
  39. diffusers/models/controlnets/controlnet.py +872 -0
  40. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +5 -5
  41. diffusers/models/controlnets/controlnet_flux.py +536 -0
  42. diffusers/models/{controlnet_hunyuan.py → controlnets/controlnet_hunyuan.py} +7 -7
  43. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  44. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  45. diffusers/models/controlnets/controlnet_union.py +832 -0
  46. diffusers/models/{controlnet_xs.py → controlnets/controlnet_xs.py} +14 -13
  47. diffusers/models/controlnets/multicontrolnet.py +183 -0
  48. diffusers/models/embeddings.py +838 -43
  49. diffusers/models/model_loading_utils.py +88 -6
  50. diffusers/models/modeling_flax_utils.py +1 -1
  51. diffusers/models/modeling_utils.py +72 -26
  52. diffusers/models/normalization.py +78 -13
  53. diffusers/models/transformers/__init__.py +5 -0
  54. diffusers/models/transformers/auraflow_transformer_2d.py +2 -2
  55. diffusers/models/transformers/cogvideox_transformer_3d.py +46 -11
  56. diffusers/models/transformers/dit_transformer_2d.py +1 -1
  57. diffusers/models/transformers/latte_transformer_3d.py +4 -4
  58. diffusers/models/transformers/pixart_transformer_2d.py +1 -1
  59. diffusers/models/transformers/sana_transformer.py +488 -0
  60. diffusers/models/transformers/stable_audio_transformer.py +1 -1
  61. diffusers/models/transformers/transformer_2d.py +1 -1
  62. diffusers/models/transformers/transformer_allegro.py +422 -0
  63. diffusers/models/transformers/transformer_cogview3plus.py +1 -1
  64. diffusers/models/transformers/transformer_flux.py +30 -9
  65. diffusers/models/transformers/transformer_hunyuan_video.py +789 -0
  66. diffusers/models/transformers/transformer_ltx.py +469 -0
  67. diffusers/models/transformers/transformer_mochi.py +499 -0
  68. diffusers/models/transformers/transformer_sd3.py +105 -17
  69. diffusers/models/transformers/transformer_temporal.py +1 -1
  70. diffusers/models/unets/unet_1d_blocks.py +1 -1
  71. diffusers/models/unets/unet_2d.py +8 -1
  72. diffusers/models/unets/unet_2d_blocks.py +88 -21
  73. diffusers/models/unets/unet_2d_condition.py +1 -1
  74. diffusers/models/unets/unet_3d_blocks.py +9 -7
  75. diffusers/models/unets/unet_motion_model.py +5 -5
  76. diffusers/models/unets/unet_spatio_temporal_condition.py +23 -0
  77. diffusers/models/unets/unet_stable_cascade.py +2 -2
  78. diffusers/models/unets/uvit_2d.py +1 -1
  79. diffusers/models/upsampling.py +8 -0
  80. diffusers/pipelines/__init__.py +34 -0
  81. diffusers/pipelines/allegro/__init__.py +48 -0
  82. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  83. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  84. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +8 -2
  85. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1 -1
  86. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +0 -6
  87. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +8 -8
  88. diffusers/pipelines/audioldm2/modeling_audioldm2.py +3 -3
  89. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -8
  90. diffusers/pipelines/auto_pipeline.py +53 -6
  91. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  92. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +50 -22
  93. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +51 -20
  94. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +69 -21
  95. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +47 -21
  96. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +1 -1
  97. diffusers/pipelines/controlnet/__init__.py +86 -80
  98. diffusers/pipelines/controlnet/multicontrolnet.py +7 -178
  99. diffusers/pipelines/controlnet/pipeline_controlnet.py +11 -2
  100. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +1 -2
  101. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +1 -2
  102. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +1 -2
  103. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +3 -3
  104. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +1 -3
  105. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  106. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  107. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  108. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +5 -1
  109. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +53 -19
  110. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
  111. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +31 -8
  112. diffusers/pipelines/flux/__init__.py +13 -1
  113. diffusers/pipelines/flux/modeling_flux.py +47 -0
  114. diffusers/pipelines/flux/pipeline_flux.py +204 -29
  115. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  116. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  117. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  118. diffusers/pipelines/flux/pipeline_flux_controlnet.py +49 -27
  119. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +40 -30
  120. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +78 -56
  121. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  122. diffusers/pipelines/flux/pipeline_flux_img2img.py +33 -27
  123. diffusers/pipelines/flux/pipeline_flux_inpaint.py +36 -29
  124. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  125. diffusers/pipelines/flux/pipeline_output.py +16 -0
  126. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  127. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  128. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  129. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +5 -1
  130. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +9 -9
  131. diffusers/pipelines/kolors/text_encoder.py +2 -2
  132. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  133. diffusers/pipelines/ltx/__init__.py +50 -0
  134. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  135. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  136. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  137. diffusers/pipelines/lumina/pipeline_lumina.py +1 -8
  138. diffusers/pipelines/mochi/__init__.py +48 -0
  139. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  140. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  141. diffusers/pipelines/pag/__init__.py +7 -0
  142. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -2
  143. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1 -2
  144. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1 -3
  145. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1 -3
  146. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +5 -1
  147. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +6 -13
  148. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  149. diffusers/pipelines/pag/pipeline_pag_sd_3.py +6 -6
  150. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  151. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +3 -0
  152. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  153. diffusers/pipelines/pipeline_flax_utils.py +1 -1
  154. diffusers/pipelines/pipeline_loading_utils.py +25 -4
  155. diffusers/pipelines/pipeline_utils.py +35 -6
  156. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +6 -13
  157. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +6 -13
  158. diffusers/pipelines/sana/__init__.py +47 -0
  159. diffusers/pipelines/sana/pipeline_output.py +21 -0
  160. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  161. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +12 -1
  162. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -3
  163. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +216 -20
  164. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +62 -9
  165. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +57 -8
  166. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -1
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +0 -8
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +0 -8
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +0 -8
  170. diffusers/pipelines/unidiffuser/modeling_uvit.py +2 -2
  171. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  172. diffusers/quantizers/auto.py +14 -1
  173. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -1
  174. diffusers/quantizers/gguf/__init__.py +1 -0
  175. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  176. diffusers/quantizers/gguf/utils.py +456 -0
  177. diffusers/quantizers/quantization_config.py +280 -2
  178. diffusers/quantizers/torchao/__init__.py +15 -0
  179. diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
  180. diffusers/schedulers/scheduling_ddpm.py +2 -6
  181. diffusers/schedulers/scheduling_ddpm_parallel.py +2 -6
  182. diffusers/schedulers/scheduling_deis_multistep.py +28 -9
  183. diffusers/schedulers/scheduling_dpmsolver_multistep.py +35 -9
  184. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +35 -8
  185. diffusers/schedulers/scheduling_dpmsolver_sde.py +4 -4
  186. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +48 -10
  187. diffusers/schedulers/scheduling_euler_discrete.py +4 -4
  188. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +153 -6
  189. diffusers/schedulers/scheduling_heun_discrete.py +4 -4
  190. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +4 -4
  191. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +4 -4
  192. diffusers/schedulers/scheduling_lcm.py +2 -6
  193. diffusers/schedulers/scheduling_lms_discrete.py +4 -4
  194. diffusers/schedulers/scheduling_repaint.py +1 -1
  195. diffusers/schedulers/scheduling_sasolver.py +28 -9
  196. diffusers/schedulers/scheduling_tcd.py +2 -6
  197. diffusers/schedulers/scheduling_unipc_multistep.py +53 -8
  198. diffusers/training_utils.py +16 -2
  199. diffusers/utils/__init__.py +5 -0
  200. diffusers/utils/constants.py +1 -0
  201. diffusers/utils/dummy_pt_objects.py +180 -0
  202. diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
  203. diffusers/utils/dynamic_modules_utils.py +3 -3
  204. diffusers/utils/hub_utils.py +31 -39
  205. diffusers/utils/import_utils.py +67 -0
  206. diffusers/utils/peft_utils.py +3 -0
  207. diffusers/utils/testing_utils.py +56 -1
  208. diffusers/utils/torch_utils.py +3 -0
  209. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/METADATA +6 -6
  210. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/RECORD +214 -162
  211. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/WHEEL +1 -1
  212. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/LICENSE +0 -0
  213. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/entry_points.txt +0 -0
  214. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,748 @@
1
+ # Copyright 2024 Genmo and 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
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import T5EncoderModel, T5TokenizerFast
21
+
22
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
23
+ from ...loaders import Mochi1LoraLoaderMixin
24
+ from ...models.autoencoders import AutoencoderKL
25
+ from ...models.transformers import MochiTransformer3DModel
26
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
27
+ from ...utils import (
28
+ is_torch_xla_available,
29
+ logging,
30
+ replace_example_docstring,
31
+ )
32
+ from ...utils.torch_utils import randn_tensor
33
+ from ...video_processor import VideoProcessor
34
+ from ..pipeline_utils import DiffusionPipeline
35
+ from .pipeline_output import MochiPipelineOutput
36
+
37
+
38
+ if is_torch_xla_available():
39
+ import torch_xla.core.xla_model as xm
40
+
41
+ XLA_AVAILABLE = True
42
+ else:
43
+ XLA_AVAILABLE = False
44
+
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+ EXAMPLE_DOC_STRING = """
49
+ Examples:
50
+ ```py
51
+ >>> import torch
52
+ >>> from diffusers import MochiPipeline
53
+ >>> from diffusers.utils import export_to_video
54
+
55
+ >>> pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview", torch_dtype=torch.bfloat16)
56
+ >>> pipe.enable_model_cpu_offload()
57
+ >>> pipe.enable_vae_tiling()
58
+ >>> prompt = "Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k."
59
+ >>> frames = pipe(prompt, num_inference_steps=28, guidance_scale=3.5).frames[0]
60
+ >>> export_to_video(frames, "mochi.mp4")
61
+ ```
62
+ """
63
+
64
+
65
+ def calculate_shift(
66
+ image_seq_len,
67
+ base_seq_len: int = 256,
68
+ max_seq_len: int = 4096,
69
+ base_shift: float = 0.5,
70
+ max_shift: float = 1.16,
71
+ ):
72
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
73
+ b = base_shift - m * base_seq_len
74
+ mu = image_seq_len * m + b
75
+ return mu
76
+
77
+
78
+ # from: https://github.com/genmoai/models/blob/075b6e36db58f1242921deff83a1066887b9c9e1/src/mochi_preview/infer.py#L77
79
+ def linear_quadratic_schedule(num_steps, threshold_noise, linear_steps=None):
80
+ if linear_steps is None:
81
+ linear_steps = num_steps // 2
82
+ linear_sigma_schedule = [i * threshold_noise / linear_steps for i in range(linear_steps)]
83
+ threshold_noise_step_diff = linear_steps - threshold_noise * num_steps
84
+ quadratic_steps = num_steps - linear_steps
85
+ quadratic_coef = threshold_noise_step_diff / (linear_steps * quadratic_steps**2)
86
+ linear_coef = threshold_noise / linear_steps - 2 * threshold_noise_step_diff / (quadratic_steps**2)
87
+ const = quadratic_coef * (linear_steps**2)
88
+ quadratic_sigma_schedule = [
89
+ quadratic_coef * (i**2) + linear_coef * i + const for i in range(linear_steps, num_steps)
90
+ ]
91
+ sigma_schedule = linear_sigma_schedule + quadratic_sigma_schedule
92
+ sigma_schedule = [1.0 - x for x in sigma_schedule]
93
+ return sigma_schedule
94
+
95
+
96
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
97
+ def retrieve_timesteps(
98
+ scheduler,
99
+ num_inference_steps: Optional[int] = None,
100
+ device: Optional[Union[str, torch.device]] = None,
101
+ timesteps: Optional[List[int]] = None,
102
+ sigmas: Optional[List[float]] = None,
103
+ **kwargs,
104
+ ):
105
+ r"""
106
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
107
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
108
+
109
+ Args:
110
+ scheduler (`SchedulerMixin`):
111
+ The scheduler to get timesteps from.
112
+ num_inference_steps (`int`):
113
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
114
+ must be `None`.
115
+ device (`str` or `torch.device`, *optional*):
116
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
117
+ timesteps (`List[int]`, *optional*):
118
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
119
+ `num_inference_steps` and `sigmas` must be `None`.
120
+ sigmas (`List[float]`, *optional*):
121
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
122
+ `num_inference_steps` and `timesteps` must be `None`.
123
+
124
+ Returns:
125
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
126
+ second element is the number of inference steps.
127
+ """
128
+ if timesteps is not None and sigmas is not None:
129
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
130
+ if timesteps is not None:
131
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
132
+ if not accepts_timesteps:
133
+ raise ValueError(
134
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
135
+ f" timestep schedules. Please check whether you are using the correct scheduler."
136
+ )
137
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
138
+ timesteps = scheduler.timesteps
139
+ num_inference_steps = len(timesteps)
140
+ elif sigmas is not None:
141
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
142
+ if not accept_sigmas:
143
+ raise ValueError(
144
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
145
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
146
+ )
147
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
148
+ timesteps = scheduler.timesteps
149
+ num_inference_steps = len(timesteps)
150
+ else:
151
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
152
+ timesteps = scheduler.timesteps
153
+ return timesteps, num_inference_steps
154
+
155
+
156
+ class MochiPipeline(DiffusionPipeline, Mochi1LoraLoaderMixin):
157
+ r"""
158
+ The mochi pipeline for text-to-video generation.
159
+
160
+ Reference: https://github.com/genmoai/models
161
+
162
+ Args:
163
+ transformer ([`MochiTransformer3DModel`]):
164
+ Conditional Transformer architecture to denoise the encoded video latents.
165
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
166
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
167
+ vae ([`AutoencoderKL`]):
168
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
169
+ text_encoder ([`T5EncoderModel`]):
170
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
171
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
172
+ tokenizer (`CLIPTokenizer`):
173
+ Tokenizer of class
174
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
175
+ tokenizer (`T5TokenizerFast`):
176
+ Second Tokenizer of class
177
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
178
+ """
179
+
180
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
181
+ _optional_components = []
182
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
183
+
184
+ def __init__(
185
+ self,
186
+ scheduler: FlowMatchEulerDiscreteScheduler,
187
+ vae: AutoencoderKL,
188
+ text_encoder: T5EncoderModel,
189
+ tokenizer: T5TokenizerFast,
190
+ transformer: MochiTransformer3DModel,
191
+ force_zeros_for_empty_prompt: bool = False,
192
+ ):
193
+ super().__init__()
194
+
195
+ self.register_modules(
196
+ vae=vae,
197
+ text_encoder=text_encoder,
198
+ tokenizer=tokenizer,
199
+ transformer=transformer,
200
+ scheduler=scheduler,
201
+ )
202
+ # TODO: determine these scaling factors from model parameters
203
+ self.vae_spatial_scale_factor = 8
204
+ self.vae_temporal_scale_factor = 6
205
+ self.patch_size = 2
206
+
207
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_spatial_scale_factor)
208
+ self.tokenizer_max_length = (
209
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 256
210
+ )
211
+ self.default_height = 480
212
+ self.default_width = 848
213
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
214
+
215
+ def _get_t5_prompt_embeds(
216
+ self,
217
+ prompt: Union[str, List[str]] = None,
218
+ num_videos_per_prompt: int = 1,
219
+ max_sequence_length: int = 256,
220
+ device: Optional[torch.device] = None,
221
+ dtype: Optional[torch.dtype] = None,
222
+ ):
223
+ device = device or self._execution_device
224
+ dtype = dtype or self.text_encoder.dtype
225
+
226
+ prompt = [prompt] if isinstance(prompt, str) else prompt
227
+ batch_size = len(prompt)
228
+
229
+ text_inputs = self.tokenizer(
230
+ prompt,
231
+ padding="max_length",
232
+ max_length=max_sequence_length,
233
+ truncation=True,
234
+ add_special_tokens=True,
235
+ return_tensors="pt",
236
+ )
237
+
238
+ text_input_ids = text_inputs.input_ids
239
+ prompt_attention_mask = text_inputs.attention_mask
240
+ prompt_attention_mask = prompt_attention_mask.bool().to(device)
241
+
242
+ # The original Mochi implementation zeros out empty negative prompts
243
+ # but this can lead to overflow when placing the entire pipeline under the autocast context
244
+ # adding this here so that we can enable zeroing prompts if necessary
245
+ if self.config.force_zeros_for_empty_prompt and (prompt == "" or prompt[-1] == ""):
246
+ text_input_ids = torch.zeros_like(text_input_ids, device=device)
247
+ prompt_attention_mask = torch.zeros_like(prompt_attention_mask, dtype=torch.bool, device=device)
248
+
249
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
250
+
251
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
252
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
253
+ logger.warning(
254
+ "The following part of your input was truncated because `max_sequence_length` is set to "
255
+ f" {max_sequence_length} tokens: {removed_text}"
256
+ )
257
+
258
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)[0]
259
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
260
+
261
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
262
+ _, seq_len, _ = prompt_embeds.shape
263
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
264
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
265
+
266
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
267
+ prompt_attention_mask = prompt_attention_mask.repeat(num_videos_per_prompt, 1)
268
+
269
+ return prompt_embeds, prompt_attention_mask
270
+
271
+ # Adapted from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt
272
+ def encode_prompt(
273
+ self,
274
+ prompt: Union[str, List[str]],
275
+ negative_prompt: Optional[Union[str, List[str]]] = None,
276
+ do_classifier_free_guidance: bool = True,
277
+ num_videos_per_prompt: int = 1,
278
+ prompt_embeds: Optional[torch.Tensor] = None,
279
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
280
+ prompt_attention_mask: Optional[torch.Tensor] = None,
281
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
282
+ max_sequence_length: int = 256,
283
+ device: Optional[torch.device] = None,
284
+ dtype: Optional[torch.dtype] = None,
285
+ ):
286
+ r"""
287
+ Encodes the prompt into text encoder hidden states.
288
+
289
+ Args:
290
+ prompt (`str` or `List[str]`, *optional*):
291
+ prompt to be encoded
292
+ negative_prompt (`str` or `List[str]`, *optional*):
293
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
294
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
295
+ less than `1`).
296
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
297
+ Whether to use classifier free guidance or not.
298
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
299
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
300
+ prompt_embeds (`torch.Tensor`, *optional*):
301
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
302
+ provided, text embeddings will be generated from `prompt` input argument.
303
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
304
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
305
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
306
+ argument.
307
+ device: (`torch.device`, *optional*):
308
+ torch device
309
+ dtype: (`torch.dtype`, *optional*):
310
+ torch dtype
311
+ """
312
+ device = device or self._execution_device
313
+
314
+ prompt = [prompt] if isinstance(prompt, str) else prompt
315
+ if prompt is not None:
316
+ batch_size = len(prompt)
317
+ else:
318
+ batch_size = prompt_embeds.shape[0]
319
+
320
+ if prompt_embeds is None:
321
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
322
+ prompt=prompt,
323
+ num_videos_per_prompt=num_videos_per_prompt,
324
+ max_sequence_length=max_sequence_length,
325
+ device=device,
326
+ dtype=dtype,
327
+ )
328
+
329
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
330
+ negative_prompt = negative_prompt or ""
331
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
332
+
333
+ if prompt is not None and type(prompt) is not type(negative_prompt):
334
+ raise TypeError(
335
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
336
+ f" {type(prompt)}."
337
+ )
338
+ elif batch_size != len(negative_prompt):
339
+ raise ValueError(
340
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
341
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
342
+ " the batch size of `prompt`."
343
+ )
344
+
345
+ negative_prompt_embeds, negative_prompt_attention_mask = self._get_t5_prompt_embeds(
346
+ prompt=negative_prompt,
347
+ num_videos_per_prompt=num_videos_per_prompt,
348
+ max_sequence_length=max_sequence_length,
349
+ device=device,
350
+ dtype=dtype,
351
+ )
352
+
353
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
354
+
355
+ def check_inputs(
356
+ self,
357
+ prompt,
358
+ height,
359
+ width,
360
+ callback_on_step_end_tensor_inputs=None,
361
+ prompt_embeds=None,
362
+ negative_prompt_embeds=None,
363
+ prompt_attention_mask=None,
364
+ negative_prompt_attention_mask=None,
365
+ ):
366
+ if height % 8 != 0 or width % 8 != 0:
367
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
368
+
369
+ if callback_on_step_end_tensor_inputs is not None and not all(
370
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
371
+ ):
372
+ raise ValueError(
373
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
374
+ )
375
+
376
+ if prompt is not None and prompt_embeds is not None:
377
+ raise ValueError(
378
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
379
+ " only forward one of the two."
380
+ )
381
+ elif prompt is None and prompt_embeds is None:
382
+ raise ValueError(
383
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
384
+ )
385
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
386
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
387
+
388
+ if prompt_embeds is not None and prompt_attention_mask is None:
389
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
390
+
391
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
392
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
393
+
394
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
395
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
396
+ raise ValueError(
397
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
398
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
399
+ f" {negative_prompt_embeds.shape}."
400
+ )
401
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
402
+ raise ValueError(
403
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
404
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
405
+ f" {negative_prompt_attention_mask.shape}."
406
+ )
407
+
408
+ def enable_vae_slicing(self):
409
+ r"""
410
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
411
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
412
+ """
413
+ self.vae.enable_slicing()
414
+
415
+ def disable_vae_slicing(self):
416
+ r"""
417
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
418
+ computing decoding in one step.
419
+ """
420
+ self.vae.disable_slicing()
421
+
422
+ def enable_vae_tiling(self):
423
+ r"""
424
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
425
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
426
+ processing larger images.
427
+ """
428
+ self.vae.enable_tiling()
429
+
430
+ def disable_vae_tiling(self):
431
+ r"""
432
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
433
+ computing decoding in one step.
434
+ """
435
+ self.vae.disable_tiling()
436
+
437
+ def prepare_latents(
438
+ self,
439
+ batch_size,
440
+ num_channels_latents,
441
+ height,
442
+ width,
443
+ num_frames,
444
+ dtype,
445
+ device,
446
+ generator,
447
+ latents=None,
448
+ ):
449
+ height = height // self.vae_spatial_scale_factor
450
+ width = width // self.vae_spatial_scale_factor
451
+ num_frames = (num_frames - 1) // self.vae_temporal_scale_factor + 1
452
+
453
+ shape = (batch_size, num_channels_latents, num_frames, height, width)
454
+
455
+ if latents is not None:
456
+ return latents.to(device=device, dtype=dtype)
457
+ if isinstance(generator, list) and len(generator) != batch_size:
458
+ raise ValueError(
459
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
460
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
461
+ )
462
+
463
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
464
+ latents = latents.to(dtype)
465
+ return latents
466
+
467
+ @property
468
+ def guidance_scale(self):
469
+ return self._guidance_scale
470
+
471
+ @property
472
+ def do_classifier_free_guidance(self):
473
+ return self._guidance_scale > 1.0
474
+
475
+ @property
476
+ def num_timesteps(self):
477
+ return self._num_timesteps
478
+
479
+ @property
480
+ def attention_kwargs(self):
481
+ return self._attention_kwargs
482
+
483
+ @property
484
+ def interrupt(self):
485
+ return self._interrupt
486
+
487
+ @torch.no_grad()
488
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
489
+ def __call__(
490
+ self,
491
+ prompt: Union[str, List[str]] = None,
492
+ negative_prompt: Optional[Union[str, List[str]]] = None,
493
+ height: Optional[int] = None,
494
+ width: Optional[int] = None,
495
+ num_frames: int = 19,
496
+ num_inference_steps: int = 64,
497
+ timesteps: List[int] = None,
498
+ guidance_scale: float = 4.5,
499
+ num_videos_per_prompt: Optional[int] = 1,
500
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
501
+ latents: Optional[torch.Tensor] = None,
502
+ prompt_embeds: Optional[torch.Tensor] = None,
503
+ prompt_attention_mask: Optional[torch.Tensor] = None,
504
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
505
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
506
+ output_type: Optional[str] = "pil",
507
+ return_dict: bool = True,
508
+ attention_kwargs: Optional[Dict[str, Any]] = None,
509
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
510
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
511
+ max_sequence_length: int = 256,
512
+ ):
513
+ r"""
514
+ Function invoked when calling the pipeline for generation.
515
+
516
+ Args:
517
+ prompt (`str` or `List[str]`, *optional*):
518
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
519
+ instead.
520
+ height (`int`, *optional*, defaults to `self.default_height`):
521
+ The height in pixels of the generated image. This is set to 480 by default for the best results.
522
+ width (`int`, *optional*, defaults to `self.default_width`):
523
+ The width in pixels of the generated image. This is set to 848 by default for the best results.
524
+ num_frames (`int`, defaults to `19`):
525
+ The number of video frames to generate
526
+ num_inference_steps (`int`, *optional*, defaults to 50):
527
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
528
+ expense of slower inference.
529
+ timesteps (`List[int]`, *optional*):
530
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
531
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
532
+ passed will be used. Must be in descending order.
533
+ guidance_scale (`float`, defaults to `4.5`):
534
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
535
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
536
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
537
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
538
+ usually at the expense of lower image quality.
539
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
540
+ The number of videos to generate per prompt.
541
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
542
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
543
+ to make generation deterministic.
544
+ latents (`torch.Tensor`, *optional*):
545
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
546
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
547
+ tensor will ge generated by sampling using the supplied random `generator`.
548
+ prompt_embeds (`torch.Tensor`, *optional*):
549
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
550
+ provided, text embeddings will be generated from `prompt` input argument.
551
+ prompt_attention_mask (`torch.Tensor`, *optional*):
552
+ Pre-generated attention mask for text embeddings.
553
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
554
+ Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
555
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
556
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
557
+ Pre-generated attention mask for negative text embeddings.
558
+ output_type (`str`, *optional*, defaults to `"pil"`):
559
+ The output format of the generate image. Choose between
560
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
561
+ return_dict (`bool`, *optional*, defaults to `True`):
562
+ Whether or not to return a [`~pipelines.mochi.MochiPipelineOutput`] instead of a plain tuple.
563
+ attention_kwargs (`dict`, *optional*):
564
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
565
+ `self.processor` in
566
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
567
+ callback_on_step_end (`Callable`, *optional*):
568
+ A function that calls at the end of each denoising steps during the inference. The function is called
569
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
570
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
571
+ `callback_on_step_end_tensor_inputs`.
572
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
573
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
574
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
575
+ `._callback_tensor_inputs` attribute of your pipeline class.
576
+ max_sequence_length (`int` defaults to `256`):
577
+ Maximum sequence length to use with the `prompt`.
578
+
579
+ Examples:
580
+
581
+ Returns:
582
+ [`~pipelines.mochi.MochiPipelineOutput`] or `tuple`:
583
+ If `return_dict` is `True`, [`~pipelines.mochi.MochiPipelineOutput`] is returned, otherwise a `tuple`
584
+ is returned where the first element is a list with the generated images.
585
+ """
586
+
587
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
588
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
589
+
590
+ height = height or self.default_height
591
+ width = width or self.default_width
592
+
593
+ # 1. Check inputs. Raise error if not correct
594
+ self.check_inputs(
595
+ prompt=prompt,
596
+ height=height,
597
+ width=width,
598
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
599
+ prompt_embeds=prompt_embeds,
600
+ negative_prompt_embeds=negative_prompt_embeds,
601
+ prompt_attention_mask=prompt_attention_mask,
602
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
603
+ )
604
+
605
+ self._guidance_scale = guidance_scale
606
+ self._attention_kwargs = attention_kwargs
607
+ self._interrupt = False
608
+
609
+ # 2. Define call parameters
610
+ if prompt is not None and isinstance(prompt, str):
611
+ batch_size = 1
612
+ elif prompt is not None and isinstance(prompt, list):
613
+ batch_size = len(prompt)
614
+ else:
615
+ batch_size = prompt_embeds.shape[0]
616
+
617
+ device = self._execution_device
618
+ # 3. Prepare text embeddings
619
+ (
620
+ prompt_embeds,
621
+ prompt_attention_mask,
622
+ negative_prompt_embeds,
623
+ negative_prompt_attention_mask,
624
+ ) = self.encode_prompt(
625
+ prompt=prompt,
626
+ negative_prompt=negative_prompt,
627
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
628
+ num_videos_per_prompt=num_videos_per_prompt,
629
+ prompt_embeds=prompt_embeds,
630
+ negative_prompt_embeds=negative_prompt_embeds,
631
+ prompt_attention_mask=prompt_attention_mask,
632
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
633
+ max_sequence_length=max_sequence_length,
634
+ device=device,
635
+ )
636
+ # 4. Prepare latent variables
637
+ num_channels_latents = self.transformer.config.in_channels
638
+ latents = self.prepare_latents(
639
+ batch_size * num_videos_per_prompt,
640
+ num_channels_latents,
641
+ height,
642
+ width,
643
+ num_frames,
644
+ prompt_embeds.dtype,
645
+ device,
646
+ generator,
647
+ latents,
648
+ )
649
+
650
+ if self.do_classifier_free_guidance:
651
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
652
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
653
+
654
+ # 5. Prepare timestep
655
+ # from https://github.com/genmoai/models/blob/075b6e36db58f1242921deff83a1066887b9c9e1/src/mochi_preview/infer.py#L77
656
+ threshold_noise = 0.025
657
+ sigmas = linear_quadratic_schedule(num_inference_steps, threshold_noise)
658
+ sigmas = np.array(sigmas)
659
+
660
+ timesteps, num_inference_steps = retrieve_timesteps(
661
+ self.scheduler,
662
+ num_inference_steps,
663
+ device,
664
+ timesteps,
665
+ sigmas,
666
+ )
667
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
668
+ self._num_timesteps = len(timesteps)
669
+
670
+ # 6. Denoising loop
671
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
672
+ for i, t in enumerate(timesteps):
673
+ if self.interrupt:
674
+ continue
675
+
676
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
677
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
678
+ timestep = t.expand(latent_model_input.shape[0]).to(latents.dtype)
679
+
680
+ noise_pred = self.transformer(
681
+ hidden_states=latent_model_input,
682
+ encoder_hidden_states=prompt_embeds,
683
+ timestep=timestep,
684
+ encoder_attention_mask=prompt_attention_mask,
685
+ attention_kwargs=attention_kwargs,
686
+ return_dict=False,
687
+ )[0]
688
+ # Mochi CFG + Sampling runs in FP32
689
+ noise_pred = noise_pred.to(torch.float32)
690
+
691
+ if self.do_classifier_free_guidance:
692
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
693
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
694
+
695
+ # compute the previous noisy sample x_t -> x_t-1
696
+ latents_dtype = latents.dtype
697
+ latents = self.scheduler.step(noise_pred, t, latents.to(torch.float32), return_dict=False)[0]
698
+ latents = latents.to(latents_dtype)
699
+
700
+ if latents.dtype != latents_dtype:
701
+ if torch.backends.mps.is_available():
702
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
703
+ latents = latents.to(latents_dtype)
704
+
705
+ if callback_on_step_end is not None:
706
+ callback_kwargs = {}
707
+ for k in callback_on_step_end_tensor_inputs:
708
+ callback_kwargs[k] = locals()[k]
709
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
710
+
711
+ latents = callback_outputs.pop("latents", latents)
712
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
713
+
714
+ # call the callback, if provided
715
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
716
+ progress_bar.update()
717
+
718
+ if XLA_AVAILABLE:
719
+ xm.mark_step()
720
+
721
+ if output_type == "latent":
722
+ video = latents
723
+ else:
724
+ # unscale/denormalize the latents
725
+ # denormalize with the mean and std if available and not None
726
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
727
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
728
+ if has_latents_mean and has_latents_std:
729
+ latents_mean = (
730
+ torch.tensor(self.vae.config.latents_mean).view(1, 12, 1, 1, 1).to(latents.device, latents.dtype)
731
+ )
732
+ latents_std = (
733
+ torch.tensor(self.vae.config.latents_std).view(1, 12, 1, 1, 1).to(latents.device, latents.dtype)
734
+ )
735
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
736
+ else:
737
+ latents = latents / self.vae.config.scaling_factor
738
+
739
+ video = self.vae.decode(latents, return_dict=False)[0]
740
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
741
+
742
+ # Offload all models
743
+ self.maybe_free_model_hooks()
744
+
745
+ if not return_dict:
746
+ return (video,)
747
+
748
+ return MochiPipelineOutput(frames=video)