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