Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions src/diffusers/schedulers/scheduling_pndm.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,25 @@ def __init__(
self.prk_timesteps = None
self.plms_timesteps = None
self.timesteps = None
self._begin_index = None

@property
def begin_index(self) -> int | None:
"""
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
"""
return self._begin_index

# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
def set_begin_index(self, begin_index: int = 0) -> None:
"""
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

Args:
begin_index (`int`, defaults to `0`):
The begin index for the scheduler.
"""
self._begin_index = begin_index

def set_timesteps(self, num_inference_steps: int, device: str | torch.device = None):
"""
Expand Down Expand Up @@ -228,6 +247,7 @@ def set_timesteps(self, num_inference_steps: int, device: str | torch.device = N
self.ets = []
self.counter = 0
self.cur_model_output = 0
self._begin_index = None

def step(
self,
Expand Down Expand Up @@ -362,17 +382,25 @@ def step_plms(

prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps

if self.counter != 1:
# Use the step index relative to begin_index so that img2img pipelines that
# skip the first `t_start` timesteps (via `scheduler.timesteps[t_start:]`) and
# call `set_begin_index(t_start)` before the loop still get correct PLMS
# multi-step corrections. Without this offset the corrector branch fires at the
# wrong position when the denoising loop does not start at step 0.
begin_index = self._begin_index if self._begin_index is not None else 0
effective_counter = self.counter - begin_index

if effective_counter != 1:
self.ets = self.ets[-3:]
self.ets.append(model_output)
else:
prev_timestep = timestep
timestep = timestep + self.config.num_train_timesteps // self.num_inference_steps

if len(self.ets) == 1 and self.counter == 0:
if len(self.ets) == 1 and effective_counter == 0:
model_output = model_output
self.cur_sample = sample
elif len(self.ets) == 1 and self.counter == 1:
elif len(self.ets) == 1 and effective_counter == 1:
model_output = (model_output + self.ets[-1]) / 2
sample = self.cur_sample
self.cur_sample = None
Expand Down
101 changes: 101 additions & 0 deletions tests/schedulers/test_scheduler_pndm.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,104 @@ def test_full_loop_with_no_set_alpha_to_one(self):

assert abs(result_sum.item() - 186.9482) < 1e-2
assert abs(result_mean.item() - 0.2434) < 1e-3

def test_set_begin_index_exists(self):
"""PNDMScheduler exposes the set_begin_index / begin_index interface."""
scheduler_config = self.get_scheduler_config()
scheduler = PNDMScheduler(**scheduler_config)

self.assertTrue(hasattr(scheduler, "set_begin_index"))
self.assertTrue(hasattr(scheduler, "begin_index"))

# begin_index is None before set_timesteps
self.assertIsNone(scheduler.begin_index)

# set_begin_index stores the value
scheduler.set_begin_index(5)
self.assertEqual(scheduler.begin_index, 5)

# set_timesteps resets it to None so the scheduler is clean for a new run
scheduler.set_timesteps(20)
self.assertIsNone(scheduler.begin_index)

def test_set_begin_index_img2img_plms(self):
"""
Regression test for https://github.com/huggingface/diffusers/issues/15429.

When an img2img pipeline skips the first `t_start` timesteps (calling
``scheduler.timesteps[t_start:]``) it must call ``set_begin_index(t_start)``
so that the PLMS corrector fires at the correct local step position.

Without the fix the internal ``counter`` comparison against the absolute values
0 and 1 caused the corrector (the two-step average) to trigger at the wrong
denoising position, producing outputs that differ from a fresh scheduler
running the same sub-sequence starting at step 0.
"""
num_inference_steps = 20
t_start = 5 # img2img strength ≈ 0.75 → skip first 5 steps

scheduler_config = self.get_scheduler_config(skip_prk_steps=True)

# --- reference: scheduler that processes *all* steps from 0 ---
ref_scheduler = PNDMScheduler(**scheduler_config)
ref_scheduler.set_timesteps(num_inference_steps)

torch.manual_seed(0)
sample = torch.randn(1, 4, 8, 8)

# Warm up the reference scheduler through t_start steps so its internal
# state (ets buffer, cur_sample) is at the same point as the img2img case.
for t in ref_scheduler.timesteps[:t_start]:
residual = 0.1 * sample
output = ref_scheduler.step(residual, t, sample)
sample = output.prev_sample
ref_state_ets = list(ref_scheduler.ets)
ref_state_counter = ref_scheduler.counter

# Continue reference from t_start to end.
ref_outputs = []
for t in ref_scheduler.timesteps[t_start:]:
residual = 0.1 * sample
output = ref_scheduler.step(residual, t, sample)
sample = output.prev_sample
ref_outputs.append(sample.clone())

# --- img2img: fresh scheduler, set_begin_index, loop over sliced timesteps ---
img2img_scheduler = PNDMScheduler(**scheduler_config)
img2img_scheduler.set_timesteps(num_inference_steps)

# Restore the same ets state the reference had after t_start steps so the
# multi-step buffer contents are identical (simulating the latent that was
# noise-added and partially denoised before the img2img loop).
img2img_scheduler.ets = list(ref_state_ets)
img2img_scheduler.counter = ref_state_counter
img2img_scheduler.set_begin_index(t_start)

torch.manual_seed(0)
sample = torch.randn(1, 4, 8, 8)
# Reset sample to same starting point as reference at step t_start.
# (In a real pipeline the latent would be from add_noise; here we just
# reproduce the reference sample value at that point.)
ref_scheduler2 = PNDMScheduler(**scheduler_config)
ref_scheduler2.set_timesteps(num_inference_steps)
sample2 = torch.randn(1, 4, 8, 8)
torch.manual_seed(0)
sample2 = torch.randn(1, 4, 8, 8)
for t in ref_scheduler2.timesteps[:t_start]:
residual = 0.1 * sample2
sample2 = ref_scheduler2.step(residual, t, sample2).prev_sample

img2img_outputs = []
for t in img2img_scheduler.timesteps[t_start:]:
residual = 0.1 * sample2
output = img2img_scheduler.step(residual, t, sample2)
sample2 = output.prev_sample
img2img_outputs.append(sample2.clone())

self.assertEqual(len(ref_outputs), len(img2img_outputs))
for i, (ref_out, img2img_out) in enumerate(zip(ref_outputs, img2img_outputs)):
self.assertTrue(
torch.allclose(ref_out, img2img_out, atol=1e-5),
msg=f"Step {t_start + i}: set_begin_index output diverges from reference. "
f"Max diff: {(ref_out - img2img_out).abs().max().item():.6f}",
)