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(flux): correct scheduler integration and default to Diffusers Euler

JPPhotoc6b8e9bbd302
diff --git a/invokeai/app/invocations/flux/flux_denoise.py b/invokeai/app/invocations/flux/flux_denoise.py
index 19f0924c94..d65640ad1f 100644
--- a/invokeai/app/invocations/flux/flux_denoise.py
+++ b/invokeai/app/invocations/flux/flux_denoise.py
@@ -298,7 +298,7 @@ class FluxDenoiseInvocation(BaseInvocation):
shift=not is_schnell,
)
- # Create scheduler if not using default euler
+ # Create the selected Diffusers scheduler.
scheduler = None
if self.scheduler in FLUX_SCHEDULER_MAP:
scheduler_class = FLUX_SCHEDULER_MAP[self.scheduler]
@@ -322,12 +322,9 @@ class FluxDenoiseInvocation(BaseInvocation):
# Noise the orig_latents by the appropriate amount for the first
# timestep in InvokeAI's clipped schedule.
#
- # Known limitation: if the selected scheduler later replaces this
- # schedule with its own first effective timestep/sigma (for example
- # Heun internal expansion or LCM's scheduler-defined schedule), the
- # img2img preblend below may not match that scheduler's true first
- # step exactly. This is an existing pipeline limitation and affects
- # both internally generated noise and externally supplied noise.
+ # 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.
t_0 = timesteps[0]
x = t_0 * noise + (1.0 - t_0) * init_latents
else:
diff --git a/invokeai/backend/flux/denoise.py b/invokeai/backend/flux/denoise.py
index 7b29a58d44..ce025d9ae6 100644
--- a/invokeai/backend/flux/denoise.py
+++ b/invokeai/backend/flux/denoise.py
@@ -3,6 +3,7 @@ import math
from typing import Callable
import torch
+from diffusers import FlowMatchEulerDiscreteScheduler, FlowMatchHeunDiscreteScheduler
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from tqdm import tqdm
@@ -13,6 +14,7 @@ from invokeai.backend.flux.extensions.regional_prompting_extension import Region
from invokeai.backend.flux.extensions.xlabs_controlnet_extension import XLabsControlNetExtension
from invokeai.backend.flux.extensions.xlabs_ip_adapter_extension import XLabsIPAdapterExtension
from invokeai.backend.flux.model import Flux
+from invokeai.backend.flux.schedulers import is_flow_match_lcm_scheduler, set_heun_timesteps_from_sigmas
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.util.devices import TorchDevice
@@ -41,40 +43,46 @@ def denoise(
img_cond_seq_ids: torch.Tensor | None = None,
# DyPE extension for high-resolution generation
dype_extension: DyPEExtension | None = None,
- # Optional scheduler for alternative sampling methods
+ # Defaults to Diffusers Euler when omitted.
scheduler: SchedulerMixin | None = None,
):
- # Determine if we're using a diffusers scheduler or the built-in Euler method
- use_scheduler = scheduler is not None
-
- if use_scheduler:
- # Initialize scheduler with timesteps
- # The timesteps list contains values in [0, 1] range (sigmas)
- # LCM should use num_inference_steps (it has its own sigma schedule),
- # while other schedulers can use custom sigmas if supported
- is_lcm = scheduler.__class__.__name__ == "FlowMatchLCMScheduler"
- set_timesteps_sig = inspect.signature(scheduler.set_timesteps)
- if not is_lcm and "sigmas" in set_timesteps_sig.parameters:
- # Scheduler supports custom sigmas - use InvokeAI's time-shifted schedule
- scheduler.set_timesteps(sigmas=timesteps, device=img.device)
- else:
- # LCM or scheduler doesn't support custom sigmas - use num_inference_steps
- # The schedule will be computed by the scheduler itself.
- #
- # 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)
-
- # For schedulers like Heun, the number of actual steps may differ
- # (Heun doubles timesteps internally)
- num_scheduler_steps = len(scheduler.timesteps)
- # For user-facing step count, use the original number of denoising steps
- total_steps = len(timesteps) - 1
+ if len(timesteps) <= 1:
+ return img
+ if scheduler is None:
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000)
+
+ # Initialize scheduler with timesteps
+ # The timesteps list contains values in [0, 1] range (sigmas)
+ # LCM should use num_inference_steps (it has its own sigma schedule),
+ # while other schedulers can use custom sigmas if supported
+ is_lcm = is_flow_match_lcm_scheduler(scheduler)
+ set_timesteps_sig = inspect.signature(scheduler.set_timesteps)
+ if isinstance(scheduler, FlowMatchHeunDiscreteScheduler):
+ set_heun_timesteps_from_sigmas(scheduler, timesteps[:-1], timesteps[-1], img.device)
+ elif not is_lcm and "sigmas" in set_timesteps_sig.parameters:
+ # InvokeAI supplies model-evaluation sigmas plus its requested terminal endpoint.
+ scheduler.set_timesteps(sigmas=timesteps[:-1], device=img.device)
+ if hasattr(scheduler, "sigmas"):
+ scheduler.sigmas[-1] = torch.as_tensor(
+ timesteps[-1], dtype=scheduler.sigmas.dtype, device=scheduler.sigmas.device
+ )
else:
- total_steps = len(timesteps) - 1
- num_scheduler_steps = total_steps
+ # LCM or scheduler doesn't support custom sigmas - use num_inference_steps
+ # The schedule will be computed by the scheduler itself. For LCM,
+ # clipping controls the requested step count but not exact start/end
+ # sigmas; keep that scheduler-defined behavior intact.
+ #
+ # 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)
+
+ # For schedulers like Heun, the number of actual steps may differ
+ # (Heun doubles timesteps internally)
+ num_scheduler_steps = len(scheduler.timesteps)
+ # For user-facing step count, use the original number of denoising steps
+ total_steps = len(timesteps) - 1
# guidance_vec is ignored for schnell.
guidance_vec = torch.full((img.shape[0],), guidance, device=img.device, dtype=img.dtype)
@@ -92,200 +100,38 @@ def denoise(
# Track the actual step for user-facing progress (accounts for Heun's double steps)
user_step = 0
- if use_scheduler:
- # Use diffusers scheduler for stepping
- # Use tqdm with total_steps (user-facing steps) not num_scheduler_steps (internal steps)
- # This ensures progress bar shows 1/8, 2/8, etc. even when scheduler uses more internal steps
- pbar = tqdm(total=total_steps, desc=f"Denoising{TorchDevice.get_session_device_label()}")
- for step_index in range(num_scheduler_steps):
- timestep = scheduler.timesteps[step_index]
- # Convert scheduler timestep (0-1000) to normalized (0-1) for the model
- t_curr = timestep.item() / scheduler.config.num_train_timesteps
- dype_sigma = DyPEExtension.resolve_step_sigma(
- fallback_sigma=t_curr,
- step_index=step_index,
- scheduler_sigmas=getattr(scheduler, "sigmas", None),
- )
- t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
-
- # DyPE: Update step state for timestep-dependent scaling
- if dype_extension is not None and dype_embedder is not None:
- dype_extension.update_step_state(
- embedder=dype_embedder,
- sigma=dype_sigma,
- )
-
- # For Heun scheduler, track if we're in first or second order step
- is_heun = hasattr(scheduler, "state_in_first_order")
- in_first_order = scheduler.state_in_first_order if is_heun else True
-
- # Run ControlNet models
- controlnet_residuals: list[ControlNetFluxOutput] = []
- for controlnet_extension in controlnet_extensions:
- controlnet_residuals.append(
- controlnet_extension.run_controlnet(
- timestep_index=user_step,
- total_num_timesteps=total_steps,
- img=img,
- img_ids=img_ids,
- txt=pos_regional_prompting_extension.regional_text_conditioning.t5_embeddings,
- txt_ids=pos_regional_prompting_extension.regional_text_conditioning.t5_txt_ids,
- y=pos_regional_prompting_extension.regional_text_conditioning.clip_embeddings,
- timesteps=t_vec,
- guidance=guidance_vec,
- )
- )
-
- merged_controlnet_residuals = sum_controlnet_flux_outputs(controlnet_residuals)
-
- # Prepare input for model
- img_input = img
- img_input_ids = img_ids
-
- if img_cond is not None:
- img_input = torch.cat((img_input, img_cond), dim=-1)
-
- if img_cond_seq is not None:
- assert img_cond_seq_ids is not None
- img_input = torch.cat((img_input, img_cond_seq), dim=1)
- img_input_ids = torch.cat((img_input_ids, img_cond_seq_ids), dim=1)
-
- pred = model(
- img=img_input,
- img_ids=img_input_ids,
- txt=pos_regional_prompting_extension.regional_text_conditioning.t5_embeddings,
- txt_ids=pos_regional_prompting_extension.regional_text_conditioning.t5_txt_ids,
- y=pos_regional_prompting_extension.regional_text_conditioning.clip_embeddings,
- timesteps=t_vec,
- guidance=guidance_vec,
- timestep_index=user_step,
- total_num_timesteps=total_steps,
- controlnet_double_block_residuals=merged_controlnet_residuals.double_block_residuals,
- controlnet_single_block_residuals=merged_controlnet_residuals.single_block_residuals,
- ip_adapter_extensions=pos_ip_adapter_extensions,
- regional_prompting_extension=pos_regional_prompting_extension,
- )
-
- if img_cond_seq is not None:
- pred = pred[:, :original_seq_len]
-
- # Get CFG scale for current user step
- step_cfg_scale = cfg_scale[min(user_step, len(cfg_scale) - 1)]
-
- if not math.isclose(step_cfg_scale, 1.0):
- if neg_regional_prompting_extension is None:
- raise ValueError("Negative text conditioning is required when cfg_scale is not 1.0.")
-
- neg_img_input = img
- neg_img_input_ids = img_ids
-
- if img_cond is not None:
- neg_img_input = torch.cat((neg_img_input, img_cond), dim=-1)
-
- if img_cond_seq is not None:
- neg_img_input = torch.cat((neg_img_input, img_cond_seq), dim=1)
- neg_img_input_ids = torch.cat((neg_img_input_ids, img_cond_seq_ids), dim=1)
-
- neg_pred = model(
- img=neg_img_input,
- img_ids=neg_img_input_ids,
- txt=neg_regional_prompting_extension.regional_text_conditioning.t5_embeddings,
- txt_ids=neg_regional_prompting_extension.regional_text_conditioning.t5_txt_ids,
- y=neg_regional_prompting_extension.regional_text_conditioning.clip_embeddings,
- timesteps=t_vec,
- guidance=guidance_vec,
- timestep_index=user_step,
- total_num_timesteps=total_steps,
- controlnet_double_block_residuals=None,
- controlnet_single_block_residuals=None,
- ip_adapter_extensions=neg_ip_adapter_extensions,
- regional_prompting_extension=neg_regional_prompting_extension,
- )
-
- if img_cond_seq is not None:
- neg_pred = neg_pred[:, :original_seq_len]
- pred = neg_pred + step_cfg_scale * (pred - neg_pred)
-
- # Use scheduler.step() for the update
- step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img)
- img = step_output.prev_sample
-
- # Get t_prev for inpainting (next sigma value)
- if step_index + 1 < len(scheduler.sigmas):
- t_prev = scheduler.sigmas[step_index + 1].item()
- else:
- t_prev = 0.0
-
- if inpaint_extension is not None:
- img = inpaint_extension.merge_intermediate_latents_with_init_latents(img, t_prev)
-
- # For Heun, only increment user step after second-order step completes
- if is_heun:
- if not in_first_order:
- # Second order step completed
- user_step += 1
- # Only call step_callback if we haven't exceeded total_steps
- if user_step <= total_steps:
- pbar.update(1)
- preview_img = img - t_curr * pred
- if inpaint_extension is not None:
- preview_img = inpaint_extension.merge_intermediate_latents_with_init_latents(
- preview_img, 0.0
- )
- step_callback(
- PipelineIntermediateState(
- step=user_step,
- order=2,
- total_steps=total_steps,
- timestep=int(t_curr * 1000),
- latents=preview_img,
- ),
- )
- else:
- # For LCM and other first-order schedulers
- user_step += 1
- # Only call step_callback if we haven't exceeded total_steps
- # (LCM scheduler may have more internal steps than user-facing steps)
- if user_step <= total_steps:
- pbar.update(1)
- preview_img = img - t_curr * pred
- if inpaint_extension is not None:
- preview_img = inpaint_extension.merge_intermediate_latents_with_init_latents(
- preview_img, 0.0
- )
- step_callback(
- PipelineIntermediateState(
- step=user_step,
- order=1,
- total_steps=total_steps,
- timestep=int(t_curr * 1000),
- latents=preview_img,
- ),
- )
-
- pbar.close()
- return img
+ # Use diffusers scheduler for stepping
+ # Use tqdm with total_steps (user-facing steps) not num_scheduler_steps (internal steps)
+ # This ensures progress bar shows 1/8, 2/8, etc. even when scheduler uses more internal steps
+ pbar = tqdm(total=total_steps, desc=f"Denoising{TorchDevice.get_session_device_label()}")
+ for step_index in range(num_scheduler_steps):
+ timestep = scheduler.timesteps[step_index]
+ # Convert scheduler timestep (0-1000) to normalized (0-1) for the model
+ t_curr = timestep.item() / scheduler.config.num_train_timesteps
+ dype_sigma = DyPEExtension.resolve_step_sigma(
+ fallback_sigma=t_curr,
+ step_index=step_index,
+ scheduler_sigmas=getattr(scheduler, "sigmas", None),
+ )
+ t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
- # Original Euler implementation (when scheduler is None)
- for step_index, (t_curr, t_prev) in tqdm(
- list(enumerate(zip(timesteps[:-1], timesteps[1:], strict=True))),
- desc=f"Denoising{TorchDevice.get_session_device_label()}",
- ):
# DyPE: Update step state for timestep-dependent scaling
if dype_extension is not None and dype_embedder is not None:
dype_extension.update_step_state(
embedder=dype_embedder,
- sigma=t_curr,
+ sigma=dype_sigma,
)
- t_vec = torch.full((img.shape[0],), t_curr, dtype=img.dtype, device=img.device)
+ # For Heun scheduler, track if we're in first or second order step
+ is_heun = hasattr(scheduler, "state_in_first_order")
+ in_first_order = scheduler.state_in_first_order if is_heun else True
- # Run ControlNet models.
+ # Run ControlNet models
controlnet_residuals: list[ControlNetFluxOutput] = []
for controlnet_extension in controlnet_extensions:
controlnet_residuals.append(
controlnet_extension.run_controlnet(
- timestep_index=step_index,
+ timestep_index=user_step,
total_num_timesteps=total_steps,
img=img,
img_ids=img_ids,
@@ -297,25 +143,17 @@ def denoise(
)
)
- # Merge the ControlNet residuals from multiple ControlNets.
- # TODO(ryand): We may want to calculate the sum just-in-time to keep peak memory low. Keep in mind, that the
- # controlnet_residuals datastructure is efficient in that it likely contains multiple references to the same
- # tensors. Calculating the sum materializes each tensor into its own instance.
merged_controlnet_residuals = sum_controlnet_flux_outputs(controlnet_residuals)
- # Prepare input for model - concatenate fresh each step
+ # Prepare input for model
img_input = img
img_input_ids = img_ids
- # Add channel-wise conditioning (for ControlNet, FLUX Fill, etc.)
if img_cond is not None:
img_input = torch.cat((img_input, img_cond), dim=-1)
- # Add sequence-wise conditioning (for Kontext)
if img_cond_seq is not None:
- assert img_cond_seq_ids is not None, (
- "You need to provide either both or neither of the sequence conditioning"
- )
+ assert img_cond_seq_ids is not None
img_input = torch.cat((img_input, img_cond_seq), dim=1)
img_input_ids = torch.cat((img_input_ids, img_cond_seq_ids), dim=1)
@@ -327,7 +165,7 @@ def denoise(
y=pos_regional_prompting_extension.regional_text_conditioning.clip_embeddings,
timesteps=t_vec,
guidance=guidance_vec,
- timestep_index=step_index,
+ timestep_index=user_step,
total_num_timesteps=total_steps,
controlnet_double_block_residuals=merged_controlnet_residuals.double_block_residuals,
controlnet_single_block_residuals=merged_controlnet_residuals.single_block_residuals,
@@ -335,33 +173,22 @@ def denoise(
regional_prompting_extension=pos_regional_prompting_extension,
)
- # Slice prediction to only include the main image tokens
if img_cond_seq is not None:
pred = pred[:, :original_seq_len]
- step_cfg_scale = cfg_scale[step_index]
+ # Get CFG scale for current user step
+ step_cfg_scale = cfg_scale[min(user_step, len(cfg_scale) - 1)]
- # If step_cfg_scale, is 1.0, then we don't need to run the negative prediction.
if not math.isclose(step_cfg_scale, 1.0):
- # TODO(ryand): Add option to run positive and negative predictions in a single batch for better performance
- # on systems with sufficient VRAM.
-
if neg_regional_prompting_extension is None:
raise ValueError("Negative text conditioning is required when cfg_scale is not 1.0.")
- # For negative prediction with Kontext, we need to include the reference images
- # to maintain consistency between positive and negative passes. Without this,
- # CFG would create artifacts as the attention mechanism would see different
- # spatial structures in each pass
neg_img_input = img
neg_img_input_ids = img_ids
- # Add channel-wise conditioning for negative pass if present
if img_cond is not None:
neg_img_input = torch.cat((neg_img_input, img_cond), dim=-1)
- # Add sequence-wise conditioning (Kontext) for negative pass
- # This ensures reference images are processed consistently
if img_cond_seq is not None:
neg_img_input = torch.cat((neg_img_input, img_cond_seq), dim=1)
neg_img_input_ids = torch.cat((neg_img_input_ids, img_cond_seq_ids), dim=1)
@@ -374,7 +201,7 @@ def denoise(
y=neg_regional_prompting_extension.regional_text_conditioning.clip_embeddings,
timesteps=t_vec,
guidance=guidance_vec,
- timestep_index=step_index,
+ timestep_index=user_step,
total_num_timesteps=total_steps,
controlnet_double_block_residuals=None,
controlnet_single_block_residuals=None,
@@ -382,28 +209,73 @@ def denoise(
regional_prompting_extension=neg_regional_prompting_extension,
)
- # Slice negative prediction to match main image tokens
if img_cond_seq is not None:
neg_pred = neg_pred[:, :original_seq_len]
pred = neg_pred + step_cfg_scale * (pred - neg_pred)
- preview_img = img - t_curr * pred
- img = img + (t_prev - t_curr) * pred
+ # Use the sample and sigma from this model evaluation. This is also
+ # the clean prediction used by Heun and FlowMatch LCM internally.
+ should_emit_preview = (
+ not is_heun or not in_first_order or step_index == num_scheduler_steps - 1
+ ) and user_step < total_steps
+ preview_img = img - t_curr * pred if should_emit_preview else None
+
+ # Use scheduler.step() for the update
+ step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img)
+ img = step_output.prev_sample
+
+ # Get t_prev for inpainting (next sigma value)
+ if step_index + 1 < len(scheduler.sigmas):
+ t_prev = scheduler.sigmas[step_index + 1].item()
+ else:
+ t_prev = 0.0
if inpaint_extension is not None:
img = inpaint_extension.merge_intermediate_latents_with_init_latents(img, t_prev)
- preview_img = inpaint_extension.merge_intermediate_latents_with_init_latents(preview_img, 0.0)
-
- step_callback(
- PipelineIntermediateState(
- step=step_index + 1,
- order=1,
- total_steps=total_steps,
- timestep=int(t_curr),
- latents=preview_img,
- ),
- )
+ # For Heun, only increment user step after second-order step completes
+ if is_heun:
+ if not in_first_order or step_index == num_scheduler_steps - 1:
+ # Second order step completed
+ user_step += 1
+ # Only call step_callback if we haven't exceeded total_steps
+ if user_step <= total_steps:
+ pbar.update(1)
+ assert preview_img is not None
+ if inpaint_extension is not None:
+ preview_img = inpaint_extension.merge_intermediate_latents_with_init_latents(
+ preview_img, 0.0
+ )
+ step_callback(
+ PipelineIntermediateState(
+ step=user_step,
+ order=2 if not in_first_order else 1,
+ total_steps=total_steps,
+ timestep=int(t_curr * 1000),
+ latents=preview_img,
+ ),
+ )
+ else:
+ # For LCM and other first-order schedulers
+ user_step += 1
+ # Only call step_callback if we haven't exceeded total_steps
+ # (LCM scheduler may have more internal steps than user-facing steps)
+ if user_step <= total_steps:
+ pbar.update(1)
+ assert preview_img is not None
+ if inpaint_extension is not None:
+ preview_img = inpaint_extension.merge_intermediate_latents_with_init_latents(preview_img, 0.0)
+ step_callback(
+ PipelineIntermediateState(
+ step=user_step,
+ order=1,
+ total_steps=total_steps,
+ timestep=int(t_curr * 1000),
+ latents=preview_img,
+ ),
+ )
+
+ pbar.close()
return img
finally:
diff --git a/invokeai/backend/flux/schedulers.py b/invokeai/backend/flux/schedulers.py
index aac35a5093..82859ee99a 100644
--- a/invokeai/backend/flux/schedulers.py
+++ b/invokeai/backend/flux/schedulers.py
@@ -6,6 +6,7 @@ This module provides the scheduler types and mapping for Flow Matching models
from typing import Any, Literal, Type
+import torch
from diffusers import (
DPMSolverMultistepScheduler,
FlowMatchEulerDiscreteScheduler,
@@ -43,6 +44,37 @@ if _HAS_LCM:
FLUX_SCHEDULER_MAP["lcm"] = FlowMatchLCMScheduler
+def set_heun_timesteps_from_sigmas(
+ scheduler: FlowMatchHeunDiscreteScheduler,
+ sigmas: list[float],
+ terminal_sigma: float,
+ device: str | torch.device | None,
+) -> None:
+ """Set the pinned Diffusers Heun layout from InvokeAI's shifted model sigmas."""
+ if not sigmas:
+ raise ValueError("At least one model-evaluation sigma is required")
+
+ # Diffusers 0.40.0 evaluates the first sigma once, later sigmas twice, then
+ # uses one terminal interval without a second-order evaluation.
+ model_sigmas = torch.tensor(sigmas, dtype=torch.float32, device=device)
+ expanded_sigmas = torch.cat((model_sigmas[:1], model_sigmas[1:].repeat_interleave(2)))
+ scheduler.num_inference_steps = len(sigmas)
+ scheduler.timesteps = expanded_sigmas * scheduler.config.num_train_timesteps
+ scheduler.sigmas = torch.cat((expanded_sigmas, model_sigmas.new_tensor([terminal_sigma])))
+
+ # Reset the state used by Diffusers step() and state_in_first_order.
+ scheduler.prev_derivative = None
+ scheduler.dt = None
+ scheduler.sample = None
+ scheduler._step_index = None
+ scheduler._begin_index = None
+
+
+def is_flow_match_lcm_scheduler(scheduler: SchedulerMixin) -> bool:
+ """Check the optional LCM scheduler without requiring it in older Diffusers builds."""
+ return _HAS_LCM and isinstance(scheduler, FlowMatchLCMScheduler)
+
+
# Z-Image scheduler types (Flow Matching schedulers)
# Note: Z-Image-Turbo is optimized for ~8 steps with Euler, LCM can also work.
# Z-Image Base (undistilled) should only use Euler or Heun (LCM not supported for undistilled models).
diff --git a/tests/app/invocations/test_denoise_noise_inputs.py b/tests/app/invocations/test_denoise_noise_inputs.py
index 40cf0836b4..c9d7a17cb4 100644
--- a/tests/app/invocations/test_denoise_noise_inputs.py
+++ b/tests/app/invocations/test_denoise_noise_inputs.py
@@ -19,7 +19,12 @@ 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 ZImageDenoiseInvocation
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional, get_schedule
-from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP, FLUX_SCHEDULER_MAP, ZIMAGE_SCHEDULER_MAP
+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, ModelType
@@ -591,8 +596,17 @@ def test_denoise_metadata_persists_hidiffusion_fields_when_disabled():
def _get_first_scheduler_sigma(
- scheduler, *, scheduler_name: str, sigmas: list[float], mu: float | None = None
+ 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"}
@@ -611,13 +625,7 @@ def _get_first_scheduler_sigma(
"scheduler_name",
[
"euler",
- pytest.param(
- "heun",
- marks=pytest.mark.xfail(
- reason="Known img2img preblend mismatch for FLUX with scheduler-defined first step.",
- strict=True,
- ),
- ),
+ "heun",
pytest.param(
"lcm",
marks=pytest.mark.xfail(
@@ -633,7 +641,12 @@ def test_flux_img2img_preblend_matches_scheduler_first_sigma(scheduler_name: str
scheduler = scheduler_class(num_train_timesteps=1000)
assert sigmas[0] == pytest.approx(
- _get_first_scheduler_sigma(scheduler, scheduler_name=scheduler_name, sigmas=sigmas)
+ _get_first_scheduler_sigma(
+ scheduler,
+ scheduler_name=scheduler_name,
+ sigmas=sigmas,
+ use_flux_heun_schedule=True,
+ )
)
diff --git a/tests/backend/flux/test_denoise.py b/tests/backend/flux/test_denoise.py
index 47065cc21f..27f18ca557 100644
--- a/tests/backend/flux/test_denoise.py
+++ b/tests/backend/flux/test_denoise.py
@@ -2,9 +2,10 @@ from types import SimpleNamespace
import pytest
import torch
+from diffusers import FlowMatchEulerDiscreteScheduler, FlowMatchHeunDiscreteScheduler
from invokeai.backend.flux.denoise import denoise
-from invokeai.backend.flux.schedulers import FLUX_SCHEDULER_MAP
+from invokeai.backend.flux.schedulers import _HAS_LCM, FLUX_SCHEDULER_MAP
class _FakeFluxModel:
@@ -27,6 +28,48 @@ class _FakeFluxModel:
return torch.zeros_like(img)
+class _ConstantFluxModel:
+ def __init__(self, value: float) -> None:
+ self.value = value
+ self.timesteps: list[float] = []
+
+ def __call__(self, img: torch.Tensor, timesteps: torch.Tensor, **kwargs: object) -> torch.Tensor:
+ del kwargs
+ self.timesteps.append(float(timesteps[0]))
+ return torch.full_like(img, self.value)
+
+
+class _PromptFluxModel:
+ def __init__(self) -> None:
+ self.outputs: list[float] = []
+
+ def __call__(self, img: torch.Tensor, txt: torch.Tensor, **kwargs: object) -> torch.Tensor:
+ del kwargs
+ value = float(txt.mean())
+ self.outputs.append(value)
+ return torch.full_like(img, value)
+
+
+class _SampleDependentFluxModel:
+ def __init__(self) -> None:
+ self.evaluations: list[tuple[float, torch.Tensor]] = []
+
+ def __call__(self, img: torch.Tensor, timesteps: torch.Tensor, **kwargs: object) -> torch.Tensor:
+ del kwargs
+ sigma = float(timesteps[0])
+ self.evaluations.append((sigma, img.clone()))
+ return 0.1 * img + 0.2 * sigma
+
+
+class _RecordingInpaintExtension:
+ def __init__(self) -> None:
+ self.sigmas: list[float] = []
+
+ def merge_intermediate_latents_with_init_latents(self, img: torch.Tensor, sigma: float) -> torch.Tensor:
+ self.sigmas.append(sigma)
+ return img
+
+
class _FakeDyPEExtension:
def __init__(self) -> None:
self.sigmas: list[float] = []
@@ -46,7 +89,7 @@ class _FakeScheduler:
def set_timesteps(self, sigmas: list[float], device: torch.device) -> None:
del device
- self.sigmas = torch.tensor(sigmas, dtype=torch.float32)
+ self.sigmas = torch.tensor([*sigmas, 0.0], dtype=torch.float32)
self.timesteps = torch.tensor([900.0, 400.0], dtype=torch.float32)
def step(self, model_output: torch.Tensor, timestep: torch.Tensor, sample: torch.Tensor) -> SimpleNamespace:
@@ -247,3 +290,224 @@ def test_denoise_real_flux_schedulers_update_dype_from_internal_sigma_schedule(m
expected_sigmas = [float(sigma) for sigma in scheduler.sigmas[: len(dype_extension.sigmas)]]
assert dype_extension.sigmas == expected_sigmas
assert callback_steps
+
+
+def _run_with_scheduler(scheduler, timesteps: list[float], **kwargs):
+ model = kwargs.pop("model", _ConstantFluxModel(0.25))
+ img = kwargs.pop("img", torch.tensor([[[1.0], [-0.5]]], dtype=torch.float32))
+ callbacks = []
+ result = denoise(
+ model=model,
+ img=img,
+ img_ids=torch.zeros(1, img.shape[1], 3),
+ pos_regional_prompting_extension=_build_regional_prompting_extension(batch_size=1),
+ neg_regional_prompting_extension=None,
+ timesteps=timesteps,
+ step_callback=callbacks.append,
+ guidance=1.0,
+ cfg_scale=[1.0] * (len(timesteps) - 1),
+ inpaint_extension=None,
+ controlnet_extensions=[],
+ pos_ip_adapter_extensions=[],
+ neg_ip_adapter_extensions=[],
+ img_cond=None,
+ scheduler=scheduler,
+ **kwargs,
+ )
+ return result, img, model, callbacks
+
+
[email protected]("terminal_sigma", [0.0, 0.2])
+def test_euler_uses_model_sigmas_and_requested_terminal_sigma(monkeypatch, terminal_sigma):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [1.0, 0.7, 0.35, terminal_sigma]
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=1.0)
+
+ result, img, model, callbacks = _run_with_scheduler(scheduler, schedule)
+
+ expected = img + (terminal_sigma - schedule[0]) * 0.25
+ assert torch.allclose(result, expected)
+ assert len(model.timesteps) == len(schedule) - 1
+ assert model.timesteps == pytest.approx(schedule[:-1])
+ assert len(scheduler.timesteps) == len(schedule) - 1
+ assert torch.equal(scheduler.sigmas[-1], torch.tensor(terminal_sigma))
+ assert len(callbacks) == len(schedule) - 1
+ assert scheduler.step_index == len(schedule) - 1
+
+
[email protected]("terminal_sigma", [0.0, 0.2])
+def test_default_scheduler_matches_explicit_euler_and_clean_preview(monkeypatch, terminal_sigma):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [1.0, 0.7, 0.35, terminal_sigma]
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=1.0)
+
+ scheduled, img, _, callbacks = _run_with_scheduler(scheduler, schedule)
+ default, _, model, default_callbacks = _run_with_scheduler(None, schedule)
+
+ assert torch.equal(scheduled, default)
+ assert model.timesteps == pytest.approx(schedule[:-1])
+ assert [callback.timestep for callback in default_callbacks] == [1000, 700, 350]
+ assert [callback.step for callback in default_callbacks] == [1, 2, 3]
+ assert all(callback.order == 1 and callback.total_steps == 3 for callback in default_callbacks)
+ for explicit_callback, default_callback in zip(callbacks, default_callbacks, strict=True):
+ assert torch.equal(explicit_callback.latents, default_callback.latents)
+ expected_clean = img - 0.25
+ assert all(torch.allclose(callback.latents, expected_clean) for callback in callbacks)
+
+
+def test_heun_uses_custom_schedule_and_completes_each_user_step(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [1.0, 0.7, 0.35, 0.2]
+ scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000)
+
+ result, img, model, callbacks = _run_with_scheduler(scheduler, schedule)
+
+ expected = img + (schedule[-1] - schedule[0]) * 0.25
+ expected_timesteps = torch.tensor([1000.0, 700.0, 700.0, 350.0, 350.0])
+ expected_sigmas = torch.tensor([1.0, 0.7, 0.7, 0.35, 0.35, 0.2])
+ assert torch.allclose(result, expected, atol=1e-6, rtol=0)
+ assert torch.equal(scheduler.timesteps.cpu(), expected_timesteps)
+ assert torch.equal(scheduler.sigmas.cpu(), expected_sigmas)
+ assert len(model.timesteps) == 2 * (len(schedule) - 1) - 1
+ assert [callback.step for callback in callbacks] == [1, 2, 3]
+ assert [callback.order for callback in callbacks] == [2, 2, 1]
+
+
+def test_heun_partial_start_and_end_use_custom_sigmas(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [0.7, 0.45, 0.2]
+ scheduler = FLUX_SCHEDULER_MAP["heun"](num_train_timesteps=1000)
+
+ result, img, model, callbacks = _run_with_scheduler(scheduler, schedule)
+
+ assert torch.allclose(result, img + (0.2 - 0.7) * 0.25, atol=1e-6, rtol=0)
+ assert torch.equal(scheduler.timesteps.cpu(), torch.tensor([700.0, 450.0, 450.0]))
+ assert torch.equal(scheduler.sigmas.cpu(), torch.tensor([0.7, 0.45, 0.45, 0.2]))
+ assert len(model.timesteps) == 3
+ assert [callback.step for callback in callbacks] == [1, 2]
+ assert [callback.order for callback in callbacks] == [2, 1]
+
+
+def test_heun_preserves_cfg_and_inpainting_callback_behavior(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ img = torch.tensor([[[1.0]]])
+ schedule = [1.0, 0.7, 0.35, 0.0]
+ scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000)
+ model = _PromptFluxModel()
+ extension = _RecordingInpaintExtension()
+ prompt = _build_regional_prompting_extension(batch_size=1)
+ negative_prompt = _build_regional_prompting_extension(batch_size=1)
+ prompt.regional_text_conditioning.t5_embeddings.fill_(1.0)
+ negative_prompt.regional_text_conditioning.t5_embeddings.fill_(-1.0)
+ callbacks = []
+
+ result = denoise(
+ model=model,
+ img=img,
+ img_ids=torch.zeros(1, 1, 3),
+ pos_regional_prompting_extension=prompt,
+ neg_regional_prompting_extension=negative_prompt,
+ timesteps=schedule,
+ step_callback=callbacks.append,
+ guidance=1.0,
+ cfg_scale=[2.0] * (len(schedule) - 1),
+ inpaint_extension=extension,
+ controlnet_extensions=[],
+ pos_ip_adapter_extensions=[],
+ neg_ip_adapter_extensions=[],
+ img_cond=None,
+ scheduler=scheduler,
+ )
+
+ guided_prediction = -1.0 + 2.0 * (1.0 - -1.0)
+ assert torch.allclose(result, img + (schedule[-1] - schedule[0]) * guided_prediction)
+ assert model.outputs == [1.0, -1.0] * 5
+ assert [callback.step for callback in callbacks] == [1, 2, 3]
+ assert [callback.order for callback in callbacks] == [2, 2, 1]
+ assert all(torch.allclose(callback.latents, img - guided_prediction) for callback in callbacks)
+ assert extension.sigmas == pytest.approx([0.7, 0.7, 0.0, 0.35, 0.35, 0.0, 0.0, 0.0])
+
+
+def test_heun_keeps_second_order_correction_for_sample_dependent_predictions(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ schedule = [0.9, 0.6, 0.3, 0.1]
+ scheduler = FLUX_SCHEDULER_MAP["heun"](num_train_timesteps=1000)
+ model = _SampleDependentFluxModel()
+
+ result, img, _, callbacks = _run_with_scheduler(scheduler, schedule, model=model)
+
+ expected = img.clone()
+ for index, sigma in enumerate(schedule[:-2]):
+ sigma_next = schedule[index + 1]
+ first_prediction = 0.1 * expected + 0.2 * sigma
+ euler_sample = expected + (sigma_next - sigma) * first_prediction
+ second_prediction = 0.1 * euler_sample + 0.2 * sigma_next
+ expected = expected + (sigma_next - sigma) * (first_prediction + second_prediction) / 2
+ terminal_prediction = 0.1 * expected + 0.2 * schedule[-2]
+ expected = expected + (schedule[-1] - schedule[-2]) * terminal_prediction
+
+ assert torch.allclose(result, expected, atol=1e-6, rtol=0)
+ assert len(model.evaluations) == 2 * (len(schedule) - 1) - 1
+ assert [callback.order for callback in callbacks] == [2, 2, 1]
+
+
+def test_scheduler_preview_preserves_cfg_and_inpainting_callback(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ img = torch.tensor([[[1.0]]])
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=1.0)
+ model = _PromptFluxModel()
+ extension = _RecordingInpaintExtension()
+ prompt = _build_regional_prompting_extension(batch_size=1)
+ negative_prompt = _build_regional_prompting_extension(batch_size=1)
+ prompt.regional_text_conditioning.t5_embeddings.fill_(1.0)
+ negative_prompt.regional_text_conditioning.t5_embeddings.fill_(-1.0)
+ callbacks = []
+ result = denoise(
+ model=model,
+ img=img,
+ img_ids=torch.zeros(1, 1, 3),
+ pos_regional_prompting_extension=prompt,
+ neg_regional_prompting_extension=negative_prompt,
+ timesteps=[1.0, 0.5, 0.0],
+ step_callback=callbacks.append,
+ guidance=1.0,
+ cfg_scale=[2.0, 2.0],
+ inpaint_extension=extension,
+ controlnet_extensions=[],
+ pos_ip_adapter_extensions=[],
+ neg_ip_adapter_extensions=[],
+ img_cond=None,
+ scheduler=scheduler,
+ )
+
+ guided_prediction = -1.0 + 2.0 * (1.0 - -1.0)
+ assert torch.allclose(result, img + (0.0 - 1.0) * guided_prediction)
+ assert model.outputs == [1.0, -1.0, 1.0, -1.0]
+ assert [callback.step for callback in callbacks] == [1, 2]
+ assert all(torch.allclose(callback.latents, img - guided_prediction) for callback in callbacks)
+ assert extension.sigmas == [0.5, 0.0, 0.0, 0.0]
+
+
[email protected](not _HAS_LCM, reason="FlowMatchLCMScheduler not available in this Diffusers version")
+def test_lcm_preview_uses_the_model_evaluation_sample_and_sigma(monkeypatch):
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+ scheduler = FLUX_SCHEDULER_MAP["lcm"](num_train_timesteps=1000)
+ result, img, model, callbacks = _run_with_scheduler(scheduler, [1.0, 0.5, 0.0])
+
+ current_sigma = scheduler.timesteps[0] / scheduler.config.num_train_timesteps
+ expected_preview = img - current_sigma * 0.25
+ assert result.shape == img.shape
+ assert len(model.timesteps) == len(scheduler.timesteps) == len(callbacks) == 2
+ assert model.timesteps == pytest.approx(
+ [float(timestep / scheduler.config.num_train_timesteps) for timestep in scheduler.timesteps]
+ )
+ assert torch.allclose(callbacks[0].latents, expected_preview)
+
+
[email protected]("schedule", [[], [0.4]])
+def test_default_scheduler_without_intervals_returns_input(schedule):
+ result, img, model, callbacks = _run_with_scheduler(None, schedule)
+
+ assert result is img
+ assert model.timesteps == []
+ assert callbacks == []