Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(schedulers): start LCM and Anima's Heun at the img2img blend sigma (#10294)

Alexander Eichhorn722a505567c1
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
index 2246ce3b29..ede58afba1 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
@@ -162,18 +162,16 @@ FLUX.1, FLUX.2, Z-Image, Krea-2, Qwen Image and MOSS-Image need sizes that are a
| Family | Schedulers | Steps the pass runs |
| --- | --- | --- |
| SD1.5, SDXL | All of the family's | The part of **Steps** after the start: about half at **Balanced** |
-| FLUX.1 | Euler, Heun | The part of **Steps** after the start: **Balanced** at 30 steps runs about the last 8 from 1024 px up |
+| FLUX.1 | Euler, Heun, LCM | The part of **Steps** after the start: **Balanced** at 30 steps runs about the last 8 from 1024 px up |
| FLUX.2 | Euler only | Starts where FLUX.1 does, then spreads all of **Steps** over the rest of the pass, so 30 steps really run 30 times |
-| Z-Image | Euler, Heun | Starts at FLUX.1's noise level; **Balanced** at 30 steps on a 2048 px result runs the last 7 |
-| Anima | Euler, DPM++ 2M, DPM++ 2M SDE, ER-SDE | As Z-Image; the last 8 |
+| Z-Image | Euler, Heun; LCM on Z-Image Turbo only | Starts at FLUX.1's noise level; **Balanced** at 30 steps on a 2048 px result runs the last 7 |
+| Anima | Euler, Heun, DPM++ 2M, DPM++ 2M SDE, ER-SDE, LCM | As Z-Image; the last 8 |
| Krea-2 | Euler only | As Z-Image; the last 7. Turbo and Raw both keep your **Steps**: Turbo, distilled for 8 steps, runs the end of a 30-step schedule |
| Qwen Image | Euler only | As Z-Image; the last 9 |
| MOSS-Image | Euler only | Starts where FLUX.1 does, then spreads all of **Steps** over the rest of the pass, as FLUX.2 does |
Z-Image, Anima, Krea-2 and Qwen Image count the start in steps rather than in noise level, so the panel translates Creativity for them: it starts on the step whose noise level is closest to where FLUX.1 would start. A preset therefore means the same on every family. These families need at least 2 steps.
-LCM builds its own noise schedule, so it would treat the enlarged image as pure noise. Anima's Heun starts below Creativity's point and leaves noise in the image.
-
</details>
## Memory
diff --git a/invokeai/app/invocations/anima/anima_denoise.py b/invokeai/app/invocations/anima/anima_denoise.py
index 3f9e009ded..0777466cce 100644
--- a/invokeai/app/invocations/anima/anima_denoise.py
+++ b/invokeai/app/invocations/anima/anima_denoise.py
@@ -782,11 +782,9 @@ class AnimaDenoiseInvocation(BaseInvocation, WithMetadata):
# Noise the init latents using the first sigma from the clipped
# InvokeAI schedule.
#
- # Known limitation: if the selected scheduler later starts from a
- # different first effective sigma/timestep than sigmas[0], the
- # img2img preblend below may not match that scheduler exactly.
- # This is an existing pipeline limitation and affects both
- # internally generated noise and externally supplied noise.
+ # Known limitation: DPM++ builds its own schedule, so its first sigma may differ
+ # from sigmas[0] and the preblend below may not match it exactly. This affects
+ # both internally generated and externally supplied noise.
s_0 = sigmas[0]
latents = s_0 * noise + (1.0 - s_0) * init_latents
else:
@@ -1066,7 +1064,8 @@ class AnimaDenoiseInvocation(BaseInvocation, WithMetadata):
step_callback(
PipelineIntermediateState(
step=user_step,
- order=it.order,
+ # Progress over completed user steps, not the solver's order.
+ order=1,
total_steps=total_steps,
timestep=int(it.sigma_curr * 1000),
latents=latents_preview.squeeze(2),
diff --git a/invokeai/app/invocations/flux/flux_denoise.py b/invokeai/app/invocations/flux/flux_denoise.py
index 0948f937c6..e293f77743 100644
--- a/invokeai/app/invocations/flux/flux_denoise.py
+++ b/invokeai/app/invocations/flux/flux_denoise.py
@@ -387,9 +387,7 @@ class FluxDenoiseInvocation(BaseInvocation, WithMetadata):
# Noise the orig_latents by the appropriate amount for the first
# timestep in InvokeAI's clipped schedule.
#
- # Euler and Heun consume this InvokeAI schedule. LCM intentionally
- # creates its own discrete schedule: clipping limits its step count,
- # but its exact start and terminal sigmas can differ from this schedule.
+ # Every scheduler consumes this InvokeAI schedule, so each starts at t_0.
t_0 = timesteps[0]
x = t_0 * noise + (1.0 - t_0) * init_latents
else:
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index 20c8a92f18..f35b021133 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -37,6 +37,7 @@ from invokeai.backend.flux.schedulers import (
ZIMAGE_SCHEDULER_MAP,
ZIMAGE_SCHEDULER_NAME_VALUES,
set_heun_timesteps_from_sigmas,
+ set_timesteps_from_sigmas,
)
from invokeai.backend.fun_controlnet.conditioning import build_fun_control_context
from invokeai.backend.fun_controlnet.hooks import FunControlHooks, install_fun_control, should_apply
@@ -417,8 +418,7 @@ class ZImageDenoiseInvocation(BaseInvocation, WithMetadata):
if self.add_noise:
assert noise is not None
# Noise the init latents using the first sigma from the clipped
- # InvokeAI schedule. Euler and Heun start from this sigma; LCM
- # creates its own schedule, whose first sigma can differ.
+ # InvokeAI schedule, which every scheduler starts from.
s_0 = sigmas[0]
latents = s_0 * noise + (1.0 - s_0) * init_latents
else:
@@ -463,9 +463,7 @@ class ZImageDenoiseInvocation(BaseInvocation, WithMetadata):
# preblend used and stops at the requested end.
set_heun_timesteps_from_sigmas(scheduler, sigmas[:-1], sigmas[-1], device)
else:
- # LCM owns its schedule: clipping only sets its step count. Its first sigma can
- # differ from sigmas[0] used in the img2img preblend above.
- scheduler.set_timesteps(num_inference_steps=total_steps, device=device)
+ set_timesteps_from_sigmas(scheduler, sigmas[:-1], sigmas[-1], device)
# For Heun scheduler, the number of actual steps may differ
num_scheduler_steps = len(scheduler.timesteps)
diff --git a/invokeai/backend/anima/scheduler_driver.py b/invokeai/backend/anima/scheduler_driver.py
index 854d133011..47b333cbf9 100644
--- a/invokeai/backend/anima/scheduler_driver.py
+++ b/invokeai/backend/anima/scheduler_driver.py
@@ -4,10 +4,10 @@ Encapsulates the per-scheduler API quirks that ``anima_denoise._run_diffusion``
would otherwise have to know about:
* Schedulers that accept ``set_timesteps(sigmas=...)`` get the pre-shifted
- Anima schedule passed directly.
-* Schedulers that don't accept ``sigmas=`` use ``set_begin_index()`` over their
- own internal flow-shifted schedule. For Heun, the doubled-array index
- translation (logical step ``k`` → doubled index ``2k``) is handled here.
+ Anima schedule passed directly. Heun's doubled layout and LCM's terminal sigma
+ are set through the helpers in ``invokeai.backend.flux.schedulers``.
+* Schedulers that don't accept ``sigmas=`` (DPM++) use ``set_begin_index()`` over
+ their own internal flow-shifted schedule.
* SDE-style schedulers receive a seeded ``torch.Generator`` on every step.
The denoise loop iterates :meth:`AnimaSchedulerDriver.iterations` and calls
@@ -26,7 +26,11 @@ import torch
from diffusers import FlowMatchHeunDiscreteScheduler
from diffusers.schedulers.scheduling_utils import SchedulerMixin
-from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP
+from invokeai.backend.flux.schedulers import (
+ ANIMA_SCHEDULER_MAP,
+ set_heun_timesteps_from_sigmas,
+ set_timesteps_from_sigmas,
+)
@dataclass(frozen=True)
@@ -44,7 +48,6 @@ class AnimaSchedulerIteration:
sigma_curr: float
sigma_prev: float
completes_user_step: bool
- order: int
class AnimaSchedulerDriver:
@@ -68,29 +71,28 @@ class AnimaSchedulerDriver:
self._begin_index: int = 0
self._step_generator = torch.Generator(device=device).manual_seed(seed)
- is_lcm = scheduler_name == "lcm"
accepts_sigmas = "sigmas" in inspect.signature(self.scheduler.set_timesteps).parameters
clipped = denoising_start > 0 or denoising_end < 1
- if not is_lcm and accepts_sigmas:
+ if self.is_heun:
+ # ``sigmas`` is the clipped schedule, so Heun starts at the img2img blend sigma and ends at the
+ # requested terminal sigma.
+ set_heun_timesteps_from_sigmas(self.scheduler, sigmas[:-1], sigmas[-1], device)
+ self._num_iterations = len(self.scheduler.timesteps)
+ elif scheduler_name == "lcm":
+ # LCM would otherwise build its own linear schedule from 1.0.
+ set_timesteps_from_sigmas(self.scheduler, sigmas[:-1], sigmas[-1], device)
+ self._num_iterations = len(self.scheduler.timesteps)
+ elif accepts_sigmas:
self.scheduler.set_timesteps(sigmas=sigmas, device=device)
self._num_iterations = len(self.scheduler.timesteps)
- elif not is_lcm and clipped and hasattr(self.scheduler, "set_begin_index"):
+ elif clipped and hasattr(self.scheduler, "set_begin_index"):
+ # DPM++ takes no sigmas: clip its own flow-shifted schedule by index.
k_start = int(denoising_start * steps)
k_end = int(denoising_end * steps)
self.scheduler.set_timesteps(num_inference_steps=steps, device=device)
- if self.is_heun:
- # Heun's timesteps array is 2N-1 entries; logical step k maps to
- # doubled index 2k. min() clamps denoising_end=1.0 to the
- # unpaired terminal first-order step.
- self._begin_index = 2 * k_start
- self._num_iterations = min(
- 2 * (k_end - k_start),
- len(self.scheduler.timesteps) - self._begin_index,
- )
- else:
- self._begin_index = k_start
- self._num_iterations = k_end - self._begin_index
+ self._begin_index = k_start
+ self._num_iterations = k_end - self._begin_index
self.scheduler.set_begin_index(self._begin_index)
else:
self.scheduler.set_timesteps(num_inference_steps=len(sigmas) - 1, device=device)
@@ -118,17 +120,16 @@ class AnimaSchedulerDriver:
sigma_prev = self.scheduler.sigmas[next_idx].item() if next_idx < len(self.scheduler.sigmas) else 0.0
# For Heun, a user step completes on the second-order half of each
- # pair AND on the unpaired terminal first-order step (sigma_prev==0).
- is_terminal = sigma_prev == 0.0
+ # pair AND on the unpaired terminal first-order step, which ends at the requested
+ # terminal sigma (not 0 when denoising_end < 1).
+ is_terminal = next_idx >= len(self.scheduler.timesteps)
completes_user_step = (not self.is_heun) or (not in_first_order) or is_terminal
- order = 2 if self.is_heun else 1
yield AnimaSchedulerIteration(
sched_timestep=sched_timestep,
sigma_curr=sigma_curr,
sigma_prev=sigma_prev,
completes_user_step=completes_user_step,
- order=order,
)
def step(
diff --git a/invokeai/backend/flux/denoise.py b/invokeai/backend/flux/denoise.py
index 30766a559a..2830872805 100644
--- a/invokeai/backend/flux/denoise.py
+++ b/invokeai/backend/flux/denoise.py
@@ -58,21 +58,12 @@ def denoise(
# Initialize scheduler with timesteps
# The timesteps list contains values in [0, 1] range (sigmas)
- # Euler and Heun use InvokeAI's custom sigmas; LCM owns its schedule.
+ # Every scheduler runs InvokeAI's schedule, so img2img starts at the sigma of the preblend.
if isinstance(scheduler, FlowMatchHeunDiscreteScheduler):
set_heun_timesteps_from_sigmas(scheduler, timesteps[:-1], timesteps[-1], img.device)
- elif isinstance(scheduler, FlowMatchEulerDiscreteScheduler):
+ elif isinstance(scheduler, FlowMatchEulerDiscreteScheduler) or is_flow_match_lcm_scheduler(scheduler):
# InvokeAI supplies model-evaluation sigmas plus its requested terminal endpoint.
set_timesteps_from_sigmas(scheduler, timesteps[:-1], timesteps[-1], img.device)
- elif is_flow_match_lcm_scheduler(scheduler):
- # LCM owns its schedule; clipping controls the requested evaluation count,
- # while its exact start/end sigmas remain scheduler-defined.
- #
- # Important for img2img callers: if the initial latent/noise blend was
- # computed from a separate pre-scheduler schedule, that preblend may not
- # match this scheduler's true first step exactly.
- num_inference_steps = len(timesteps) - 1
- scheduler.set_timesteps(num_inference_steps=num_inference_steps, device=img.device)
else:
raise TypeError(f"Unsupported FLUX scheduler: {type(scheduler).__name__}")
diff --git a/invokeai/backend/flux/schedulers.py b/invokeai/backend/flux/schedulers.py
index f54c4c38b1..a2961a5a02 100644
--- a/invokeai/backend/flux/schedulers.py
+++ b/invokeai/backend/flux/schedulers.py
@@ -78,6 +78,8 @@ def set_timesteps_from_sigmas(
# set_timesteps() appends a terminal sigma of 0, and step() reads sigmas[step_index + 1], so the
# requested terminal sigma has to replace it for a pass that ends before the schedule does.
scheduler.set_timesteps(sigmas=sigmas, device=device)
+ # step() otherwise finds its index by value, which lands past the first entry when the leading sigma repeats.
+ scheduler.set_begin_index(0)
scheduler.sigmas[-1] = torch.as_tensor(terminal_sigma, dtype=scheduler.sigmas.dtype, device=scheduler.sigmas.device)
@@ -135,12 +137,10 @@ ERNIE_IMAGE_SHIFT = 4.0
# Anima scheduler types.
-# Anima uses rectified flow with shift=3.0. The driver passes pre-shifted sigmas via
-# set_timesteps(sigmas=...) when the scheduler accepts that signature. For those, the
-# entry carries shift=1.0 to avoid double-shifting (the scheduler uses our sigmas verbatim).
-# Schedulers that don't accept sigmas= (Heun, DPM++ on diffusers 0.35.1) build their own
-# internal schedule, so they need shift=ANIMA_SHIFT/flow_shift=ANIMA_SHIFT in kwargs to match
-# Anima's reference loglinear schedule.
+# Anima uses rectified flow with shift=3.0. The driver passes pre-shifted sigmas, so Euler, Heun and LCM
+# entries carry shift=1.0 to avoid double-shifting: Euler and LCM take them through set_timesteps(sigmas=...),
+# Heun through set_heun_timesteps_from_sigmas. DPM++ on diffusers takes no sigmas= and builds its own
+# internal schedule, so it needs flow_shift=ANIMA_SHIFT in kwargs to match Anima's reference loglinear schedule.
# Fixed shift factor for the Anima rectified-flow noise schedule.
ANIMA_SHIFT = 3.0
@@ -159,12 +159,11 @@ ANIMA_SCHEDULER_LABELS: dict[str, str] = {
# When adding a new Anima scheduler: add to all three of NAME_VALUES, LABELS,
# and this MAP. The MAP entry is `(SchedulerClass, scheduler_kwargs)`. For
# rectified-flow schedulers, set `use_flow_sigmas=True` and use
-# `prediction_type="flow_prediction"`. If the scheduler accepts set_timesteps(sigmas=...),
-# use shift=1.0 (driver passes pre-shifted sigmas); otherwise use shift=ANIMA_SHIFT
-# so the scheduler builds the correct internal schedule.
+# `prediction_type="flow_prediction"`. If the driver passes the scheduler pre-shifted sigmas,
+# use shift=1.0; otherwise use shift=ANIMA_SHIFT so the scheduler builds the correct internal schedule.
ANIMA_SCHEDULER_MAP: dict[str, tuple[Type[SchedulerMixin], dict[str, Any]]] = {
"euler": (FlowMatchEulerDiscreteScheduler, {"shift": 1.0}),
- "heun": (FlowMatchHeunDiscreteScheduler, {"shift": ANIMA_SHIFT}),
+ "heun": (FlowMatchHeunDiscreteScheduler, {"shift": 1.0}),
"dpmpp_2m": (
DPMSolverMultistepScheduler,
{
diff --git a/invokeai/backend/flux2/denoise.py b/invokeai/backend/flux2/denoise.py
index 164bac46b4..58f3ee47bb 100644
--- a/invokeai/backend/flux2/denoise.py
+++ b/invokeai/backend/flux2/denoise.py
@@ -115,9 +115,8 @@ def denoise(
use_scheduler = scheduler is not None
if use_scheduler:
# Every scheduler runs InvokeAI's schedule: the model-evaluation sigmas plus the requested
- # terminal sigma, which is not 0 when denoising_end < 1. Unlike FLUX.1, LCM gets it too: the
- # FLUX.2 schedule is shifted from mu and these schedulers do not shift, so a schedule LCM built
- # itself would be the unshifted linear one.
+ # terminal sigma, which is not 0 when denoising_end < 1. The FLUX.2 schedule is shifted from mu and
+ # these schedulers do not shift, so a schedule LCM built itself would be the unshifted linear one.
is_heun = isinstance(scheduler, FlowMatchHeunDiscreteScheduler)
if is_heun:
set_heun_timesteps_from_sigmas(scheduler, timesteps[:-1], timesteps[-1], img.device)
diff --git a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx
index 49ff72d37b..0fc601ad2f 100644
--- a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx
@@ -398,7 +398,7 @@ describe('Upscale without the served architecture table', () => {
?.click()
);
- // Euler and Heun both start where the blend left the latents on Z-Image; LCM does not.
+ // Every Z-Image scheduler starts where the blend left the latents.
expect(host.textContent).toContain('widgets.upscale.cfgScale');
const scheduler = host.querySelector<HTMLInputElement>('input[aria-label="widgets.upscale.scheduler"]');
expect(scheduler?.value).toBe('Euler');
@@ -411,7 +411,7 @@ describe('Upscale without the served architecture table', () => {
);
const offered = [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent);
- expect(offered).toEqual(['Euler', 'Heun (2nd order)']);
+ expect(offered).toEqual(['Euler', 'Heun (2nd order)', 'LCM']);
});
});
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json
index 1de557686a..cd8a9b4b60 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json
+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json
@@ -1517,9 +1517,11 @@
"schedulers": {
"anima": [
"euler",
+ "heun",
"dpmpp_2m",
"dpmpp_2m_sde",
- "er_sde"
+ "er_sde",
+ "lcm"
],
"krea-2": [
"euler"
@@ -1529,7 +1531,8 @@
],
"z-image": [
"euler",
- "heun"
+ "heun",
+ "lcm"
]
}
}
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
index f1d9886e46..c4a308210a 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
@@ -650,13 +650,16 @@ describe('Creativity on index-clipping architectures', () => {
});
describe('schedulers on the upscale pass', () => {
+ // A scheduler stored from another base is coerced to one the base offers. FLUX.2 steps with Euler
+ // whenever the pass starts above pure noise.
it.each([
- ['flux', () => createFluxValues(), 'lcm', 'euler'],
+ ['flux', () => createFluxValues(), 'lcm', 'lcm'],
['flux', () => createFluxValues(), 'heun', 'heun'],
['flux2', () => createFlux2Values('klein_4b'), 'heun', 'euler'],
- ['z-image', () => createZImageValues(), 'lcm', 'euler'],
+ ['z-image', () => createZImageValues(), 'lcm', 'lcm'],
['z-image', () => createZImageValues(), 'heun', 'heun'],
- ['anima', () => createAnimaValues(), 'heun', 'euler'],
+ ['anima', () => createAnimaValues(), 'heun', 'heun'],
+ ['anima', () => createAnimaValues(), 'lcm', 'lcm'],
['anima', () => createAnimaValues(), 'dpmpp_2m', 'dpmpp_2m'],
['sd-1', () => createValues('sd-1'), 'heun', 'heun'],
] as const)('runs %s with %s stored as %s, and records what ran', (_base, createBaseValues, stored, runs) => {
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
index 57c16a2e8e..f049aa81be 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
@@ -383,9 +383,10 @@ describe('schedulers per architecture', () => {
const offered = (base: string) =>
upscaleSchedulerOptions(model(base, 'main', base) as never).map((option) => option.value);
- expect(offered('flux')).toEqual(['euler', 'heun']);
- expect(offered('z-image')).toEqual(['euler', 'heun']);
- expect(offered('anima')).toEqual(['euler', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde']);
+ expect(offered('flux')).toEqual(['euler', 'heun', 'lcm']);
+ expect(offered('z-image')).toEqual(['euler', 'heun', 'lcm']);
+ expect(offered('anima')).toEqual(['euler', 'heun', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde', 'lcm']);
+ // `krea2_denoise` and `qwen_image_denoise` have no scheduler input.
expect(offered('krea-2')).toEqual(['euler']);
expect(offered('qwen-image')).toEqual(['euler']);
expect(offered('flux2')).toEqual(['euler']);
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
index 0639002032..7f63b7ad21 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
@@ -173,8 +173,8 @@ export interface UpscaleArchitecture {
/** SD denoises in overlapping tiles, hence its required tile ControlNet; the others run whole. */
readonly multiDiffusion: boolean;
/**
- * Schedulers that start where Creativity puts the pass; null where all do. LCM on FLUX.1/Z-Image/Anima and
- * Anima's Heun build their own schedules past the blend. `test_upscale_index_clipped_starts.py` checks these.
+ * Schedulers that start where Creativity puts the pass; null where all do. Explicit even where they match every
+ * backend scheduler, so a new one stays out until `test_upscale_index_clipped_starts.py` passes it.
*/
readonly schedulers: readonly string[] | null;
/**
@@ -220,8 +220,9 @@ export const UPSCALE_ARCHITECTURES = {
: { slots: [T5_ENCODER_SLOT, CLIP_EMBED_SLOT], vae: true },
label: 'FLUX.1',
multiDiffusion: false,
- // `flux/denoise.py` uses `z_image_denoise`'s schedulers, so this follows the backend contract's Z-Image list.
- schedulers: ['euler', 'heun'],
+ // `flux/denoise.py` hands Heun and LCM to the same diffusers schedulers as `z_image_denoise`, so
+ // this list follows the one the backend contract checks for Z-Image.
+ schedulers: ['euler', 'heun', 'lcm'],
takesModelGuidance: false,
takesModelSteps: false,
tileControlNet: null,
@@ -246,7 +247,7 @@ export const UPSCALE_ARCHITECTURES = {
isBundledMainForBase('z-image')(model) ? NO_COMPONENTS : { slots: [Z_IMAGE_QWEN3_SLOT], vae: true },
label: 'Z-Image',
multiDiffusion: false,
- schedulers: ['euler', 'heun'],
+ schedulers: ['euler', 'heun', 'lcm'],
takesModelGuidance: true,
takesModelSteps: false,
tileControlNet: { kind: 'z_image_control', matchesName: nameIncludes('tile'), required: false },
@@ -259,7 +260,7 @@ export const UPSCALE_ARCHITECTURES = {
}),
label: 'Anima',
multiDiffusion: false,
- schedulers: ['euler', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde'],
+ schedulers: ['euler', 'heun', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde', 'lcm'],
takesModelGuidance: true,
takesModelSteps: false,
tileControlNet: null,
diff --git a/tests/app/invocations/test_anima_ip_adapter.py b/tests/app/invocations/test_anima_ip_adapter.py
index 217e3b0cab..723fbeb65d 100644
--- a/tests/app/invocations/test_anima_ip_adapter.py
+++ b/tests/app/invocations/test_anima_ip_adapter.py
@@ -15,6 +15,7 @@ from invokeai.app.invocations.anima.anima_denoise import AnimaDenoiseInvocation
from invokeai.app.invocations.anima.anima_ip_adapter import AnimaIPAdapterField, AnimaIPAdapterInvocation
from invokeai.app.invocations.fields import AnimaConditioningField
from invokeai.app.invocations.model import ModelIdentifierField
+from invokeai.app.util.step_callback import calc_percentage
from invokeai.backend.anima.ip_adapter import AnimaIPAdapter
from invokeai.backend.model_manager.starter_models.common import siglip, siglip2_base_512
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
@@ -145,6 +146,19 @@ def _denoise(
return transformer, patches, adapters
[email protected]("scheduler", ["heun", "lcm"])
+def test_progress_advances_one_user_step_at_a_time(monkeypatch, scheduler) -> None:
+ """Heun runs two evaluations per step, but progress counts user steps: a Heun pass must not report order 2,
+ which would make `calc_percentage` advance in pairs."""
+ steps = 5
+ context = MagicMock()
+ _denoise(monkeypatch, None, steps=steps, scheduler=scheduler, context=context)
+
+ states = [call.args[0] for call in context.util.sd_step_callback.call_args_list]
+ assert [state.step for state in states] == list(range(1, steps + 1))
+ assert [calc_percentage(state) for state in states] == pytest.approx([k / steps for k in range(1, steps + 1)])
+
+
@pytest.mark.parametrize("scheduler", ["euler", "dpmpp_2m"])
def test_the_positive_pass_gets_the_image_and_the_negative_pass_does_not(monkeypatch, scheduler) -> None:
transformer, patches, adapters = _denoise(monkeypatch, _field(), scheduler=scheduler)
diff --git a/tests/app/invocations/test_denoise_noise_inputs.py b/tests/app/invocations/test_denoise_noise_inputs.py
index 7433cea0d2..31384a5e35 100644
--- a/tests/app/invocations/test_denoise_noise_inputs.py
+++ b/tests/app/invocations/test_denoise_noise_inputs.py
@@ -1,4 +1,3 @@
-import inspect
from contextlib import ExitStack, nullcontext
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -18,13 +17,11 @@ from invokeai.app.invocations.metadata_linked import (
)
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.invocations.sd3.sd3_denoise import SD3DenoiseInvocation
-from invokeai.app.invocations.z_image.z_image_denoise import Z_IMAGE_SHIFT_FIT, ZImageDenoiseInvocation
-from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional, get_schedule
+from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional
from invokeai.backend.flux.schedulers import (
- ANIMA_SCHEDULER_MAP,
FLUX_SCHEDULER_MAP,
ZIMAGE_SCHEDULER_MAP,
- set_heun_timesteps_from_sigmas,
)
from invokeai.backend.flux2.sampling_utils import get_schedule_flux2
from invokeai.backend.model_manager.taxonomy import BaseModelType, FluxVariantType, ModelFormat, ModelType
@@ -661,61 +658,6 @@ def test_denoise_metadata_persists_hidiffusion_fields_when_disabled():
assert result.metadata.root["hidiffusion_t2_ratio"] == 0.1
-def _get_first_scheduler_sigma(
- scheduler,
- *,
- scheduler_name: str,
- sigmas: list[float],
- mu: float | None = None,
- use_flux_heun_schedule: bool = False,
-) -> float:
- if scheduler_name == "heun" and use_flux_heun_schedule:
- set_heun_timesteps_from_sigmas(scheduler, sigmas[:-1], sigmas[-1], "cpu")
- return float(scheduler.sigmas[0])
-
- set_timesteps_signature = inspect.signature(scheduler.set_timesteps)
- if scheduler_name != "lcm" and "sigmas" in set_timesteps_signature.parameters:
- kwargs: dict[str, object] = {"sigmas": sigmas, "device": "cpu"}
- if mu is not None and "mu" in set_timesteps_signature.parameters:
- kwargs["mu"] = mu
- scheduler.set_timesteps(**kwargs)
- else:
- kwargs = {"num_inference_steps": len(sigmas) - 1, "device": "cpu"}
- if mu is not None and "mu" in set_timesteps_signature.parameters:
- kwargs["mu"] = mu
- scheduler.set_timesteps(**kwargs)
- return float(scheduler.sigmas[0])
-
-
- "scheduler_name",
- [
- "euler",
- "heun",
- pytest.param(
- "lcm",
- marks=pytest.mark.xfail(
- reason="Known img2img preblend mismatch for FLUX with scheduler-defined first step.",
- strict=True,
- ),
- ),
- ],
-)
-def test_flux_img2img_preblend_matches_scheduler_first_sigma(scheduler_name: str):
- sigmas = clip_timestep_schedule_fractional(get_schedule(num_steps=4, image_seq_len=16, shift=True), 0.25, 1.0)
- scheduler_class = FLUX_SCHEDULER_MAP[scheduler_name]
- scheduler = scheduler_class(num_train_timesteps=1000)
-
- assert sigmas[0] == pytest.approx(
- _get_first_scheduler_sigma(
- scheduler,
- scheduler_name=scheduler_name,
- sigmas=sigmas,
- use_flux_heun_schedule=True,
- )
- )
-
-
def test_flux2_partial_denoise_short_circuit_uses_first_clipped_timestep():
invocation = Flux2DenoiseInvocation.model_construct(
latents=MagicMock(latents_name="latents"),
@@ -983,66 +925,6 @@ def test_z_image_invocation_steps_lcm_with_a_seeded_generator(seed: int, expecte
_assert_step_generator(step_generators[0], expected_seed)
-# Heun is covered through the node in test_z_image_denoise_schedulers.py.
- "scheduler_name",
- [
- "euler",
- pytest.param(
- "lcm",
- marks=pytest.mark.xfail(
- reason="Known img2img preblend mismatch for Z-Image with scheduler-defined first step.",
- strict=True,
- ),
- ),
- ],
-)
-def test_z_image_img2img_preblend_matches_scheduler_first_sigma(scheduler_name: str):
- invocation = ZImageDenoiseInvocation.model_construct(steps=8, width=1024, height=1024)
- img_seq_len = (invocation.height // 8 // 2) * (invocation.width // 8 // 2)
- shift = Z_IMAGE_SHIFT_FIT.shift(img_seq_len)
- sigmas = invocation._get_sigmas(shift, invocation.steps)
- sigmas = sigmas[int(0.25 * (len(sigmas) - 1)) :]
- scheduler_class = ZIMAGE_SCHEDULER_MAP[scheduler_name]
- scheduler = scheduler_class(num_train_timesteps=1000, shift=1.0)
-
- assert sigmas[0] == pytest.approx(
- _get_first_scheduler_sigma(scheduler, scheduler_name=scheduler_name, sigmas=sigmas)
- )
-
-
- "scheduler_name",
- [
- "euler",
- pytest.param(
- "heun",
- marks=pytest.mark.xfail(
- reason="Known img2img preblend mismatch for Anima with scheduler-defined first step.",
- strict=True,
- ),
- ),
- pytest.param(
- "lcm",
- marks=pytest.mark.xfail(
- reason="Known img2img preblend mismatch for Anima with scheduler-defined first step.",
- strict=True,
- ),
- ),
- ],
-)
-def test_anima_img2img_preblend_matches_scheduler_first_sigma(scheduler_name: str):
- invocation = AnimaDenoiseInvocation.model_construct(steps=30)
- sigmas = invocation._get_sigmas(invocation.steps)
- sigmas = sigmas[int(0.25 * (len(sigmas) - 1)) :]
- scheduler_class, scheduler_kwargs = ANIMA_SCHEDULER_MAP[scheduler_name]
- scheduler = scheduler_class(num_train_timesteps=1000, **scheduler_kwargs)
-
- assert sigmas[0] == pytest.approx(
- _get_first_scheduler_sigma(scheduler, scheduler_name=scheduler_name, sigmas=sigmas)
- )
-
-
def test_sd3_partial_denoise_short_circuit_uses_first_clipped_timestep():
invocation = SD3DenoiseInvocation.model_construct(
latents=MagicMock(latents_name="latents"),
diff --git a/tests/app/invocations/test_z_image_denoise_schedulers.py b/tests/app/invocations/test_z_image_denoise_schedulers.py
index 86f408b549..6d2a62697a 100644
--- a/tests/app/invocations/test_z_image_denoise_schedulers.py
+++ b/tests/app/invocations/test_z_image_denoise_schedulers.py
@@ -1,12 +1,12 @@
-"""Z-Image's Heun scheduler runs the node's shifted, clipped schedule.
+"""Z-Image's Heun and LCM schedulers run the node's shifted, clipped schedule.
-Heun used to rebuild its own schedule from the step count with a shift of 1.0: it ran linear sigmas
+Heun and LCM used to rebuild their own schedule from the step count with a shift of 1.0: they ran linear sigmas
instead of the shifted ones, started img2img at sigma 1.0 whatever the img2img blend used, ignored
-`denoising_end`, and its progress stopped one step short of the end.
+`denoising_end`, and Heun's progress stopped one step short of the end.
These tests drive the real `_run_diffusion` through the denoising loop with a stand-in transformer.
The node's own manual Euler path is the reference for the schedule: it steps the clipped sigmas
-directly, so Heun has to evaluate the same sigmas in Diffusers' Heun layout. An interval of zero length,
+directly, so Heun has to evaluate the same sigmas in Diffusers' Heun layout and LCM the same sigmas as Euler. An interval of zero length,
which an explicit shift of 0 leaves at sigma 0, is the exception: Heun would divide by zero there.
"""
@@ -147,13 +147,50 @@ def test_a_pass_ending_at_denoising_end_stops_where_the_continuing_pass_starts(s
@pytest.mark.skipif("lcm" not in ZIMAGE_SCHEDULER_MAP, reason="FlowMatchLCMScheduler unavailable")
-def test_lcm_keeps_its_own_schedule():
- """LCM builds its schedule from the step count; only Heun is handed the node's sigmas."""
- lcm, _, callbacks = _drive("lcm")
+ ("denoising_start", "denoising_end"),
+ [
+ pytest.param(0.0, 1.0, id="txt2img"),
+ pytest.param(0.5, 1.0, id="img2img"),
+ pytest.param(0.3, 1.0, id="img2img-low-strength"),
+ pytest.param(0.0, 0.5, id="partial"),
+ ],
+)
+def test_lcm_evaluates_the_sigmas_euler_steps(denoising_start: float, denoising_end: float):
+ euler, _, _ = _drive("euler", denoising_start, denoising_end)
+ lcm, _, callbacks = _drive("lcm", denoising_start, denoising_end)
- assert len(lcm.sigmas) == STEPS
- assert lcm.sigmas[0] == pytest.approx(1.0)
- assert [callback.step for callback in callbacks] == list(range(1, STEPS + 1))
+ assert lcm.sigmas == pytest.approx(euler.sigmas, abs=1e-6)
+ assert [callback.step for callback in callbacks] == list(range(1, len(euler.sigmas) + 1))
+
+
[email protected]("lcm" not in ZIMAGE_SCHEDULER_MAP, reason="FlowMatchLCMScheduler unavailable")
[email protected]("denoising_end", [1.0, 0.5])
+def test_lcm_ends_at_the_clipped_schedules_terminal_sigma(denoising_end: float):
+ real = ZIMAGE_SCHEDULER_MAP["lcm"]
+ made = []
+
+ class _Recording(real):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ made.append(self)
+
+ with patch.dict(ZIMAGE_SCHEDULER_MAP, {"lcm": _Recording}):
+ _drive("lcm", denoising_end=denoising_end)
+
+ # A pass ending at denoising_end stops where the continuing pass starts; a full pass ends at 0.
+ expected = _drive("euler", denoising_start=denoising_end)[0].sample_levels[0] if denoising_end < 1.0 else 0.0
+ (scheduler,) = made
+ assert scheduler.sigmas[-1].item() == pytest.approx(expected, abs=1e-6)
+
+
[email protected]("lcm" not in ZIMAGE_SCHEDULER_MAP, reason="FlowMatchLCMScheduler unavailable")
+def test_lcm_img2img_starts_at_the_sigma_the_blend_used():
+ lcm, _, _ = _drive("lcm", denoising_start=0.5)
+
+ # Zero init latents and unit noise: the blended sample's value is the sigma it was blended at.
+ assert lcm.sigmas[0] == pytest.approx(lcm.sample_levels[0], abs=1e-6)
+ assert lcm.sigmas[0] < 1.0
def test_heun_progress_reaches_every_step():
diff --git a/tests/backend/anima/test_scheduler_driver.py b/tests/backend/anima/test_scheduler_driver.py
index d484247c29..b59206c5a5 100644
--- a/tests/backend/anima/test_scheduler_driver.py
+++ b/tests/backend/anima/test_scheduler_driver.py
@@ -57,7 +57,7 @@ def test_driver_single_step_schedulers_complete_user_step_every_iteration(schedu
def test_driver_heun_completes_user_step_on_second_order_and_terminal() -> None:
"""Heun yields one completion per user step: each pair's 2nd-order half plus
- the unpaired terminal 1st-order step (sigma_prev==0)."""
+ the unpaired terminal 1st-order step."""
num_steps = 4
driver = AnimaSchedulerDriver(
scheduler_name="heun",
@@ -117,40 +117,102 @@ def test_driver_dpmpp_clipped_schedule_starts_at_correct_sigma(denoising_start:
assert abs(first_iter.sigma_curr - expected_first_sigma) < 2e-3
- ("denoising_start", "denoising_end", "steps"),
- [(0.2, 0.8, 30), (0.0, 0.8, 30), (0.2, 1.0, 30), (0.5, 0.75, 20)],
-)
-def test_driver_heun_clipped_schedule_iteration_count(denoising_start: float, denoising_end: float, steps: int) -> None:
- """Heun clipped schedule: iteration count is 2*(k_end-k_start), clamped so
- denoising_end=1.0 doesn't run past the 2N-1 array."""
+def _clipped_driver(scheduler_name: str, denoising_start: float, denoising_end: float, steps: int, seed: int = 0):
+ """Build the driver as `anima_denoise` does: it hands over the schedule already clipped by index."""
full_sigmas = _anima_sigmas(steps)
- k_start = int(denoising_start * steps)
- k_end = int(denoising_end * steps)
-
+ clipped = full_sigmas[int(denoising_start * steps) : int(denoising_end * steps) + 1]
driver = AnimaSchedulerDriver(
- scheduler_name="heun",
- sigmas=full_sigmas,
+ scheduler_name=scheduler_name,
+ sigmas=clipped,
steps=steps,
denoising_start=denoising_start,
denoising_end=denoising_end,
device=torch.device("cpu"),
- seed=0,
+ seed=seed,
)
+ return driver, clipped
+
+
[email protected]("scheduler_name", ["er_sde", "lcm"])
+ ("denoising_start", "denoising_end"),
+ [(0.0, 1.0), (0.3, 1.0), (0.5, 1.0), (0.0, 0.8), (0.5, 0.75)],
+)
+def test_driver_starts_at_the_first_sigma_of_the_clipped_schedule(
+ scheduler_name: str, denoising_start: float, denoising_end: float
+) -> None:
+ """The img2img blend noises the latents to the clipped schedule's first sigma, so that is where every
+ scheduler that takes sigmas has to start (Heun and LCM used to start at their own 1.0 / unshifted plan)."""
+ driver, clipped = _clipped_driver(scheduler_name, denoising_start, denoising_end, steps=30)
+
+ first = next(driver.iterations())
+
+ assert first.sigma_curr == pytest.approx(clipped[0], abs=1e-6)
+
+
+ ("denoising_start", "denoising_end"),
+ [(0.0, 1.0), (0.3, 1.0), (0.5, 1.0), (0.0, 0.8), (0.5, 0.75)],
+)
+def test_driver_heun_runs_the_clipped_schedule_in_its_doubled_layout(
+ denoising_start: float, denoising_end: float
+) -> None:
+ driver, clipped = _clipped_driver("heun", denoising_start, denoising_end, steps=30)
+ user_steps = len(clipped) - 1
+
+ iterations = list(driver.iterations())
+
+ assert driver.num_iterations == len(iterations) == 2 * user_steps - 1
+ assert [it.sigma_curr for it in iterations] == pytest.approx(
+ [clipped[0]] + [s for s in clipped[1:-1] for _ in (0, 1)], abs=1e-6
+ )
+ # The last iteration ends at the requested terminal sigma, which is not 0 when denoising_end < 1.
+ assert iterations[-1].sigma_prev == pytest.approx(clipped[-1], abs=1e-6)
+
+
[email protected]("denoising_end", [1.0, 0.75])
+def test_driver_heun_progress_reaches_every_user_step(denoising_end: float) -> None:
+ """Fed through scheduler.step like production, Heun completes exactly one user step per interval,
+ including the terminal first-order step when the pass ends before sigma 0."""
+ driver, clipped = _clipped_driver("heun", 0.5, denoising_end, steps=20)
+ completions = 0
+ for it in driver.iterations():
+ completions += it.completes_user_step
+ driver.scheduler.step(
+ model_output=torch.zeros((1, 1, 1, 4, 4)),
+ timestep=it.sched_timestep,
+ sample=torch.zeros((1, 1, 1, 4, 4)),
+ )
+
+ assert completions == len(clipped) - 1
+
+
[email protected](("denoising_start", "denoising_end"), [(0.0, 1.0), (0.5, 1.0), (0.5, 0.75)])
+def test_driver_lcm_runs_the_clipped_schedule_to_its_terminal_sigma(
+ denoising_start: float, denoising_end: float
+) -> None:
+ driver, clipped = _clipped_driver("lcm", denoising_start, denoising_end, steps=20)
+
+ iterations = list(driver.iterations())
+
+ assert [it.sigma_curr for it in iterations] == pytest.approx(clipped[:-1], abs=1e-6)
+ assert iterations[-1].sigma_prev == pytest.approx(clipped[-1], abs=1e-6)
+ assert all(it.completes_user_step for it in iterations)
+
+
+def test_driver_lcm_step_noise_follows_the_seed() -> None:
+ """LCM re-noises the sample on every step: it has to draw from the driver's seeded generator, not the global RNG."""
+
+ def run(seed: int) -> torch.Tensor:
+ torch.rand(64) # advance the global RNG like a long-lived server does
+ driver, _ = _clipped_driver("lcm", 0.5, 1.0, steps=8, seed=seed)
+ sample = torch.zeros((1, 1, 1, 4, 4))
+ for it in driver.iterations():
+ sample = driver.step(torch.zeros_like(sample), it.sched_timestep, sample)
+ return sample
- # If Heun's set_timesteps accepts sigmas=, the driver will pass the full schedule directly
- # and yield 2*steps-1 iterations regardless of clipping. The set_begin_index path applies
- # only when sigmas= is unsupported.
- accepts_sigmas = "sigmas" in inspect.signature(driver.scheduler.set_timesteps).parameters
- if accepts_sigmas:
- # Driver took the sigma-passing path; sigmas were not pre-clipped here, so the count
- # reflects the full schedule.
- assert driver.num_iterations == 2 * steps - 1
- return
-
- expected = min(2 * (k_end - k_start), len(driver.scheduler.timesteps) - driver.begin_index)
- assert driver.num_iterations == expected
- assert driver.begin_index == 2 * k_start
+ assert torch.equal(run(1234), run(1234))
+ assert not torch.equal(run(1), run(2))
def test_driver_terminal_sigma_prev_is_zero() -> None:
diff --git a/tests/backend/flux/test_anima_schedulers.py b/tests/backend/flux/test_anima_schedulers.py
index c94c2678ff..bfb0d8ca2c 100644
--- a/tests/backend/flux/test_anima_schedulers.py
+++ b/tests/backend/flux/test_anima_schedulers.py
@@ -2,7 +2,6 @@
import typing
-import pytest
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from invokeai.backend.flux.schedulers import (
@@ -179,69 +178,6 @@ def test_anima_set_begin_index_path_step_count_with_denoising_end():
)
- ["denoising_start", "denoising_end", "steps"],
- [
- (0.2, 0.8, 30), # mid-range: 18 logical steps → 36 doubled calls
- (0.0, 0.8, 30), # start-only clip: 24 logical steps → 48 doubled calls
- (0.2, 1.0, 30), # end=1.0: clamp kicks in (last step first-order only)
- (0.5, 0.75, 20), # different step count
- ],
-)
-def test_anima_heun_set_begin_index_path_begin_index_and_step_count(
- denoising_start: float, denoising_end: float, steps: int
-):
- """Heun img2img: set_begin_index must use doubled-array index and step count must
- account for Heun's 2N-1 timestep structure.
-
- Logical step k maps to doubled-array begin index 2k. For a range [k_start, k_end)
- the total calls is 2*(k_end-k_start), clamped to len(timesteps)-begin_index so that
- denoising_end=1.0 correctly gets the 2N-1 (not 2N) count.
- """
- from diffusers import FlowMatchHeunDiscreteScheduler
-
- k_start = int(denoising_start * steps)
- k_end = int(denoising_end * steps)
-
- scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000, shift=1.0)
- scheduler.set_timesteps(num_inference_steps=steps, device="cpu")
-
- expected_begin_index = 2 * k_start
- expected_steps = min(2 * (k_end - k_start), len(scheduler.timesteps) - expected_begin_index)
-
- # Verify the doubled structure: len(timesteps) == 2*steps - 1
- assert len(scheduler.timesteps) == 2 * steps - 1, (
- f"Heun timesteps length: expected {2 * steps - 1}, got {len(scheduler.timesteps)}"
- )
-
- # The fixed code's begin index must map logical step to doubled-array space.
- assert expected_begin_index == 2 * k_start
-
- # For mid-range (denoising_end < 1): all steps in range have first + second order.
- if denoising_end < 1.0:
- assert expected_steps == 2 * (k_end - k_start), (
- f"mid-range step count: expected {2 * (k_end - k_start)}, got {expected_steps}"
- )
-
- # For denoising_end=1.0: last step is first-order only → clamped to 2N-1-begin.
- if denoising_end == 1.0 and k_start > 0:
- full_from_begin = len(scheduler.timesteps) - expected_begin_index
- assert expected_steps == full_from_begin
-
- # Bounds check: begin_index + num_steps must not exceed len(timesteps).
- assert expected_begin_index + expected_steps <= len(scheduler.timesteps), (
- f"step range [{expected_begin_index}, {expected_begin_index + expected_steps}) "
- f"exceeds timesteps length {len(scheduler.timesteps)}"
- )
-
- # Sigma sanity: the sigma at the doubled begin index must equal the sigma at logical k_start.
- # sigmas has 2N entries; sigmas[2k] == s_k for all k.
- assert len(scheduler.sigmas) == 2 * steps
- sigma_at_begin = scheduler.sigmas[expected_begin_index].item()
- sigma_at_logical_k = scheduler.sigmas[2 * k_start].item()
- assert abs(sigma_at_begin - sigma_at_logical_k) < 1e-6
-
-
def test_anima_literal_covers_every_map_key():
"""Catch the silent failure mode where a new entry lands in the map but
the Literal isn't updated — Pydantic validation would still accept it
@@ -262,44 +198,6 @@ def test_anima_scheduler_literal_includes_er_sde():
assert "er_sde" in ANIMA_SCHEDULER_MAP
-def test_anima_heun_uses_anima_shift_for_internal_schedule():
- """Heun does NOT accept set_timesteps(sigmas=...) so it always builds its own internal
- schedule. With shift=1.0 (the previous setting), that schedule was linear and gave the
- wrong noise levels for img2img — Heun's sigmas[2*k_start] would be ~0.48 when Anima's
- reference at user step k_start (denoising_start=0.5) is ~0.75. The model would receive
- a timestep matching neither the latents nor its training distribution.
-
- Fix: give Heun shift=ANIMA_SHIFT so its internal schedule approximates Anima's reference.
- """
- from invokeai.app.invocations.anima.anima_denoise import loglinear_timestep_shift
-
- cls, kwargs = ANIMA_SCHEDULER_MAP["heun"]
- from invokeai.backend.flux.schedulers import ANIMA_SHIFT
-
- assert kwargs["shift"] == ANIMA_SHIFT, (
- f"Heun must use shift={ANIMA_SHIFT} (Anima's loglinear shift) since it doesn't accept "
- f"sigmas=; got shift={kwargs['shift']}"
- )
-
- # Verify the schedule approximates Anima's reference for the bulk of user steps.
- # The two formulas diverge at the tail (Heun uses linspace(1, T, N+1), Anima uses
- # 1 - i/N), so we tolerate up to 5% absolute. The previous shift=1.0 bug gave 25-40%+
- # divergence at mid-schedule, so any reasonable tolerance catches that regression.
- steps = 30
- anima_ref = [loglinear_timestep_shift(ANIMA_SHIFT, 1.0 - i / steps) for i in range(steps + 1)]
- s = cls(num_train_timesteps=1000, **kwargs)
- s.set_timesteps(num_inference_steps=steps, device="cpu")
-
- # Heun's sigmas array has 2*N entries; sigmas[2*k] is the noise level at user step k.
- for k in (0, 5, 10, 15):
- heun_sigma = s.sigmas[2 * k].item()
- ref = anima_ref[k]
- assert abs(heun_sigma - ref) < 0.05, (
- f"Heun internal sigma at user step {k} ({heun_sigma:.4f}) diverges from "
- f"Anima reference ({ref:.4f}) by more than 5% — likely a shift kwarg regression"
- )
-
-
def test_anima_scheduler_map_er_sde_entry():
"""ANIMA_SCHEDULER_MAP['er_sde'] must map to ERSDEScheduler with rectified-flow kwargs.
diff --git a/tests/backend/flux/test_denoise.py b/tests/backend/flux/test_denoise.py
index 5cccb5fbd4..3a3f53c287 100644
--- a/tests/backend/flux/test_denoise.py
+++ b/tests/backend/flux/test_denoise.py
@@ -539,11 +539,44 @@ def test_lcm_preview_uses_the_model_evaluation_sample_and_sigma(monkeypatch):
assert model.timesteps == pytest.approx(
[float(timestep / scheduler.config.num_train_timesteps) for timestep in scheduler.timesteps]
)
- assert model.timesteps == pytest.approx([1.0, 0.001])
- assert not torch.allclose(scheduler.sigmas, torch.tensor([1.0, 0.5, 0.0]))
+ assert model.timesteps == pytest.approx([1.0, 0.5])
assert torch.allclose(callbacks[0].latents, expected_preview)
[email protected](not _HAS_LCM, reason="FlowMatchLCMScheduler not available in this Diffusers version")
[email protected]("terminal_sigma", [0.0, 0.1])
+def test_lcm_img2img_starts_at_the_clipped_schedules_first_sigma_and_ends_at_its_terminal_sigma(
+ monkeypatch, terminal_sigma
+):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [0.5, 0.3, terminal_sigma]
+ scheduler = FLUX_SCHEDULER_MAP["lcm"](num_train_timesteps=1000)
+
+ _, _, model, callbacks = _run_with_scheduler(scheduler, schedule)
+
+ assert model.timesteps == pytest.approx(schedule[:-1])
+ assert scheduler.sigmas[0].item() == pytest.approx(0.5)
+ assert scheduler.sigmas[-1].item() == pytest.approx(terminal_sigma)
+ assert [callback.step for callback in callbacks] == [1, 2]
+
+
[email protected]("scheduler_name", ["euler", "lcm"])
+def test_set_timesteps_from_sigmas_steps_a_plan_whose_leading_sigma_repeats(scheduler_name):
+ """step() would find a repeated leading timestep by value and start one entry late, running off the plan's end."""
+ if scheduler_name == "lcm" and not _HAS_LCM:
+ pytest.skip("FlowMatchLCMScheduler not available in this Diffusers version")
+ from invokeai.backend.flux.schedulers import set_timesteps_from_sigmas
+
+ scheduler = FLUX_SCHEDULER_MAP[scheduler_name](num_train_timesteps=1000)
+ set_timesteps_from_sigmas(scheduler, [0.5, 0.5, 0.2], 0.1, "cpu")
+ sample = torch.ones(1, 1, 1)
+
+ for timestep in scheduler.timesteps:
+ sample = scheduler.step(torch.zeros_like(sample), timestep, sample).prev_sample
+
+ assert scheduler.step_index == 3
+
+
@pytest.mark.skipif(not _HAS_LCM, reason="FlowMatchLCMScheduler not available in this Diffusers version")
def test_lcm_step_noise_follows_the_generator(monkeypatch):
"""LCM re-noises the sample on every step. With a seeded generator the result must not depend