Skip to content

Commit 1be91a0

Browse files
authored
Merge branch 'main' into add-joyimage-edit-plus
2 parents 5a831a3 + 570b6a7 commit 1be91a0

1 file changed

Lines changed: 66 additions & 27 deletions

File tree

src/diffusers/schedulers/scheduling_lcm.py

Lines changed: 66 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ class LCMSchedulerOutput(BaseOutput):
4040
prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
4141
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
4242
denoising loop.
43-
pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
44-
The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
45-
`pred_original_sample` can be used to preview progress or for guidance.
43+
denoised (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images, *optional*):
44+
The predicted denoised sample `(x_{0})` based on the model output from the current timestep. `denoised` can
45+
be used to preview progress or for guidance.
4646
"""
4747

4848
prev_sample: torch.Tensor
@@ -150,45 +150,45 @@ class LCMScheduler(SchedulerMixin, ConfigMixin):
150150
functionality via the [`SchedulerMixin.save_pretrained`] and [`~SchedulerMixin.from_pretrained`] functions.
151151
152152
Args:
153-
num_train_timesteps (`int`, defaults to 1000):
153+
num_train_timesteps (`int`, defaults to `1000`):
154154
The number of diffusion steps to train the model.
155-
beta_start (`float`, defaults to 0.0001):
155+
beta_start (`float`, defaults to `0.00085`):
156156
The starting `beta` value of inference.
157-
beta_end (`float`, defaults to 0.02):
157+
beta_end (`float`, defaults to `0.012`):
158158
The final `beta` value.
159-
beta_schedule (`str`, defaults to `"linear"`):
159+
beta_schedule (`str`, defaults to `"scaled_linear"`):
160160
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
161161
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
162-
trained_betas (`np.ndarray`, *optional*):
162+
trained_betas (`np.ndarray` or `list[float]`, *optional*):
163163
Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
164-
original_inference_steps (`int`, *optional*, defaults to 50):
164+
original_inference_steps (`int`, defaults to `50`):
165165
The default number of inference steps used to generate a linearly-spaced timestep schedule, from which we
166166
will ultimately take `num_inference_steps` evenly spaced timesteps to form the final timestep schedule.
167-
clip_sample (`bool`, defaults to `True`):
167+
clip_sample (`bool`, defaults to `False`):
168168
Clip the predicted sample for numerical stability.
169-
clip_sample_range (`float`, defaults to 1.0):
169+
clip_sample_range (`float`, defaults to `1.0`):
170170
The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
171171
set_alpha_to_one (`bool`, defaults to `True`):
172172
Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
173173
there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
174174
otherwise it uses the alpha value at step 0.
175-
steps_offset (`int`, defaults to 0):
175+
steps_offset (`int`, defaults to `0`):
176176
An offset added to the inference steps, as required by some model families.
177-
prediction_type (`str`, defaults to `epsilon`, *optional*):
177+
prediction_type (`str`, defaults to `"epsilon"`):
178178
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
179179
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
180180
Video](https://huggingface.co/papers/2210.02303) paper).
181181
thresholding (`bool`, defaults to `False`):
182182
Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
183183
as Stable Diffusion.
184-
dynamic_thresholding_ratio (`float`, defaults to 0.995):
184+
dynamic_thresholding_ratio (`float`, defaults to `0.995`):
185185
The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
186-
sample_max_value (`float`, defaults to 1.0):
186+
sample_max_value (`float`, defaults to `1.0`):
187187
The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
188188
timestep_spacing (`str`, defaults to `"leading"`):
189189
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
190190
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
191-
timestep_scaling (`float`, defaults to 10.0):
191+
timestep_scaling (`float`, defaults to `10.0`):
192192
The factor the timesteps will be multiplied by when calculating the consistency model boundary conditions
193193
`c_skip` and `c_out`. Increasing this will decrease the approximation error (although the approximation
194194
error at the default of `10.0` is already pretty small).
@@ -306,13 +306,24 @@ def _init_step_index(self, timestep: float | torch.Tensor) -> None:
306306
self._step_index = self._begin_index
307307

308308
@property
309-
def step_index(self):
309+
def step_index(self) -> int | None:
310+
"""
311+
The index counter for current timestep. It will increase by 1 after each scheduler step.
312+
313+
Returns:
314+
`int` or `None`:
315+
The current step index, or `None` if not initialized.
316+
"""
310317
return self._step_index
311318

312319
@property
313-
def begin_index(self):
320+
def begin_index(self) -> int | None:
314321
"""
315322
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
323+
324+
Returns:
325+
`int` or `None`:
326+
The begin index for the scheduler, or `None` if not set.
316327
"""
317328
return self._begin_index
318329

@@ -337,6 +348,7 @@ def scale_model_input(self, sample: torch.Tensor, timestep: int | None = None) -
337348
The input sample.
338349
timestep (`int`, *optional*):
339350
The current timestep in the diffusion chain.
351+
340352
Returns:
341353
`torch.Tensor`:
342354
A scaled input sample.
@@ -390,11 +402,11 @@ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
390402
def set_timesteps(
391403
self,
392404
num_inference_steps: int | None = None,
393-
device: str | torch.device = None,
405+
device: str | torch.device | None = None,
394406
original_inference_steps: int | None = None,
395407
timesteps: list[int] | None = None,
396-
strength: int = 1.0,
397-
):
408+
strength: float = 1.0,
409+
) -> None:
398410
"""
399411
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
400412
@@ -413,6 +425,12 @@ def set_timesteps(
413425
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
414426
timestep spacing strategy of equal spacing between timesteps on the training/distillation timestep
415427
schedule is used. If `timesteps` is passed, `num_inference_steps` must be `None`.
428+
strength (`float`, defaults to `1.0`):
429+
Strength factor used to generate a partial timestep schedule (e.g. for image-to-image). A value of
430+
`1.0` uses the full schedule.
431+
432+
Returns:
433+
`None`
416434
"""
417435
# 0. Check inputs
418436
if num_inference_steps is None and timesteps is None:
@@ -527,7 +545,20 @@ def set_timesteps(
527545
self._step_index = None
528546
self._begin_index = None
529547

530-
def get_scalings_for_boundary_condition_discrete(self, timestep):
548+
def get_scalings_for_boundary_condition_discrete(self, timestep: int) -> tuple[float, float]:
549+
"""
550+
Computes the boundary condition scalings (`c_skip` and `c_out`) for the given discrete timestep, as used in the
551+
Latent Consistency Model.
552+
553+
Args:
554+
timestep (`int`):
555+
The discrete timestep for which to compute the scalings.
556+
557+
Returns:
558+
`tuple[float, float]`:
559+
A tuple containing `c_skip` (scaling for the input sample) and `c_out` (scaling for the predicted
560+
denoised sample).
561+
"""
531562
self.sigma_data = 0.5 # Default: 0.5
532563
scaled_timestep = timestep * self.config.timestep_scaling
533564

@@ -550,16 +581,17 @@ def step(
550581
Args:
551582
model_output (`torch.Tensor`):
552583
The direct output from learned diffusion model.
553-
timestep (`float`):
584+
timestep (`int`):
554585
The current discrete timestep in the diffusion chain.
555586
sample (`torch.Tensor`):
556587
A current instance of a sample created by the diffusion process.
557588
generator (`torch.Generator`, *optional*):
558-
A random number generator.
559-
return_dict (`bool`, *optional*, defaults to `True`):
589+
A random number generator for reproducible sampling.
590+
return_dict (`bool`, defaults to `True`):
560591
Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
592+
561593
Returns:
562-
[`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
594+
[`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`:
563595
If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
564596
tuple is returned where the first element is the sample tensor.
565597
"""
@@ -709,7 +741,14 @@ def get_velocity(self, sample: torch.Tensor, noise: torch.Tensor, timesteps: tor
709741
velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
710742
return velocity
711743

712-
def __len__(self):
744+
def __len__(self) -> int:
745+
"""
746+
Returns the number of train timesteps.
747+
748+
Returns:
749+
`int`:
750+
The number of diffusion steps used to train the model.
751+
"""
713752
return self.config.num_train_timesteps
714753

715754
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.previous_timestep

0 commit comments

Comments
 (0)