coralLight commited on
Commit
ddc7f94
·
1 Parent(s): 4146ea9

add inference

Browse files
Files changed (2) hide show
  1. app.py +54 -37
  2. customed_unipc_scheduler.py +986 -0
app.py CHANGED
@@ -30,6 +30,7 @@ from itertools import islice
30
  device = "cuda" if torch.cuda.is_available() else "cpu"
31
  model_repo_id = "Lykon/dreamshaper-xl-1-0" # Replace to the model you would like to use
32
  from sampler import UniPCSampler
 
33
 
34
  precision_scope = autocast
35
 
@@ -164,7 +165,7 @@ vae.to('cuda')
164
  pipe = StableDiffusionXLPipeline.from_pretrained("John6666/nova-anime-xl-il-v120-sdxl",torch_dtype=torch_dtype,vae=vae)
165
  # pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0",torch_dtype=torch.float16,vae=vae)
166
 
167
- pipe.to('cuda')
168
 
169
 
170
 
@@ -175,46 +176,62 @@ accelerator = accelerate.Accelerator()
175
 
176
  def generate_image_with_steps(prompt, negative_prompt, seed, width, height, guidance_scale, num_inference_steps):
177
  """Helper function to generate image with specific number of steps"""
 
 
 
 
 
178
  with torch.no_grad():
179
  with precision_scope("cuda"):
180
  prompts = [prompt]
181
- if num_inference_steps > 8:
182
- sampler = UniPCSampler(pipe,model_closure=model_closure
183
- , steps=num_inference_steps
184
- , guidance_scale=guidance_scale
185
- ,skip_type='time_uniform'
186
- ,force_not_use_afs=True)
187
- else:
188
- sampler = UniPCSampler(pipe,model_closure=model_closure
189
- , steps=num_inference_steps
190
- , guidance_scale=guidance_scale)
191
-
192
- c = prompts
193
- uc = ['(worst quality:2), (low quality:2), (normal quality:2), bad anatomy, bad proportions, poorly drawn face, poorly drawn hands, missing fingers, extra limbs, blurry, pixelated, distorted, lowres, jpeg artifacts, watermark, signature, text, (deformed:1.5), (bad hands:1.3), overexposed, underexposed, censored, mutated, extra fingers, cloned face, bad eyes'] * len(c) if guidance_scale != 1.0 else None
194
- shape = [4, width // 8, height // 8]
195
- # if opt.method == "dpm_solver_v3":
196
- # batch_size, shape, conditioning, x_T, unconditional_conditioning
197
- samples, _ = sampler.sample(
198
- conditioning=c,
199
- batch_size=1,
200
- shape=shape,
201
- unconditional_conditioning=uc,
202
- x_T=None,
203
- start_free_u_step=6 if num_inference_steps == 8 else 4 if num_inference_steps < 8 else None,
204
- xl_preprocess_closure = prepare_sdxl_pipeline_step_parameter,
205
- # npnet = npn_net,
206
- use_corrector=True,
207
  )
208
-
209
- x_samples = pipe.vae.decode(samples / pipe.vae.config.scaling_factor).sample
210
- x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0)
211
- x_samples = x_samples.cpu().permute(0, 2, 3, 1).numpy()
212
-
213
- x_image_torch = torch.from_numpy(x_samples).permute(0, 3, 1, 2) # need to pay attention
214
-
215
- for x_sample in x_image_torch:
216
- x_sample = 255.0 * rearrange(x_sample.cpu().numpy(), "c h w -> h w c")
217
- img = Image.fromarray(x_sample.astype(np.uint8))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  return img
219
 
220
  @spaces.GPU #[uncomment to use ZeroGPU]
 
30
  device = "cuda" if torch.cuda.is_available() else "cpu"
31
  model_repo_id = "Lykon/dreamshaper-xl-1-0" # Replace to the model you would like to use
32
  from sampler import UniPCSampler
33
+ from customed_unipc_scheduler import CustomedUniPCMultistepScheduler
34
 
35
  precision_scope = autocast
36
 
 
165
  pipe = StableDiffusionXLPipeline.from_pretrained("John6666/nova-anime-xl-il-v120-sdxl",torch_dtype=torch_dtype,vae=vae)
166
  # pipe = StableDiffusionXLPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0",torch_dtype=torch.float16,vae=vae)
167
 
168
+
169
 
170
 
171
 
 
176
 
177
  def generate_image_with_steps(prompt, negative_prompt, seed, width, height, guidance_scale, num_inference_steps):
178
  """Helper function to generate image with specific number of steps"""
179
+ scheduler = CustomedUniPCMultistepScheduler.from_config(pipe.scheduler.config
180
+ , solver_order = 2 if num_inference_steps==8 else 1
181
+ ,denoise_to_zero = False)
182
+ pipe.scheduler = scheduler
183
+ pipe.to('cuda')
184
  with torch.no_grad():
185
  with precision_scope("cuda"):
186
  prompts = [prompt]
187
+
188
+ latents = torch.randn(
189
+ (1, pipe.unet.config.in_channels, height // 8, width // 8),
190
+ device=device,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  )
192
+ latents = latents * pipe.scheduler.init_noise_sigma
193
+
194
+ pipe.scheduler.set_timesteps(num_inference_steps)
195
+ idx = 0
196
+ register_free_upblock2d(pipe, b1=1.0, b2=1.0, s1=1.0, s2=1.0)
197
+ register_free_crossattn_upblock2d(pipe, b1=1.0, b2=1.0, s1=1.0, s2=1.0)
198
+ for t in tqdm(pipe.scheduler.timesteps):
199
+ # Still not enough. I will tell you, what is the best implementation. Although not via the following code.
200
+
201
+ # if idx == len(pipe.scheduler.timesteps) - 1:
202
+ # break
203
+ if idx == -1:#(6 if num_inference_steps == 8 else 4):
204
+ register_free_upblock2d(pipe, b1=1.2, b2=1.2, s1=0.9, s2=0.9)
205
+ register_free_crossattn_upblock2d(pipe, b1=1.2, b2=1.2, s1=0.9, s2=0.9)
206
+ latent_model_input = torch.cat([latents] * 2)
207
+
208
+ latent_model_input = pipe.scheduler.scale_model_input(latent_model_input , timestep=t)
209
+ negative_prompts = '(worst quality:2), (low quality:2), (normal quality:2), bad anatomy, bad proportions, poorly drawn face, poorly drawn hands, missing fingers, extra limbs, blurry, pixelated, distorted, lowres, jpeg artifacts, watermark, signature, text, (deformed:1.5), (bad hands:1.3), overexposed, underexposed, censored, mutated, extra fingers, cloned face, bad eyes'
210
+ negative_prompts = 1 * [negative_prompts]
211
+
212
+ prompt_embeds, cond_kwargs = prepare_sdxl_pipeline_step_parameter(pipe
213
+ , prompts
214
+ , need_cfg=True
215
+ , device=pipe.device
216
+ , negative_prompt=negative_prompts
217
+ , W=width
218
+ , H=height)
219
+ noise_pred = pipe.unet(latent_model_input
220
+ , t
221
+ , encoder_hidden_states=prompt_embeds.to(device=latents.device, dtype=latents.dtype)
222
+ , added_cond_kwargs=cond_kwargs).sample
223
+ uncond, cond = noise_pred.chunk(2)
224
+ noise_pred = uncond + (cond - uncond) * guidance_scale
225
+ latents = pipe.scheduler.step(noise_pred, t, latents).prev_sample
226
+ idx += 1
227
+
228
+ x_samples_ddim = pipe.vae.decode(latents / pipe.vae.config.scaling_factor).sample
229
+ x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
230
+ if True:
231
+ for x_sample in x_samples_ddim:
232
+ # x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
233
+ x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
234
+ img = Image.fromarray(x_sample.astype(np.uint8))
235
  return img
236
 
237
  @spaces.GPU #[uncomment to use ZeroGPU]
customed_unipc_scheduler.py ADDED
@@ -0,0 +1,986 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 TSAIL Team 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: check https://huggingface.co/papers/2302.04867 and https://github.com/wl-zhao/UniPC for more info
16
+ # The codebase is modified based on https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ import copy
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.utils import deprecate, is_scipy_available
27
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
28
+
29
+ if is_scipy_available():
30
+ import scipy.stats
31
+
32
+
33
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
34
+ def betas_for_alpha_bar(
35
+ num_diffusion_timesteps,
36
+ max_beta=0.999,
37
+ alpha_transform_type="cosine",
38
+ ):
39
+ """
40
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
41
+ (1-beta) over time from t = [0,1].
42
+
43
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
44
+ to that part of the diffusion process.
45
+
46
+
47
+ Args:
48
+ num_diffusion_timesteps (`int`): the number of betas to produce.
49
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
50
+ prevent singularities.
51
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
52
+ Choose from `cosine` or `exp`
53
+
54
+ Returns:
55
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
56
+ """
57
+ if alpha_transform_type == "cosine":
58
+
59
+ def alpha_bar_fn(t):
60
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
61
+
62
+ elif alpha_transform_type == "exp":
63
+
64
+ def alpha_bar_fn(t):
65
+ return math.exp(t * -12.0)
66
+
67
+ else:
68
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
69
+
70
+ betas = []
71
+ for i in range(num_diffusion_timesteps):
72
+ t1 = i / num_diffusion_timesteps
73
+ t2 = (i + 1) / num_diffusion_timesteps
74
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
75
+ return torch.tensor(betas, dtype=torch.float32)
76
+
77
+
78
+
79
+ # Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
80
+ def rescale_zero_terminal_snr(betas):
81
+ """
82
+ Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)
83
+
84
+
85
+ Args:
86
+ betas (`torch.Tensor`):
87
+ the betas that the scheduler is being initialized with.
88
+
89
+ Returns:
90
+ `torch.Tensor`: rescaled betas with zero terminal SNR
91
+ """
92
+ # Convert betas to alphas_bar_sqrt
93
+ alphas = 1.0 - betas
94
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
95
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
96
+
97
+ # Store old values.
98
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
99
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
100
+
101
+ # Shift so the last timestep is zero.
102
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
103
+
104
+ # Scale so the first timestep is back to the old value.
105
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
106
+
107
+ # Convert alphas_bar_sqrt to betas
108
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
109
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
110
+ alphas = torch.cat([alphas_bar[0:1], alphas])
111
+ betas = 1 - alphas
112
+
113
+ return betas
114
+
115
+
116
+ class CustomedUniPCMultistepScheduler(SchedulerMixin, ConfigMixin):
117
+ """
118
+ `UniPCMultistepScheduler` is a training-free framework designed for the fast sampling of diffusion models.
119
+
120
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
121
+ methods the library implements for all schedulers such as loading and saving.
122
+
123
+ Args:
124
+ num_train_timesteps (`int`, defaults to 1000):
125
+ The number of diffusion steps to train the model.
126
+ beta_start (`float`, defaults to 0.0001):
127
+ The starting `beta` value of inference.
128
+ beta_end (`float`, defaults to 0.02):
129
+ The final `beta` value.
130
+ beta_schedule (`str`, defaults to `"linear"`):
131
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
132
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
133
+ trained_betas (`np.ndarray`, *optional*):
134
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
135
+ solver_order (`int`, default `2`):
136
+ The UniPC order which can be any positive integer. The effective order of accuracy is `solver_order + 1`
137
+ due to the UniC. It is recommended to use `solver_order=2` for guided sampling, and `solver_order=3` for
138
+ unconditional sampling.
139
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
140
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
141
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
142
+ Video](https://imagen.research.google/video/paper.pdf) paper).
143
+ thresholding (`bool`, defaults to `False`):
144
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
145
+ as Stable Diffusion.
146
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
147
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
148
+ sample_max_value (`float`, defaults to 1.0):
149
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and `predict_x0=True`.
150
+ predict_x0 (`bool`, defaults to `True`):
151
+ Whether to use the updating algorithm on the predicted x0.
152
+ solver_type (`str`, default `bh2`):
153
+ Solver type for UniPC. It is recommended to use `bh1` for unconditional sampling when steps < 10, and `bh2`
154
+ otherwise.
155
+ lower_order_final (`bool`, default `True`):
156
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
157
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
158
+ disable_corrector (`list`, default `[]`):
159
+ Decides which step to disable the corrector to mitigate the misalignment between `epsilon_theta(x_t, c)`
160
+ and `epsilon_theta(x_t^c, c)` which can influence convergence for a large guidance scale. Corrector is
161
+ usually disabled during the first few steps.
162
+ solver_p (`SchedulerMixin`, default `None`):
163
+ Any other scheduler that if specified, the algorithm becomes `solver_p + UniC`.
164
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
165
+ Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
166
+ the sigmas are determined according to a sequence of noise levels {σi}.
167
+ use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
168
+ Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
169
+ use_beta_sigmas (`bool`, *optional*, defaults to `False`):
170
+ Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
171
+ Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
172
+ timestep_spacing (`str`, defaults to `"linspace"`):
173
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
174
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
175
+ steps_offset (`int`, defaults to 0):
176
+ An offset added to the inference steps, as required by some model families.
177
+ final_sigmas_type (`str`, defaults to `"zero"`):
178
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
179
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
180
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
181
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
182
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
183
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
184
+ """
185
+
186
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
187
+ order = 1
188
+
189
+ @register_to_config
190
+ def __init__(
191
+ self,
192
+ num_train_timesteps: int = 1000,
193
+ beta_start: float = 0.0001,
194
+ beta_end: float = 0.02,
195
+ beta_schedule: str = "linear",
196
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
197
+ solver_order: int = 2,
198
+ prediction_type: str = "epsilon",
199
+ thresholding: bool = False,
200
+ dynamic_thresholding_ratio: float = 0.995,
201
+ sample_max_value: float = 1.0,
202
+ predict_x0: bool = True,
203
+ solver_type: str = "bh2",
204
+ lower_order_final: bool = True,
205
+ disable_corrector: List[int] = [],
206
+ solver_p: SchedulerMixin = None,
207
+ use_karras_sigmas: Optional[bool] = False,
208
+ use_exponential_sigmas: Optional[bool] = False,
209
+ use_beta_sigmas: Optional[bool] = False,
210
+ use_flow_sigmas: Optional[bool] = False,
211
+ flow_shift: Optional[float] = 1.0,
212
+ timestep_spacing: str = "linspace",
213
+ steps_offset: int = 0,
214
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
215
+ skip_type: str = "customed_time_karras",
216
+ denoise_to_zero: bool = False,
217
+ rescale_betas_zero_snr: bool = False,
218
+ ):
219
+
220
+ if self.config.use_beta_sigmas and not is_scipy_available():
221
+ raise ImportError("Make sure to install scipy if you want to use beta sigmas.")
222
+ if sum([self.config.use_beta_sigmas, self.config.use_exponential_sigmas, self.config.use_karras_sigmas]) > 1:
223
+ raise ValueError(
224
+ "Only one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used."
225
+ )
226
+ if trained_betas is not None:
227
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
228
+ elif beta_schedule == "linear":
229
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
230
+ elif beta_schedule == "scaled_linear":
231
+ # this schedule is very specific to the latent diffusion model.
232
+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
233
+ elif beta_schedule == "squaredcos_cap_v2":
234
+ # Glide cosine schedule
235
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
236
+ else:
237
+ raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
238
+
239
+ self.skip_type = skip_type
240
+ self.denoise_to_zero = denoise_to_zero
241
+ if rescale_betas_zero_snr:
242
+ self.betas = rescale_zero_terminal_snr(self.betas)
243
+
244
+ self.alphas = 1.0 - self.betas
245
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
246
+
247
+ if rescale_betas_zero_snr:
248
+ # Close to 0 without being 0 so first sigma is not inf
249
+ # FP16 smallest positive subnormal works well here
250
+ self.alphas_cumprod[-1] = 2**-24
251
+
252
+ # Currently we only support VP-type noise schedule
253
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
254
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
255
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
256
+ self.sigmas = ((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5
257
+
258
+ # standard deviation of the initial noise distribution
259
+ self.init_noise_sigma = 1.0
260
+
261
+ if solver_type not in ["bh1", "bh2"]:
262
+ if solver_type in ["midpoint", "heun", "logrho"]:
263
+ self.register_to_config(solver_type="bh2")
264
+ else:
265
+ raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
266
+
267
+ self.predict_x0 = predict_x0
268
+ # setable values
269
+ self.num_inference_steps = None
270
+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
271
+ self.timesteps = torch.from_numpy(timesteps)
272
+ self.model_outputs = [None] * solver_order
273
+ self.timestep_list = [None] * solver_order
274
+ self.solver_order = solver_order
275
+ self.lower_order_nums = 0
276
+ self.disable_corrector = disable_corrector
277
+ self.solver_p = solver_p
278
+ self.last_sample = None
279
+ self._step_index = None
280
+ self._begin_index = None
281
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
282
+
283
+ @property
284
+ def step_index(self):
285
+ """
286
+ The index counter for current timestep. It will increase 1 after each scheduler step.
287
+ """
288
+ return self._step_index
289
+
290
+ @property
291
+ def begin_index(self):
292
+ """
293
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
294
+ """
295
+ return self._begin_index
296
+
297
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
298
+ def set_begin_index(self, begin_index: int = 0):
299
+ """
300
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
301
+
302
+ Args:
303
+ begin_index (`int`):
304
+ The begin index for the scheduler.
305
+ """
306
+ self._begin_index = begin_index
307
+
308
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
309
+ """
310
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
311
+
312
+ Args:
313
+ num_inference_steps (`int`):
314
+ The number of diffusion steps used when generating samples with a pre-trained model.
315
+ device (`str` or `torch.device`, *optional*):
316
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
317
+ """
318
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://huggingface.co/papers/2305.08891
319
+
320
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
321
+ if self.skip_type == "customed_time_karras":
322
+ sigma_T = sigmas[-1]
323
+ sigma_0 = sigmas[0]
324
+ N = num_inference_steps
325
+ if N == 9:
326
+ log_sigmas = np.log(sigmas)
327
+ sigmas = self.get_sigmas_karras(12, sigma_0, sigma_T, rho=7.0)
328
+ ct_start = self._sigma_to_t(sigmas[0], log_sigmas)
329
+ ct_end = self._sigma_to_t(sigmas[9], log_sigmas)
330
+ if self.denoise_to_zero:
331
+ ct_real_end = self._sigma_to_t(sigmas[-1], log_sigmas)
332
+ timesteps = self.get_sigmas_karras(9, ct_end, ct_start,rho=1.2, customed_final_sigma= ct_real_end if self.denoise_to_zero else None)
333
+ elif N == 5:
334
+ log_sigmas = np.log(sigmas)
335
+ sigmas = self.get_sigmas_karras(8, sigma_0, sigma_T, rho=5.0)
336
+ ct_start = self._sigma_to_t(sigmas[0], log_sigmas)
337
+ ct_end = self._sigma_to_t(sigmas[6], log_sigmas)
338
+ if self.denoise_to_zero:
339
+ ct_real_end = self._sigma_to_t(sigmas[-1], log_sigmas)
340
+ timesteps = self.get_sigmas_karras(5, ct_end, ct_start,rho=1.2, customed_final_sigma= ct_real_end if self.denoise_to_zero else None)
341
+ elif N == 6:
342
+ log_sigmas = np.log(sigmas)
343
+ sigmas = self.get_sigmas_karras(8, sigma_0, sigma_T, rho=5.0)
344
+ ct_start = self._sigma_to_t(sigmas[0], log_sigmas)
345
+ ct_end = self._sigma_to_t(sigmas[6], log_sigmas)
346
+ if self.denoise_to_zero:
347
+ ct_real_end = self._sigma_to_t(sigmas[-1], log_sigmas)
348
+ timesteps = self.get_sigmas_karras(6, ct_end, ct_start,rho=1.2, customed_final_sigma= ct_real_end if self.denoise_to_zero else None)
349
+ elif N == 7:
350
+ log_sigmas = np.log(sigmas)
351
+ sigmas = self.get_sigmas_karras(8, sigma_0, sigma_T, rho=5.0)
352
+ ct_start = self._sigma_to_t(sigmas[0], log_sigmas)
353
+ ct_end = self._sigma_to_t(sigmas[6], log_sigmas)
354
+ if self.denoise_to_zero:
355
+ ct_real_end = self._sigma_to_t(sigmas[-1], log_sigmas)
356
+ timesteps = self.get_sigmas_karras(7, ct_end, ct_start,rho=1.2, customed_final_sigma= ct_real_end if self.denoise_to_zero else None)
357
+ elif N == 8:
358
+ log_sigmas = np.log(sigmas).copy()
359
+ sigmas = self.get_sigmas_karras(8, sigma_0, sigma_T, rho=5.0)
360
+ ct_start = self._sigma_to_t(sigmas[0], log_sigmas)
361
+ ct_end = self._sigma_to_t(sigmas[6], log_sigmas)
362
+ if self.denoise_to_zero:
363
+ ct_real_end = self._sigma_to_t(sigmas[-1], log_sigmas)
364
+ timesteps = self.get_sigmas_karras(8, ct_end, ct_start,rho=1.2, customed_final_sigma= ct_real_end if self.denoise_to_zero else None)
365
+ timesteps_tmp = copy.deepcopy(timesteps)
366
+ timesteps_tmp = np.append(timesteps_tmp, self._sigma_to_t(sigmas[-1], log_sigmas))
367
+ sigmas = np.array([self._t_to_sigma(t, log_sigmas) for t in timesteps_tmp])
368
+
369
+ self.sigmas = torch.from_numpy(sigmas)
370
+ self.timesteps = torch.from_numpy(timesteps).to(device=device)
371
+
372
+ self.num_inference_steps = len(timesteps)
373
+
374
+ self.model_outputs = [
375
+ None,
376
+ ] * self.solver_order
377
+ self.lower_order_nums = 0
378
+ self.last_sample = None
379
+ if self.solver_p:
380
+ self.solver_p.set_timesteps(self.num_inference_steps, device=device)
381
+
382
+ # add an index counter for schedulers that allow duplicated timesteps
383
+ self._step_index = None
384
+ self._begin_index = None
385
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
386
+
387
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
388
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
389
+ """
390
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
391
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
392
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
393
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
394
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
395
+
396
+ https://huggingface.co/papers/2205.11487
397
+ """
398
+ dtype = sample.dtype
399
+ batch_size, channels, *remaining_dims = sample.shape
400
+
401
+ if dtype not in (torch.float32, torch.float64):
402
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
403
+
404
+ # Flatten sample for doing quantile calculation along each image
405
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
406
+
407
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
408
+
409
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
410
+ s = torch.clamp(
411
+ s, min=1, max=self.config.sample_max_value
412
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
413
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
414
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
415
+
416
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
417
+ sample = sample.to(dtype)
418
+
419
+ return sample
420
+
421
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
422
+ def _sigma_to_t(self, sigma, log_sigmas):
423
+ # get log sigma
424
+ log_sigma = np.log(np.maximum(sigma, 1e-10))
425
+
426
+ # get distribution
427
+ dists = log_sigma - log_sigmas[:, np.newaxis]
428
+
429
+ # get sigmas range
430
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
431
+ high_idx = low_idx + 1
432
+
433
+ low = log_sigmas[low_idx]
434
+ high = log_sigmas[high_idx]
435
+
436
+ # interpolate sigmas
437
+ w = (low - log_sigma) / (low - high)
438
+ w = np.clip(w, 0, 1)
439
+
440
+ # transform interpolation to time range
441
+ t = (1 - w) * low_idx + w * high_idx
442
+ t = t.reshape(sigma.shape)
443
+ return t
444
+
445
+ def _t_to_sigma(self, t, log_sigmas):
446
+ # t = t
447
+ low_idx, high_idx, w = np.int64(np.floor(t)), np.int64(np.ceil(t)), t - np.floor(t)
448
+ log_sigma = (1 - w) * log_sigmas[low_idx] + w * log_sigmas[high_idx]
449
+ return np.exp(log_sigma)
450
+
451
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t
452
+ def _sigma_to_alpha_sigma_t(self, sigma):
453
+ if self.config.use_flow_sigmas:
454
+ alpha_t = 1 - sigma
455
+ sigma_t = sigma
456
+ else:
457
+ alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
458
+ sigma_t = sigma * alpha_t
459
+
460
+ return alpha_t, sigma_t
461
+
462
+ def get_sigmas_karras(self, n, in_sigma_min: torch.Tensor, in_sigma_max: torch.Tensor, rho=7., customed_final_sigma = None) -> torch.Tensor:
463
+ """Constructs the noise schedule of Karras et al. (2022)."""
464
+ if hasattr(self.config, "sigma_min"):
465
+ sigma_min = self.config.sigma_min
466
+ else:
467
+ sigma_min = in_sigma_min.item()
468
+
469
+ if hasattr(self.config, "sigma_max"):
470
+ sigma_max = self.config.sigma_max
471
+ else:
472
+ sigma_max = in_sigma_max.item()
473
+
474
+ ramp = np.linspace(0, 1, n)
475
+ min_inv_rho = sigma_min ** (1 / rho)
476
+ max_inv_rho = sigma_max ** (1 / rho)
477
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
478
+ if customed_final_sigma is not None :
479
+ sigmas[-1] = customed_final_sigma
480
+ return sigmas
481
+
482
+ def convert_model_output(
483
+ self,
484
+ model_output: torch.Tensor,
485
+ *args,
486
+ sample: torch.Tensor = None,
487
+ **kwargs,
488
+ ) -> torch.Tensor:
489
+ r"""
490
+ Convert the model output to the corresponding type the UniPC algorithm needs.
491
+
492
+ Args:
493
+ model_output (`torch.Tensor`):
494
+ The direct output from the learned diffusion model.
495
+ timestep (`int`):
496
+ The current discrete timestep in the diffusion chain.
497
+ sample (`torch.Tensor`):
498
+ A current instance of a sample created by the diffusion process.
499
+
500
+ Returns:
501
+ `torch.Tensor`:
502
+ The converted model output.
503
+ """
504
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
505
+ if sample is None:
506
+ if len(args) > 1:
507
+ sample = args[1]
508
+ else:
509
+ raise ValueError("missing `sample` as a required keyword argument")
510
+ if timestep is not None:
511
+ deprecate(
512
+ "timesteps",
513
+ "1.0.0",
514
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
515
+ )
516
+
517
+ sigma = self.sigmas[self.step_index]
518
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
519
+
520
+ if self.predict_x0:
521
+ if self.config.prediction_type == "epsilon":
522
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
523
+ elif self.config.prediction_type == "sample":
524
+ x0_pred = model_output
525
+ elif self.config.prediction_type == "v_prediction":
526
+ x0_pred = alpha_t * sample - sigma_t * model_output
527
+ elif self.config.prediction_type == "flow_prediction":
528
+ sigma_t = self.sigmas[self.step_index]
529
+ x0_pred = sample - sigma_t * model_output
530
+ else:
531
+ raise ValueError(
532
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, "
533
+ "`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler."
534
+ )
535
+
536
+ if self.config.thresholding:
537
+ x0_pred = self._threshold_sample(x0_pred)
538
+
539
+ return x0_pred
540
+ else:
541
+ if self.config.prediction_type == "epsilon":
542
+ return model_output
543
+ elif self.config.prediction_type == "sample":
544
+ epsilon = (sample - alpha_t * model_output) / sigma_t
545
+ return epsilon
546
+ elif self.config.prediction_type == "v_prediction":
547
+ epsilon = alpha_t * model_output + sigma_t * sample
548
+ return epsilon
549
+ else:
550
+ raise ValueError(
551
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
552
+ " `v_prediction` for the UniPCMultistepScheduler."
553
+ )
554
+
555
+ def multistep_uni_p_bh_update(
556
+ self,
557
+ model_output: torch.Tensor,
558
+ *args,
559
+ sample: torch.Tensor = None,
560
+ order: int = None,
561
+ **kwargs,
562
+ ) -> torch.Tensor:
563
+ """
564
+ One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
565
+
566
+ Args:
567
+ model_output (`torch.Tensor`):
568
+ The direct output from the learned diffusion model at the current timestep.
569
+ prev_timestep (`int`):
570
+ The previous discrete timestep in the diffusion chain.
571
+ sample (`torch.Tensor`):
572
+ A current instance of a sample created by the diffusion process.
573
+ order (`int`):
574
+ The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
575
+
576
+ Returns:
577
+ `torch.Tensor`:
578
+ The sample tensor at the previous timestep.
579
+ """
580
+ prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None)
581
+ if sample is None:
582
+ if len(args) > 1:
583
+ sample = args[1]
584
+ else:
585
+ raise ValueError("missing `sample` as a required keyword argument")
586
+ if order is None:
587
+ if len(args) > 2:
588
+ order = args[2]
589
+ else:
590
+ raise ValueError("missing `order` as a required keyword argument")
591
+ if prev_timestep is not None:
592
+ deprecate(
593
+ "prev_timestep",
594
+ "1.0.0",
595
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
596
+ )
597
+ model_output_list = self.model_outputs
598
+
599
+ s0 = self.timestep_list[-1]
600
+ m0 = model_output_list[-1]
601
+ x = sample
602
+
603
+ if self.solver_p:
604
+ x_t = self.solver_p.step(model_output, s0, x).prev_sample
605
+ return x_t
606
+
607
+ sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
608
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
609
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
610
+
611
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
612
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
613
+
614
+ h = lambda_t - lambda_s0
615
+ device = sample.device
616
+
617
+ rks = []
618
+ D1s = []
619
+ for i in range(1, order):
620
+ si = self.step_index - i
621
+ mi = model_output_list[-(i + 1)]
622
+ alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
623
+ lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
624
+ rk = (lambda_si - lambda_s0) / h
625
+ rks.append(rk)
626
+ D1s.append((mi - m0) / rk)
627
+
628
+ rks.append(1.0)
629
+ rks = torch.tensor(rks, device=device)
630
+
631
+ R = []
632
+ b = []
633
+
634
+ hh = -h if self.predict_x0 else h
635
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
636
+ h_phi_k = h_phi_1 / hh - 1
637
+
638
+ factorial_i = 1
639
+
640
+ if self.config.solver_type == "bh1":
641
+ B_h = hh
642
+ elif self.config.solver_type == "bh2":
643
+ B_h = torch.expm1(hh)
644
+ else:
645
+ raise NotImplementedError()
646
+
647
+ for i in range(1, order + 1):
648
+ R.append(torch.pow(rks, i - 1))
649
+ b.append(h_phi_k * factorial_i / B_h)
650
+ factorial_i *= i + 1
651
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
652
+
653
+ R = torch.stack(R)
654
+ b = torch.tensor(b, device=device)
655
+
656
+ if len(D1s) > 0:
657
+ D1s = torch.stack(D1s, dim=1) # (B, K)
658
+ # for order 2, we use a simplified version
659
+ if order == 2:
660
+ rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
661
+ else:
662
+ rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype)
663
+ else:
664
+ D1s = None
665
+
666
+ if self.predict_x0:
667
+ x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
668
+ if D1s is not None:
669
+ pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
670
+ else:
671
+ pred_res = 0
672
+ x_t = x_t_ - alpha_t * B_h * pred_res
673
+ else:
674
+ x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
675
+ if D1s is not None:
676
+ pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
677
+ else:
678
+ pred_res = 0
679
+ x_t = x_t_ - sigma_t * B_h * pred_res
680
+
681
+ x_t = x_t.to(x.dtype)
682
+ return x_t
683
+
684
+ def multistep_uni_c_bh_update(
685
+ self,
686
+ this_model_output: torch.Tensor,
687
+ *args,
688
+ last_sample: torch.Tensor = None,
689
+ this_sample: torch.Tensor = None,
690
+ order: int = None,
691
+ **kwargs,
692
+ ) -> torch.Tensor:
693
+ """
694
+ One step for the UniC (B(h) version).
695
+
696
+ Args:
697
+ this_model_output (`torch.Tensor`):
698
+ The model outputs at `x_t`.
699
+ this_timestep (`int`):
700
+ The current timestep `t`.
701
+ last_sample (`torch.Tensor`):
702
+ The generated sample before the last predictor `x_{t-1}`.
703
+ this_sample (`torch.Tensor`):
704
+ The generated sample after the last predictor `x_{t}`.
705
+ order (`int`):
706
+ The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
707
+
708
+ Returns:
709
+ `torch.Tensor`:
710
+ The corrected sample tensor at the current timestep.
711
+ """
712
+ this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None)
713
+ if last_sample is None:
714
+ if len(args) > 1:
715
+ last_sample = args[1]
716
+ else:
717
+ raise ValueError("missing `last_sample` as a required keyword argument")
718
+ if this_sample is None:
719
+ if len(args) > 2:
720
+ this_sample = args[2]
721
+ else:
722
+ raise ValueError("missing `this_sample` as a required keyword argument")
723
+ if order is None:
724
+ if len(args) > 3:
725
+ order = args[3]
726
+ else:
727
+ raise ValueError("missing `order` as a required keyword argument")
728
+ if this_timestep is not None:
729
+ deprecate(
730
+ "this_timestep",
731
+ "1.0.0",
732
+ "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
733
+ )
734
+
735
+ model_output_list = self.model_outputs
736
+
737
+ m0 = model_output_list[-1]
738
+ x = last_sample
739
+ x_t = this_sample
740
+ model_t = this_model_output
741
+
742
+ sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1]
743
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
744
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
745
+
746
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
747
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
748
+
749
+ h = lambda_t - lambda_s0
750
+ device = this_sample.device
751
+
752
+ rks = []
753
+ D1s = []
754
+ for i in range(1, order):
755
+ si = self.step_index - (i + 1)
756
+ mi = model_output_list[-(i + 1)]
757
+ alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
758
+ lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
759
+ rk = (lambda_si - lambda_s0) / h
760
+ rks.append(rk)
761
+ D1s.append((mi - m0) / rk)
762
+
763
+ rks.append(1.0)
764
+ rks = torch.tensor(rks, device=device)
765
+
766
+ R = []
767
+ b = []
768
+
769
+ hh = -h if self.predict_x0 else h
770
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
771
+ h_phi_k = h_phi_1 / hh - 1
772
+
773
+ factorial_i = 1
774
+
775
+ if self.config.solver_type == "bh1":
776
+ B_h = hh
777
+ elif self.config.solver_type == "bh2":
778
+ B_h = torch.expm1(hh)
779
+ else:
780
+ raise NotImplementedError()
781
+
782
+ for i in range(1, order + 1):
783
+ R.append(torch.pow(rks, i - 1))
784
+ b.append(h_phi_k * factorial_i / B_h)
785
+ factorial_i *= i + 1
786
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
787
+
788
+ R = torch.stack(R)
789
+ b = torch.tensor(b, device=device)
790
+
791
+ if len(D1s) > 0:
792
+ D1s = torch.stack(D1s, dim=1)
793
+ else:
794
+ D1s = None
795
+
796
+ # for order 1, we use a simplified version
797
+ if order == 1:
798
+ rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
799
+ else:
800
+ rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
801
+
802
+ if self.predict_x0:
803
+ x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
804
+ if D1s is not None:
805
+ corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
806
+ else:
807
+ corr_res = 0
808
+ D1_t = model_t - m0
809
+ x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
810
+ else:
811
+ x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
812
+ if D1s is not None:
813
+ corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
814
+ else:
815
+ corr_res = 0
816
+ D1_t = model_t - m0
817
+ x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
818
+ x_t = x_t.to(x.dtype)
819
+ return x_t
820
+
821
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.index_for_timestep
822
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
823
+ if schedule_timesteps is None:
824
+ schedule_timesteps = self.timesteps
825
+
826
+ index_candidates = (schedule_timesteps == timestep).nonzero()
827
+
828
+ if len(index_candidates) == 0:
829
+ step_index = len(self.timesteps) - 1
830
+ # The sigma index that is taken for the **very** first `step`
831
+ # is always the second index (or the last index if there is only 1)
832
+ # This way we can ensure we don't accidentally skip a sigma in
833
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
834
+ elif len(index_candidates) > 1:
835
+ step_index = index_candidates[1].item()
836
+ else:
837
+ step_index = index_candidates[0].item()
838
+
839
+ return step_index
840
+
841
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
842
+ def _init_step_index(self, timestep):
843
+ """
844
+ Initialize the step_index counter for the scheduler.
845
+ """
846
+
847
+ if self.begin_index is None:
848
+ if isinstance(timestep, torch.Tensor):
849
+ timestep = timestep.to(self.timesteps.device)
850
+ self._step_index = self.index_for_timestep(timestep)
851
+ else:
852
+ self._step_index = self._begin_index
853
+
854
+ def step(
855
+ self,
856
+ model_output: torch.Tensor,
857
+ timestep: Union[int, torch.Tensor],
858
+ sample: torch.Tensor,
859
+ return_dict: bool = True,
860
+ ) -> Union[SchedulerOutput, Tuple]:
861
+ """
862
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
863
+ the multistep UniPC.
864
+
865
+ Args:
866
+ model_output (`torch.Tensor`):
867
+ The direct output from learned diffusion model.
868
+ timestep (`int`):
869
+ The current discrete timestep in the diffusion chain.
870
+ sample (`torch.Tensor`):
871
+ A current instance of a sample created by the diffusion process.
872
+ return_dict (`bool`):
873
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
874
+
875
+ Returns:
876
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
877
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
878
+ tuple is returned where the first element is the sample tensor.
879
+
880
+ """
881
+ if self.num_inference_steps is None:
882
+ raise ValueError(
883
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
884
+ )
885
+
886
+ if self.step_index is None:
887
+ self._init_step_index(timestep) # I remember is this part prevent us directly customed the discrete method
888
+
889
+ use_corrector = (
890
+ self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None
891
+ )
892
+
893
+ model_output_convert = self.convert_model_output(model_output, sample=sample)
894
+ if use_corrector:
895
+ sample = self.multistep_uni_c_bh_update(
896
+ this_model_output=model_output_convert,
897
+ last_sample=self.last_sample,
898
+ this_sample=sample,
899
+ order=self.this_order,
900
+ )
901
+
902
+ for i in range(self.solver_order - 1):
903
+ self.model_outputs[i] = self.model_outputs[i + 1]
904
+ self.timestep_list[i] = self.timestep_list[i + 1]
905
+
906
+ self.model_outputs[-1] = model_output_convert
907
+ self.timestep_list[-1] = timestep
908
+
909
+ if self.config.lower_order_final:
910
+ this_order = min(self.solver_order, len(self.timesteps) - self.step_index)
911
+ else:
912
+ this_order = self.solver_order
913
+
914
+ self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
915
+ assert self.this_order > 0
916
+
917
+ self.last_sample = sample
918
+ prev_sample = self.multistep_uni_p_bh_update(
919
+ model_output=model_output, # pass the original non-converted model output, in case solver-p is used
920
+ sample=sample,
921
+ order=self.this_order,
922
+ )
923
+
924
+ if self.lower_order_nums < self.solver_order:
925
+ self.lower_order_nums += 1
926
+
927
+ # upon completion increase step index by one
928
+ self._step_index += 1
929
+
930
+ if not return_dict:
931
+ return (prev_sample,)
932
+
933
+ return SchedulerOutput(prev_sample=prev_sample)
934
+
935
+ def scale_model_input(self, sample: torch.Tensor, *args, **kwargs) -> torch.Tensor:
936
+ """
937
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
938
+ current timestep.
939
+
940
+ Args:
941
+ sample (`torch.Tensor`):
942
+ The input sample.
943
+
944
+ Returns:
945
+ `torch.Tensor`:
946
+ A scaled input sample.
947
+ """
948
+ return sample
949
+
950
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.add_noise
951
+ def add_noise(
952
+ self,
953
+ original_samples: torch.Tensor,
954
+ noise: torch.Tensor,
955
+ timesteps: torch.IntTensor,
956
+ ) -> torch.Tensor:
957
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
958
+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
959
+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
960
+ # mps does not support float64
961
+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
962
+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
963
+ else:
964
+ schedule_timesteps = self.timesteps.to(original_samples.device)
965
+ timesteps = timesteps.to(original_samples.device)
966
+
967
+ # begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index
968
+ if self.begin_index is None:
969
+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]
970
+ elif self.step_index is not None:
971
+ # add_noise is called after first denoising step (for inpainting)
972
+ step_indices = [self.step_index] * timesteps.shape[0]
973
+ else:
974
+ # add noise is called before first denoising step to create initial latent(img2img)
975
+ step_indices = [self.begin_index] * timesteps.shape[0]
976
+
977
+ sigma = sigmas[step_indices].flatten()
978
+ while len(sigma.shape) < len(original_samples.shape):
979
+ sigma = sigma.unsqueeze(-1)
980
+
981
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
982
+ noisy_samples = alpha_t * original_samples + sigma_t * noise
983
+ return noisy_samples
984
+
985
+ def __len__(self):
986
+ return self.config.num_train_timesteps