diffusers 0.17.1__py3-none-any.whl → 0.18.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. diffusers/__init__.py +26 -1
  2. diffusers/configuration_utils.py +34 -29
  3. diffusers/dependency_versions_table.py +4 -0
  4. diffusers/image_processor.py +125 -12
  5. diffusers/loaders.py +169 -203
  6. diffusers/models/attention.py +24 -1
  7. diffusers/models/attention_flax.py +10 -5
  8. diffusers/models/attention_processor.py +3 -0
  9. diffusers/models/autoencoder_kl.py +114 -33
  10. diffusers/models/controlnet.py +131 -14
  11. diffusers/models/controlnet_flax.py +37 -26
  12. diffusers/models/cross_attention.py +17 -17
  13. diffusers/models/embeddings.py +67 -0
  14. diffusers/models/modeling_flax_utils.py +64 -56
  15. diffusers/models/modeling_utils.py +193 -104
  16. diffusers/models/prior_transformer.py +207 -37
  17. diffusers/models/resnet.py +26 -26
  18. diffusers/models/transformer_2d.py +36 -41
  19. diffusers/models/transformer_temporal.py +24 -21
  20. diffusers/models/unet_1d.py +31 -25
  21. diffusers/models/unet_2d.py +43 -30
  22. diffusers/models/unet_2d_blocks.py +210 -89
  23. diffusers/models/unet_2d_blocks_flax.py +12 -12
  24. diffusers/models/unet_2d_condition.py +172 -64
  25. diffusers/models/unet_2d_condition_flax.py +38 -24
  26. diffusers/models/unet_3d_blocks.py +34 -31
  27. diffusers/models/unet_3d_condition.py +101 -34
  28. diffusers/models/vae.py +5 -5
  29. diffusers/models/vae_flax.py +37 -34
  30. diffusers/models/vq_model.py +23 -14
  31. diffusers/pipelines/__init__.py +24 -1
  32. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +1 -1
  33. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -3
  34. diffusers/pipelines/consistency_models/__init__.py +1 -0
  35. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +337 -0
  36. diffusers/pipelines/controlnet/multicontrolnet.py +120 -1
  37. diffusers/pipelines/controlnet/pipeline_controlnet.py +59 -17
  38. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +60 -15
  39. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +60 -17
  40. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
  41. diffusers/pipelines/kandinsky/__init__.py +1 -1
  42. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +4 -6
  43. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +1 -0
  44. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -0
  45. diffusers/pipelines/kandinsky2_2/__init__.py +7 -0
  46. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +317 -0
  47. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +372 -0
  48. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +434 -0
  49. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +398 -0
  50. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +531 -0
  51. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +541 -0
  52. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +605 -0
  53. diffusers/pipelines/pipeline_flax_utils.py +2 -2
  54. diffusers/pipelines/pipeline_utils.py +124 -146
  55. diffusers/pipelines/shap_e/__init__.py +27 -0
  56. diffusers/pipelines/shap_e/camera.py +147 -0
  57. diffusers/pipelines/shap_e/pipeline_shap_e.py +390 -0
  58. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +349 -0
  59. diffusers/pipelines/shap_e/renderer.py +709 -0
  60. diffusers/pipelines/stable_diffusion/__init__.py +2 -0
  61. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +261 -66
  62. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +3 -3
  63. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -3
  64. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -2
  65. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  66. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +1 -1
  67. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  68. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +719 -0
  69. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -1
  70. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +832 -0
  71. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +17 -7
  72. diffusers/pipelines/stable_diffusion_xl/__init__.py +26 -0
  73. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +823 -0
  74. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +896 -0
  75. diffusers/pipelines/stable_diffusion_xl/watermark.py +31 -0
  76. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -1
  77. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -1
  78. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +771 -0
  79. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +92 -6
  80. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  81. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +209 -91
  82. diffusers/schedulers/__init__.py +3 -0
  83. diffusers/schedulers/scheduling_consistency_models.py +380 -0
  84. diffusers/schedulers/scheduling_ddim.py +28 -6
  85. diffusers/schedulers/scheduling_ddim_inverse.py +19 -4
  86. diffusers/schedulers/scheduling_ddim_parallel.py +642 -0
  87. diffusers/schedulers/scheduling_ddpm.py +53 -7
  88. diffusers/schedulers/scheduling_ddpm_parallel.py +604 -0
  89. diffusers/schedulers/scheduling_deis_multistep.py +66 -11
  90. diffusers/schedulers/scheduling_dpmsolver_multistep.py +55 -13
  91. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +19 -4
  92. diffusers/schedulers/scheduling_dpmsolver_sde.py +73 -11
  93. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +23 -7
  94. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -9
  95. diffusers/schedulers/scheduling_euler_discrete.py +58 -8
  96. diffusers/schedulers/scheduling_heun_discrete.py +89 -14
  97. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +73 -11
  98. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +73 -11
  99. diffusers/schedulers/scheduling_lms_discrete.py +57 -8
  100. diffusers/schedulers/scheduling_pndm.py +46 -10
  101. diffusers/schedulers/scheduling_repaint.py +19 -4
  102. diffusers/schedulers/scheduling_sde_ve.py +5 -1
  103. diffusers/schedulers/scheduling_unclip.py +43 -4
  104. diffusers/schedulers/scheduling_unipc_multistep.py +48 -7
  105. diffusers/training_utils.py +1 -1
  106. diffusers/utils/__init__.py +2 -1
  107. diffusers/utils/dummy_pt_objects.py +60 -0
  108. diffusers/utils/dummy_torch_and_transformers_and_invisible_watermark_objects.py +32 -0
  109. diffusers/utils/dummy_torch_and_transformers_objects.py +180 -0
  110. diffusers/utils/hub_utils.py +1 -1
  111. diffusers/utils/import_utils.py +20 -3
  112. diffusers/utils/logging.py +15 -18
  113. diffusers/utils/outputs.py +3 -3
  114. diffusers/utils/testing_utils.py +15 -0
  115. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/METADATA +4 -2
  116. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/RECORD +120 -94
  117. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/WHEEL +1 -1
  118. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/LICENSE +0 -0
  119. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/entry_points.txt +0 -0
  120. {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,604 @@
1
+ # Copyright 2023 ParaDiGMS authors 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
+ # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ from ..configuration_utils import ConfigMixin, register_to_config
25
+ from ..utils import BaseOutput, randn_tensor
26
+ from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
27
+
28
+
29
+ @dataclass
30
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput
31
+ class DDPMParallelSchedulerOutput(BaseOutput):
32
+ """
33
+ Output class for the scheduler's step function output.
34
+
35
+ Args:
36
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
37
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
38
+ denoising loop.
39
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
40
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
41
+ `pred_original_sample` can be used to preview progress or for guidance.
42
+ """
43
+
44
+ prev_sample: torch.FloatTensor
45
+ pred_original_sample: Optional[torch.FloatTensor] = None
46
+
47
+
48
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
49
+ def betas_for_alpha_bar(
50
+ num_diffusion_timesteps,
51
+ max_beta=0.999,
52
+ alpha_transform_type="cosine",
53
+ ):
54
+ """
55
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
56
+ (1-beta) over time from t = [0,1].
57
+
58
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
59
+ to that part of the diffusion process.
60
+
61
+
62
+ Args:
63
+ num_diffusion_timesteps (`int`): the number of betas to produce.
64
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
65
+ prevent singularities.
66
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
67
+ Choose from `cosine` or `exp`
68
+
69
+ Returns:
70
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
71
+ """
72
+ if alpha_transform_type == "cosine":
73
+
74
+ def alpha_bar_fn(t):
75
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
76
+
77
+ elif alpha_transform_type == "exp":
78
+
79
+ def alpha_bar_fn(t):
80
+ return math.exp(t * -12.0)
81
+
82
+ else:
83
+ raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
84
+
85
+ betas = []
86
+ for i in range(num_diffusion_timesteps):
87
+ t1 = i / num_diffusion_timesteps
88
+ t2 = (i + 1) / num_diffusion_timesteps
89
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
90
+ return torch.tensor(betas, dtype=torch.float32)
91
+
92
+
93
+ class DDPMParallelScheduler(SchedulerMixin, ConfigMixin):
94
+ """
95
+ Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and
96
+ Langevin dynamics sampling.
97
+
98
+ [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
99
+ function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
100
+ [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
101
+ [`~SchedulerMixin.from_pretrained`] functions.
102
+
103
+ For more details, see the original paper: https://arxiv.org/abs/2006.11239
104
+
105
+ Args:
106
+ num_train_timesteps (`int`): number of diffusion steps used to train the model.
107
+ beta_start (`float`): the starting `beta` value of inference.
108
+ beta_end (`float`): the final `beta` value.
109
+ beta_schedule (`str`):
110
+ the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
111
+ `linear`, `scaled_linear`, `squaredcos_cap_v2` or `sigmoid`.
112
+ trained_betas (`np.ndarray`, optional):
113
+ option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
114
+ variance_type (`str`):
115
+ options to clip the variance used when adding noise to the denoised sample. Choose from `fixed_small`,
116
+ `fixed_small_log`, `fixed_large`, `fixed_large_log`, `learned` or `learned_range`.
117
+ clip_sample (`bool`, default `True`):
118
+ option to clip predicted sample for numerical stability.
119
+ clip_sample_range (`float`, default `1.0`):
120
+ the maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
121
+ prediction_type (`str`, default `epsilon`, optional):
122
+ prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
123
+ process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
124
+ https://imagen.research.google/video/paper.pdf)
125
+ thresholding (`bool`, default `False`):
126
+ whether to use the "dynamic thresholding" method (introduced by Imagen, https://arxiv.org/abs/2205.11487).
127
+ Note that the thresholding method is unsuitable for latent-space diffusion models (such as
128
+ stable-diffusion).
129
+ dynamic_thresholding_ratio (`float`, default `0.995`):
130
+ the ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen
131
+ (https://arxiv.org/abs/2205.11487). Valid only when `thresholding=True`.
132
+ sample_max_value (`float`, default `1.0`):
133
+ the threshold value for dynamic thresholding. Valid only when `thresholding=True`.
134
+ timestep_spacing (`str`, default `"leading"`):
135
+ The way the timesteps should be scaled. Refer to Table 2. of [Common Diffusion Noise Schedules and Sample
136
+ Steps are Flawed](https://arxiv.org/abs/2305.08891) for more information.
137
+ steps_offset (`int`, default `0`):
138
+ an offset added to the inference steps. You can use a combination of `offset=1` and
139
+ `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
140
+ stable diffusion.
141
+ """
142
+
143
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
144
+ order = 1
145
+ _is_ode_scheduler = False
146
+
147
+ @register_to_config
148
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.__init__
149
+ def __init__(
150
+ self,
151
+ num_train_timesteps: int = 1000,
152
+ beta_start: float = 0.0001,
153
+ beta_end: float = 0.02,
154
+ beta_schedule: str = "linear",
155
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
156
+ variance_type: str = "fixed_small",
157
+ clip_sample: bool = True,
158
+ prediction_type: str = "epsilon",
159
+ thresholding: bool = False,
160
+ dynamic_thresholding_ratio: float = 0.995,
161
+ clip_sample_range: float = 1.0,
162
+ sample_max_value: float = 1.0,
163
+ timestep_spacing: str = "leading",
164
+ steps_offset: int = 0,
165
+ ):
166
+ if trained_betas is not None:
167
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
168
+ elif beta_schedule == "linear":
169
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
170
+ elif beta_schedule == "scaled_linear":
171
+ # this schedule is very specific to the latent diffusion model.
172
+ self.betas = (
173
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
174
+ )
175
+ elif beta_schedule == "squaredcos_cap_v2":
176
+ # Glide cosine schedule
177
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
178
+ elif beta_schedule == "sigmoid":
179
+ # GeoDiff sigmoid schedule
180
+ betas = torch.linspace(-6, 6, num_train_timesteps)
181
+ self.betas = torch.sigmoid(betas) * (beta_end - beta_start) + beta_start
182
+ else:
183
+ raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
184
+
185
+ self.alphas = 1.0 - self.betas
186
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
187
+ self.one = torch.tensor(1.0)
188
+
189
+ # standard deviation of the initial noise distribution
190
+ self.init_noise_sigma = 1.0
191
+
192
+ # setable values
193
+ self.custom_timesteps = False
194
+ self.num_inference_steps = None
195
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy())
196
+
197
+ self.variance_type = variance_type
198
+
199
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.scale_model_input
200
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
201
+ """
202
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
203
+ current timestep.
204
+
205
+ Args:
206
+ sample (`torch.FloatTensor`): input sample
207
+ timestep (`int`, optional): current timestep
208
+
209
+ Returns:
210
+ `torch.FloatTensor`: scaled input sample
211
+ """
212
+ return sample
213
+
214
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.set_timesteps
215
+ def set_timesteps(
216
+ self,
217
+ num_inference_steps: Optional[int] = None,
218
+ device: Union[str, torch.device] = None,
219
+ timesteps: Optional[List[int]] = None,
220
+ ):
221
+ """
222
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
223
+
224
+ Args:
225
+ num_inference_steps (`Optional[int]`):
226
+ the number of diffusion steps used when generating samples with a pre-trained model. If passed, then
227
+ `timesteps` must be `None`.
228
+ device (`str` or `torch.device`, optional):
229
+ the device to which the timesteps are moved to.
230
+ custom_timesteps (`List[int]`, optional):
231
+ custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
232
+ timestep spacing strategy of equal spacing between timesteps is used. If passed, `num_inference_steps`
233
+ must be `None`.
234
+
235
+ """
236
+ if num_inference_steps is not None and timesteps is not None:
237
+ raise ValueError("Can only pass one of `num_inference_steps` or `custom_timesteps`.")
238
+
239
+ if timesteps is not None:
240
+ for i in range(1, len(timesteps)):
241
+ if timesteps[i] >= timesteps[i - 1]:
242
+ raise ValueError("`custom_timesteps` must be in descending order.")
243
+
244
+ if timesteps[0] >= self.config.num_train_timesteps:
245
+ raise ValueError(
246
+ f"`timesteps` must start before `self.config.train_timesteps`:"
247
+ f" {self.config.num_train_timesteps}."
248
+ )
249
+
250
+ timesteps = np.array(timesteps, dtype=np.int64)
251
+ self.custom_timesteps = True
252
+ else:
253
+ if num_inference_steps > self.config.num_train_timesteps:
254
+ raise ValueError(
255
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
256
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
257
+ f" maximal {self.config.num_train_timesteps} timesteps."
258
+ )
259
+
260
+ self.num_inference_steps = num_inference_steps
261
+ self.custom_timesteps = False
262
+
263
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
264
+ if self.config.timestep_spacing == "linspace":
265
+ timesteps = (
266
+ np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps)
267
+ .round()[::-1]
268
+ .copy()
269
+ .astype(np.int64)
270
+ )
271
+ elif self.config.timestep_spacing == "leading":
272
+ step_ratio = self.config.num_train_timesteps // self.num_inference_steps
273
+ # creates integer timesteps by multiplying by ratio
274
+ # casting to int to avoid issues when num_inference_step is power of 3
275
+ timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64)
276
+ timesteps += self.config.steps_offset
277
+ elif self.config.timestep_spacing == "trailing":
278
+ step_ratio = self.config.num_train_timesteps / self.num_inference_steps
279
+ # creates integer timesteps by multiplying by ratio
280
+ # casting to int to avoid issues when num_inference_step is power of 3
281
+ timesteps = np.round(np.arange(self.config.num_train_timesteps, 0, -step_ratio)).astype(np.int64)
282
+ timesteps -= 1
283
+ else:
284
+ raise ValueError(
285
+ f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
286
+ )
287
+
288
+ self.timesteps = torch.from_numpy(timesteps).to(device)
289
+
290
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._get_variance
291
+ def _get_variance(self, t, predicted_variance=None, variance_type=None):
292
+ prev_t = self.previous_timestep(t)
293
+
294
+ alpha_prod_t = self.alphas_cumprod[t]
295
+ alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one
296
+ current_beta_t = 1 - alpha_prod_t / alpha_prod_t_prev
297
+
298
+ # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
299
+ # and sample from it to get previous sample
300
+ # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
301
+ variance = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * current_beta_t
302
+
303
+ # we always take the log of variance, so clamp it to ensure it's not 0
304
+ variance = torch.clamp(variance, min=1e-20)
305
+
306
+ if variance_type is None:
307
+ variance_type = self.config.variance_type
308
+
309
+ # hacks - were probably added for training stability
310
+ if variance_type == "fixed_small":
311
+ variance = variance
312
+ # for rl-diffuser https://arxiv.org/abs/2205.09991
313
+ elif variance_type == "fixed_small_log":
314
+ variance = torch.log(variance)
315
+ variance = torch.exp(0.5 * variance)
316
+ elif variance_type == "fixed_large":
317
+ variance = current_beta_t
318
+ elif variance_type == "fixed_large_log":
319
+ # Glide max_log
320
+ variance = torch.log(current_beta_t)
321
+ elif variance_type == "learned":
322
+ return predicted_variance
323
+ elif variance_type == "learned_range":
324
+ min_log = torch.log(variance)
325
+ max_log = torch.log(current_beta_t)
326
+ frac = (predicted_variance + 1) / 2
327
+ variance = frac * max_log + (1 - frac) * min_log
328
+
329
+ return variance
330
+
331
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
332
+ def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor:
333
+ """
334
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
335
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
336
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
337
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
338
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
339
+
340
+ https://arxiv.org/abs/2205.11487
341
+ """
342
+ dtype = sample.dtype
343
+ batch_size, channels, height, width = sample.shape
344
+
345
+ if dtype not in (torch.float32, torch.float64):
346
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
347
+
348
+ # Flatten sample for doing quantile calculation along each image
349
+ sample = sample.reshape(batch_size, channels * height * width)
350
+
351
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
352
+
353
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
354
+ s = torch.clamp(
355
+ s, min=1, max=self.config.sample_max_value
356
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
357
+
358
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
359
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
360
+
361
+ sample = sample.reshape(batch_size, channels, height, width)
362
+ sample = sample.to(dtype)
363
+
364
+ return sample
365
+
366
+ def step(
367
+ self,
368
+ model_output: torch.FloatTensor,
369
+ timestep: int,
370
+ sample: torch.FloatTensor,
371
+ generator=None,
372
+ return_dict: bool = True,
373
+ ) -> Union[DDPMParallelSchedulerOutput, Tuple]:
374
+ """
375
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
376
+ process from the learned model outputs (most often the predicted noise).
377
+
378
+ Args:
379
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
380
+ timestep (`int`): current discrete timestep in the diffusion chain.
381
+ sample (`torch.FloatTensor`):
382
+ current instance of sample being created by diffusion process.
383
+ generator: random number generator.
384
+ return_dict (`bool`): option for returning tuple rather than DDPMParallelSchedulerOutput class
385
+
386
+ Returns:
387
+ [`~schedulers.scheduling_utils.DDPMParallelSchedulerOutput`] or `tuple`:
388
+ [`~schedulers.scheduling_utils.DDPMParallelSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`.
389
+ When returning a tuple, the first element is the sample tensor.
390
+
391
+ """
392
+ t = timestep
393
+
394
+ prev_t = self.previous_timestep(t)
395
+
396
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
397
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
398
+ else:
399
+ predicted_variance = None
400
+
401
+ # 1. compute alphas, betas
402
+ alpha_prod_t = self.alphas_cumprod[t]
403
+ alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one
404
+ beta_prod_t = 1 - alpha_prod_t
405
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
406
+ current_alpha_t = alpha_prod_t / alpha_prod_t_prev
407
+ current_beta_t = 1 - current_alpha_t
408
+
409
+ # 2. compute predicted original sample from predicted noise also called
410
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
411
+ if self.config.prediction_type == "epsilon":
412
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
413
+ elif self.config.prediction_type == "sample":
414
+ pred_original_sample = model_output
415
+ elif self.config.prediction_type == "v_prediction":
416
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
417
+ else:
418
+ raise ValueError(
419
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or"
420
+ " `v_prediction` for the DDPMScheduler."
421
+ )
422
+
423
+ # 3. Clip or threshold "predicted x_0"
424
+ if self.config.thresholding:
425
+ pred_original_sample = self._threshold_sample(pred_original_sample)
426
+ elif self.config.clip_sample:
427
+ pred_original_sample = pred_original_sample.clamp(
428
+ -self.config.clip_sample_range, self.config.clip_sample_range
429
+ )
430
+
431
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
432
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
433
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * current_beta_t) / beta_prod_t
434
+ current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t
435
+
436
+ # 5. Compute predicted previous sample µ_t
437
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
438
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
439
+
440
+ # 6. Add noise
441
+ variance = 0
442
+ if t > 0:
443
+ device = model_output.device
444
+ variance_noise = randn_tensor(
445
+ model_output.shape, generator=generator, device=device, dtype=model_output.dtype
446
+ )
447
+ if self.variance_type == "fixed_small_log":
448
+ variance = self._get_variance(t, predicted_variance=predicted_variance) * variance_noise
449
+ elif self.variance_type == "learned_range":
450
+ variance = self._get_variance(t, predicted_variance=predicted_variance)
451
+ variance = torch.exp(0.5 * variance) * variance_noise
452
+ else:
453
+ variance = (self._get_variance(t, predicted_variance=predicted_variance) ** 0.5) * variance_noise
454
+
455
+ pred_prev_sample = pred_prev_sample + variance
456
+
457
+ if not return_dict:
458
+ return (pred_prev_sample,)
459
+
460
+ return DDPMParallelSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
461
+
462
+ def batch_step_no_noise(
463
+ self,
464
+ model_output: torch.FloatTensor,
465
+ timesteps: List[int],
466
+ sample: torch.FloatTensor,
467
+ ) -> torch.FloatTensor:
468
+ """
469
+ Batched version of the `step` function, to be able to reverse the SDE for multiple samples/timesteps at once.
470
+ Also, does not add any noise to the predicted sample, which is necessary for parallel sampling where the noise
471
+ is pre-sampled by the pipeline.
472
+
473
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
474
+ process from the learned model outputs (most often the predicted noise).
475
+
476
+ Args:
477
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
478
+ timesteps (`List[int]`):
479
+ current discrete timesteps in the diffusion chain. This is now a list of integers.
480
+ sample (`torch.FloatTensor`):
481
+ current instance of sample being created by diffusion process.
482
+
483
+ Returns:
484
+ `torch.FloatTensor`: sample tensor at previous timestep.
485
+ """
486
+ t = timesteps
487
+ num_inference_steps = self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps
488
+ prev_t = t - self.config.num_train_timesteps // num_inference_steps
489
+
490
+ t = t.view(-1, *([1] * (model_output.ndim - 1)))
491
+ prev_t = prev_t.view(-1, *([1] * (model_output.ndim - 1)))
492
+
493
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
494
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
495
+ else:
496
+ pass
497
+
498
+ # 1. compute alphas, betas
499
+ self.alphas_cumprod = self.alphas_cumprod.to(model_output.device)
500
+ alpha_prod_t = self.alphas_cumprod[t]
501
+ alpha_prod_t_prev = self.alphas_cumprod[torch.clip(prev_t, min=0)]
502
+ alpha_prod_t_prev[prev_t < 0] = torch.tensor(1.0)
503
+
504
+ beta_prod_t = 1 - alpha_prod_t
505
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
506
+ current_alpha_t = alpha_prod_t / alpha_prod_t_prev
507
+ current_beta_t = 1 - current_alpha_t
508
+
509
+ # 2. compute predicted original sample from predicted noise also called
510
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
511
+ if self.config.prediction_type == "epsilon":
512
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
513
+ elif self.config.prediction_type == "sample":
514
+ pred_original_sample = model_output
515
+ elif self.config.prediction_type == "v_prediction":
516
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
517
+ else:
518
+ raise ValueError(
519
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or"
520
+ " `v_prediction` for the DDPMParallelScheduler."
521
+ )
522
+
523
+ # 3. Clip or threshold "predicted x_0"
524
+ if self.config.thresholding:
525
+ pred_original_sample = self._threshold_sample(pred_original_sample)
526
+ elif self.config.clip_sample:
527
+ pred_original_sample = pred_original_sample.clamp(
528
+ -self.config.clip_sample_range, self.config.clip_sample_range
529
+ )
530
+
531
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
532
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
533
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * current_beta_t) / beta_prod_t
534
+ current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t
535
+
536
+ # 5. Compute predicted previous sample µ_t
537
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
538
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
539
+
540
+ return pred_prev_sample
541
+
542
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
543
+ def add_noise(
544
+ self,
545
+ original_samples: torch.FloatTensor,
546
+ noise: torch.FloatTensor,
547
+ timesteps: torch.IntTensor,
548
+ ) -> torch.FloatTensor:
549
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
550
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
551
+ timesteps = timesteps.to(original_samples.device)
552
+
553
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
554
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
555
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
556
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
557
+
558
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
559
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
560
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
561
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
562
+
563
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
564
+ return noisy_samples
565
+
566
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
567
+ def get_velocity(
568
+ self, sample: torch.FloatTensor, noise: torch.FloatTensor, timesteps: torch.IntTensor
569
+ ) -> torch.FloatTensor:
570
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
571
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
572
+ timesteps = timesteps.to(sample.device)
573
+
574
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
575
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
576
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
577
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
578
+
579
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
580
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
581
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
582
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
583
+
584
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
585
+ return velocity
586
+
587
+ def __len__(self):
588
+ return self.config.num_train_timesteps
589
+
590
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.previous_timestep
591
+ def previous_timestep(self, timestep):
592
+ if self.custom_timesteps:
593
+ index = (self.timesteps == timestep).nonzero(as_tuple=True)[0][0]
594
+ if index == self.timesteps.shape[0] - 1:
595
+ prev_t = torch.tensor(-1)
596
+ else:
597
+ prev_t = self.timesteps[index + 1]
598
+ else:
599
+ num_inference_steps = (
600
+ self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps
601
+ )
602
+ prev_t = timestep - self.config.num_train_timesteps // num_inference_steps
603
+
604
+ return prev_t