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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(model): Add ER SDE / DPM++ 2M Scheduler Support For Anima (#9125)
kappacommit25bbf32a6505
diff --git a/invokeai/app/invocations/anima_denoise.py b/invokeai/app/invocations/anima_denoise.pyindex 530bf2918f..0016a4fd26 100644--- a/invokeai/app/invocations/anima_denoise.py+++ b/invokeai/app/invocations/anima_denoise.py@@ -16,14 +16,12 @@ Key differences from Z-Image denoise:- Anima uses 3D latents directly, Z-Image converts 4D -> list of 5D"""-import inspectimport mathfrom contextlib import ExitStackfrom typing import Callable, Iterator, Optional, Tupleimport torchimport torchvision.transforms as tv_transforms-from diffusers.schedulers.scheduling_utils import SchedulerMixinfrom torchvision.transforms.functional import resize as tv_resizefrom tqdm import tqdm@@ -42,7 +40,12 @@ from invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.anima.anima_transformer_patch import patch_anima_for_regional_promptingfrom invokeai.backend.anima.conditioning_data import AnimaRegionalTextConditioning, AnimaTextConditioningfrom invokeai.backend.anima.regional_prompting import AnimaRegionalPromptingExtension-from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_LABELS, ANIMA_SCHEDULER_MAP, ANIMA_SCHEDULER_NAME_VALUES+from invokeai.backend.anima.scheduler_driver import AnimaSchedulerDriver+from invokeai.backend.flux.schedulers import (+ ANIMA_SCHEDULER_LABELS,+ ANIMA_SCHEDULER_NAME_VALUES,+ ANIMA_SHIFT,+)from invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcherfrom invokeai.backend.patches.lora_conversions.anima_lora_constants import ANIMA_LORA_TRANSFORMER_PREFIX@@ -59,8 +62,6 @@ from invokeai.backend.util.devices import TorchDeviceANIMA_LATENT_SCALE_FACTOR = 8# Anima uses 16 latent channelsANIMA_LATENT_CHANNELS = 16-# Anima uses fixed shift=3.0 for the rectified flow schedule-ANIMA_SHIFT = 3.0# Anima uses raw sigma values as timesteps (no rescaling)ANIMA_MULTIPLIER = 1.0@@ -165,7 +166,7 @@ class AnimaInpaintExtension(RectifiedFlowInpaintExtension):title="Denoise - Anima",tags=["image", "anima"],category="image",- version="1.2.0",+ version="1.5.0",classification=Classification.Prototype,)class AnimaDenoiseInvocation(BaseInvocation):@@ -491,22 +492,19 @@ class AnimaDenoiseInvocation(BaseInvocation):step_callback = self._build_step_callback(context)- # Initialize diffusers scheduler if not using built-in Euler- scheduler: SchedulerMixin | None = None+ # Initialize scheduler driver if not using built-in Euler.use_scheduler = self.scheduler != "euler"-+ driver: AnimaSchedulerDriver | None = Noneif use_scheduler:- scheduler_class = ANIMA_SCHEDULER_MAP[self.scheduler]- scheduler = scheduler_class(num_train_timesteps=1000, shift=1.0)- is_lcm = self.scheduler == "lcm"- set_timesteps_sig = inspect.signature(scheduler.set_timesteps)- if not is_lcm and "sigmas" in set_timesteps_sig.parameters:- scheduler.set_timesteps(sigmas=sigmas, device=device)- else:- scheduler.set_timesteps(num_inference_steps=total_steps, device=device)- num_scheduler_steps = len(scheduler.timesteps)- else:- num_scheduler_steps = total_steps+ driver = AnimaSchedulerDriver(+ scheduler_name=self.scheduler,+ sigmas=sigmas,+ steps=self.steps,+ denoising_start=self.denoising_start,+ denoising_end=self.denoising_end,+ device=device,+ seed=self.seed,+ )with ExitStack() as exit_stack:(cached_weights, transformer) = exit_stack.enter_context(transformer_info.model_on_device())@@ -587,19 +585,12 @@ class AnimaDenoiseInvocation(BaseInvocation):# t5xxl_ids=None skips the LLM Adapter — context is already pre-computed)- if use_scheduler and scheduler is not None:- # Scheduler-based denoising+ if driver is not None:user_step = 0pbar = tqdm(total=total_steps, desc="Denoising (Anima)")- for step_index in range(num_scheduler_steps):- sched_timestep = scheduler.timesteps[step_index]- sigma_curr = sched_timestep.item() / scheduler.config.num_train_timesteps-- is_heun = hasattr(scheduler, "state_in_first_order")- in_first_order = scheduler.state_in_first_order if is_heun else True-+ for it in driver.iterations():timestep = torch.tensor(- [sigma_curr * ANIMA_MULTIPLIER], device=device, dtype=inference_dtype+ [it.sigma_curr * ANIMA_MULTIPLIER], device=device, dtype=inference_dtype).expand(latents.shape[0])noise_pred_cond = _run_transformer(pos_context, latents, timestep).float()@@ -610,48 +601,30 @@ class AnimaDenoiseInvocation(BaseInvocation):else:noise_pred = noise_pred_cond- step_output = scheduler.step(model_output=noise_pred, timestep=sched_timestep, sample=latents)- latents = step_output.prev_sample-- if step_index + 1 < len(scheduler.sigmas):- sigma_prev = scheduler.sigmas[step_index + 1].item()- else:- sigma_prev = 0.0+ latents = driver.step(model_output=noise_pred, timestep=it.sched_timestep, sample=latents)- if inpaint_extension is not None:- latents_4d = latents.squeeze(2)- latents_4d = inpaint_extension.merge_intermediate_latents_with_init_latents(- latents_4d, sigma_prev- )- latents = latents_4d.unsqueeze(2)+ if it.completes_user_step:+ # RectifiedFlowInpaintExtension expects this once per user step (its+ # docstring), so for Heun we skip the FO half of each pair to avoid+ # corrupting the second-order corrector's input.+ if inpaint_extension is not None:+ latents_4d = latents.squeeze(2)+ latents_4d = inpaint_extension.merge_intermediate_latents_with_init_latents(+ latents_4d, it.sigma_prev+ )+ latents = latents_4d.unsqueeze(2)- if is_heun:- if not in_first_order:- user_step += 1- if user_step <= total_steps:- pbar.update(1)- step_callback(- PipelineIntermediateState(- step=user_step,- order=2,- total_steps=total_steps,- timestep=int(sigma_curr * 1000),- latents=latents.squeeze(2),- )- )- else:user_step += 1- if user_step <= total_steps:- pbar.update(1)- step_callback(- PipelineIntermediateState(- step=user_step,- order=1,- total_steps=total_steps,- timestep=int(sigma_curr * 1000),- latents=latents.squeeze(2),- )+ pbar.update(1)+ step_callback(+ PipelineIntermediateState(+ step=user_step,+ order=it.order,+ total_steps=total_steps,+ timestep=int(it.sigma_curr * 1000),+ latents=latents.squeeze(2),)+ )pbar.close()else:# Built-in Euler implementation (default for Anima)diff --git a/invokeai/backend/anima/scheduler_driver.py b/invokeai/backend/anima/scheduler_driver.pynew file mode 100644index 0000000000..854d133011--- /dev/null+++ b/invokeai/backend/anima/scheduler_driver.py@@ -0,0 +1,150 @@+"""Anima scheduler driver.++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.+* SDE-style schedulers receive a seeded ``torch.Generator`` on every step.++The denoise loop iterates :meth:`AnimaSchedulerDriver.iterations` and calls+:meth:`AnimaSchedulerDriver.step` per iteration; the driver yields the+``sigma_prev`` and ``completes_user_step`` flags the caller needs for inpaint+mixing and progress reporting.+"""++from __future__ import annotations++import inspect+from dataclasses import dataclass+from typing import Iterator++import torch+from diffusers import FlowMatchHeunDiscreteScheduler+from diffusers.schedulers.scheduling_utils import SchedulerMixin++from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP+++@dataclass(frozen=True)+class AnimaSchedulerIteration:+ """Per-iteration metadata yielded by :meth:`AnimaSchedulerDriver.iterations`.++ ``sigma_prev`` is the noise level the latents will be at after this iteration's+ :meth:`AnimaSchedulerDriver.step` call. ``completes_user_step`` is True when+ this iteration finishes a user-visible step — for Heun, the second-order+ half of each pair plus the unpaired terminal first-order step; for every+ other scheduler, always True.+ """++ sched_timestep: torch.Tensor+ sigma_curr: float+ sigma_prev: float+ completes_user_step: bool+ order: int+++class AnimaSchedulerDriver:+ """Drives a diffusers scheduler over Anima's pre-shifted sigma schedule."""++ def __init__(+ self,+ scheduler_name: str,+ sigmas: list[float],+ steps: int,+ denoising_start: float,+ denoising_end: float,+ device: torch.device,+ seed: int,+ ):+ scheduler_class, scheduler_kwargs = ANIMA_SCHEDULER_MAP[scheduler_name]+ self.scheduler: SchedulerMixin = scheduler_class(num_train_timesteps=1000, **scheduler_kwargs)+ # Heun toggles state_in_first_order during step(); detect by class so we+ # can read it before set_timesteps has run.+ self.is_heun: bool = isinstance(self.scheduler, FlowMatchHeunDiscreteScheduler)+ 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:+ 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"):+ 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.scheduler.set_begin_index(self._begin_index)+ else:+ self.scheduler.set_timesteps(num_inference_steps=len(sigmas) - 1, device=device)+ self._num_iterations = len(self.scheduler.timesteps)++ @property+ def num_iterations(self) -> int:+ """Total :meth:`step` calls. For Heun this is roughly 2× the user-visible step count."""+ return self._num_iterations++ @property+ def begin_index(self) -> int:+ return self._begin_index++ def iterations(self) -> Iterator[AnimaSchedulerIteration]:+ for i in range(self._num_iterations):+ sched_idx = i + self._begin_index+ sched_timestep = self.scheduler.timesteps[sched_idx]+ sigma_curr = sched_timestep.item() / self.scheduler.config.num_train_timesteps++ # Read state_in_first_order before step (Heun toggles it inside step()).+ in_first_order = self.scheduler.state_in_first_order if self.is_heun else True++ next_idx = sched_idx + 1+ 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+ 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(+ self,+ model_output: torch.Tensor,+ timestep: torch.Tensor,+ sample: torch.Tensor,+ ) -> torch.Tensor:+ step_output = self.scheduler.step(+ model_output=model_output,+ timestep=timestep,+ sample=sample,+ generator=self._step_generator,+ )+ return step_output.prev_sample++ @property+ def step_generator(self) -> torch.Generator:+ return self._step_generatordiff --git a/invokeai/backend/flux/schedulers.py b/invokeai/backend/flux/schedulers.pyindex 05e6bb085f..b35658d20f 100644--- a/invokeai/backend/flux/schedulers.py+++ b/invokeai/backend/flux/schedulers.py@@ -4,14 +4,17 @@ This module provides the scheduler types and mapping for Flow Matching models(Flux and Z-Image), supporting multiple schedulers from the diffusers library."""-from typing import Literal, Type+from typing import Any, Literal, Typefrom diffusers import (+ DPMSolverMultistepScheduler,FlowMatchEulerDiscreteScheduler,FlowMatchHeunDiscreteScheduler,)from diffusers.schedulers.scheduling_utils import SchedulerMixin+from invokeai.backend.rectified_flow.er_sde_scheduler import ERSDEScheduler+# Note: FlowMatchLCMScheduler may not be available in all diffusers versionstry:from diffusers import FlowMatchLCMScheduler@@ -62,21 +65,67 @@ if _HAS_LCM:ZIMAGE_SCHEDULER_MAP["lcm"] = FlowMatchLCMScheduler-# Anima scheduler types (same Flow Matching schedulers as Flux/Z-Image)-# Anima uses rectified flow with shift=3.0 and multiplier=1000.-# Recommended: 30 steps with Euler, CFG 4-5.-ANIMA_SCHEDULER_NAME_VALUES = Literal["euler", "heun", "lcm"]+# 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.++# Fixed shift factor for the Anima rectified-flow noise schedule.+ANIMA_SHIFT = 3.0++ANIMA_SCHEDULER_NAME_VALUES = Literal["euler", "heun", "dpmpp_2m", "dpmpp_2m_sde", "er_sde", "lcm"]ANIMA_SCHEDULER_LABELS: dict[str, str] = {"euler": "Euler","heun": "Heun (2nd order)",+ "dpmpp_2m": "DPM++ 2M",+ "dpmpp_2m_sde": "DPM++ 2M SDE",+ "er_sde": "ER-SDE","lcm": "LCM",}-ANIMA_SCHEDULER_MAP: dict[str, Type[SchedulerMixin]] = {- "euler": FlowMatchEulerDiscreteScheduler,- "heun": FlowMatchHeunDiscreteScheduler,+# 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.+ANIMA_SCHEDULER_MAP: dict[str, tuple[Type[SchedulerMixin], dict[str, Any]]] = {+ "euler": (FlowMatchEulerDiscreteScheduler, {"shift": 1.0}),+ "heun": (FlowMatchHeunDiscreteScheduler, {"shift": ANIMA_SHIFT}),+ "dpmpp_2m": (+ DPMSolverMultistepScheduler,+ {+ "prediction_type": "flow_prediction",+ "use_flow_sigmas": True,+ "flow_shift": ANIMA_SHIFT,+ "solver_order": 2,+ },+ ),+ "dpmpp_2m_sde": (+ DPMSolverMultistepScheduler,+ {+ "prediction_type": "flow_prediction",+ "use_flow_sigmas": True,+ "flow_shift": ANIMA_SHIFT,+ "algorithm_type": "sde-dpmsolver++",+ "solver_order": 2,+ },+ ),+ "er_sde": (+ ERSDEScheduler,+ {+ "prediction_type": "flow_prediction",+ "use_flow_sigmas": True,+ "flow_shift": ANIMA_SHIFT,+ "solver_order": 3,+ "stochastic": True,+ },+ ),}if _HAS_LCM:- ANIMA_SCHEDULER_MAP["lcm"] = FlowMatchLCMScheduler+ ANIMA_SCHEDULER_MAP["lcm"] = (FlowMatchLCMScheduler, {"shift": 1.0})diff --git a/invokeai/backend/rectified_flow/er_sde_scheduler.py b/invokeai/backend/rectified_flow/er_sde_scheduler.pynew file mode 100644index 0000000000..7a30aa8cb6--- /dev/null+++ b/invokeai/backend/rectified_flow/er_sde_scheduler.py@@ -0,0 +1,601 @@+"""ER-SDE (Extended Reverse-time SDE) ``diffusers`` scheduler.++Implements the multistep Taylor-expansion solver from:++ Cui, Q., Zhang, X., Lu, Z., & Liao, Q. (2023).+ Elucidating the solution space of extended reverse-time SDE+ for diffusion models. arXiv:2309.06169.+ https://arxiv.org/abs/2309.06169++Reference implementation (MIT-licensed):+ https://github.com/QinpengCui/ER-SDE-Solver/blob/main/er_sde_solver.py++This scheduler unifies two regimes under a single API:++* **VP-SDE** (``use_flow_sigmas=False``) — Stable Diffusion / SDXL style models+ with epsilon, x0, or v prediction. Uses the standard+ ``alpha_t = 1 / sqrt(1 + sigma^2), sigma_t = sigma * alpha_t`` parameterization+ and ports ``vp_*_order_*`` from the reference impl.+* **Rectified flow / flow matching** (``use_flow_sigmas=True``) — FLUX, Z-Image,+ Anima style models with flow_prediction. Uses ``alpha_t = 1 - sigma, sigma_t = sigma``+ and the rectified-flow integral helpers defined locally (``_fn``,+ ``_integral_one_over_fn``, ``_integral_lam_minus_curr_over_fn``).++The rectified-flow integral helpers are kept local so this class is self-contained.+"""++from __future__ import annotations++import math+from typing import List, Optional, Tuple, Union++import numpy as np+import torch+from diffusers.configuration_utils import ConfigMixin, register_to_config+from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput+from diffusers.utils.torch_utils import randn_tensor++# Number of sample points for the left Riemann sums approximating the+# Taylor-extension integrals. Matches the reference impl's nums_intergrate=100.+_INTEGRAL_NUM_POINTS = 100+++def _fn(x: float) -> float:+ """ER-SDE noise-scale function ``SDE_5`` (paper appendix A.8).++ Mirrors ``customized_func(..., func_type=7)`` in the reference impl —+ the variant the paper recommends and tests for fast (~20 NFE) sampling.+ """+ return x * (math.exp(x**0.3) + 10.0)+++def _integral_one_over_fn(lambda_next: float, lambda_curr: float) -> float:+ """Left Riemann sum of int_{lambda_next}^{lambda_curr} 1/_fn(lam) dlam.++ Precondition: ``lambda_next > 0``. The integrand has a logarithmic singularity+ at ``lam = 0`` (``_fn(0) = 0``); callers must skip this when ``sigma_next == 0``.+ """+ delta = lambda_curr - lambda_next+ if delta <= 0:+ return 0.0+ step = delta / _INTEGRAL_NUM_POINTS+ total = 0.0+ for k in range(_INTEGRAL_NUM_POINTS):+ lam = lambda_next + k * step+ total += step / _fn(lam)+ return total+++def _integral_lam_minus_curr_over_fn(lambda_next: float, lambda_curr: float) -> float:+ """Left Riemann sum of int_{lambda_next}^{lambda_curr} (lam - lambda_curr)/_fn(lam) dlam.++ Precondition: ``lambda_next > 0``. Same singularity at ``lam = 0`` as+ :func:`_integral_one_over_fn`.+ """+ delta = lambda_curr - lambda_next+ if delta <= 0:+ return 0.0+ step = delta / _INTEGRAL_NUM_POINTS+ total = 0.0+ for k in range(_INTEGRAL_NUM_POINTS):+ lam = lambda_next + k * step+ total += step * (lam - lambda_curr) / _fn(lam)+ return total+++class ERSDEScheduler(SchedulerMixin, ConfigMixin):+ """``diffusers`` scheduler for the ER-SDE multistep solver.++ See module docstring for paper / reference-impl citations.++ Args:+ num_train_timesteps: Number of diffusion steps used during training.+ beta_start: VP-SDE beta schedule start (ignored when ``use_flow_sigmas=True``).+ beta_end: VP-SDE beta schedule end (ignored when ``use_flow_sigmas=True``).+ beta_schedule: ``"linear"``, ``"scaled_linear"``, or ``"squaredcos_cap_v2"``.+ trained_betas: Override betas with a pre-computed schedule.+ prediction_type: ``"epsilon"``, ``"v_prediction"``, or ``"flow_prediction"``.+ solver_order: Multistep order (1, 2, or 3). The solver auto-warms from order 1.+ use_flow_sigmas: If True, use the rectified-flow parameterization+ (``alpha_t = 1 - sigma``); else VP-SDE.+ flow_shift: Sigma shift applied to the default flow schedule.+ stochastic: If True, inject noise (full ER-SDE). If False, deterministic+ ODE companion — same Taylor expansion with the noise term zeroed.+ sigma_one_tolerance: Boundary tolerance for the ``sigma = 1`` limit+ (rectified-flow only). Numerically paranoid; keep small.+ timestep_spacing: ``"linspace"``, ``"leading"``, or ``"trailing"``.+ steps_offset: Offset added to ``"leading"`` timesteps.+ """++ _compatibles = [e.name for e in KarrasDiffusionSchedulers]+ order = 1++ @register_to_config+ def __init__(+ self,+ num_train_timesteps: int = 1000,+ beta_start: float = 0.00085,+ beta_end: float = 0.012,+ beta_schedule: str = "scaled_linear",+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,+ prediction_type: str = "epsilon",+ solver_order: int = 3,+ use_flow_sigmas: bool = False,+ flow_shift: float = 1.0,+ stochastic: bool = True,+ sigma_one_tolerance: float = 1e-6,+ timestep_spacing: str = "linspace",+ steps_offset: int = 0,+ ):+ if prediction_type not in ("epsilon", "v_prediction", "flow_prediction"):+ raise ValueError(+ f"prediction_type must be one of 'epsilon', 'v_prediction', 'flow_prediction', got {prediction_type!r}"+ )+ if solver_order not in (1, 2, 3):+ raise ValueError(f"solver_order must be 1, 2, or 3, got {solver_order}")+ if prediction_type == "flow_prediction" and not use_flow_sigmas:+ # Not strictly invalid, but almost certainly a misconfiguration.+ raise ValueError("prediction_type='flow_prediction' requires use_flow_sigmas=True (rectified-flow regime).")++ # VP-SDE noise schedule (only used when use_flow_sigmas=False).+ if trained_betas is not None:+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)+ elif beta_schedule == "linear":+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)+ elif beta_schedule == "scaled_linear":+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2+ elif beta_schedule == "squaredcos_cap_v2":+ # Glide cosine schedule.+ betas = []+ for i in range(num_train_timesteps):+ t1 = i / num_train_timesteps+ t2 = (i + 1) / num_train_timesteps+ a1 = math.cos((t1 + 0.008) / 1.008 * math.pi / 2) ** 2+ a2 = math.cos((t2 + 0.008) / 1.008 * math.pi / 2) ** 2+ betas.append(min(1 - a2 / a1, 0.999))+ self.betas = torch.tensor(betas, dtype=torch.float32)+ else:+ raise NotImplementedError(f"beta_schedule {beta_schedule!r} is not implemented for ERSDEScheduler")++ self.alphas = 1.0 - self.betas+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)++ # Default sigmas (VP-SDE form). Overwritten in set_timesteps.+ self.sigmas = ((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5++ # Standard deviation of initial noise distribution (per Euler convention).+ self.init_noise_sigma = 1.0++ self.num_inference_steps: Optional[int] = None+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()+ self.timesteps = torch.from_numpy(timesteps)++ # Multistep history. ``model_outputs`` stores x0 predictions; ``_sigma_history``+ # stores the sigma at which each prediction was made. Both are FIFO with+ # length == solver_order. Slot ``-1`` is the most recent.+ self.model_outputs: List[Optional[torch.Tensor]] = [None] * solver_order+ self._sigma_history: List[Optional[float]] = [None] * solver_order+ self.lower_order_nums = 0+ self._step_index: Optional[int] = None+ self._begin_index: Optional[int] = None+ self.sigmas = self.sigmas.to("cpu")++ # ---- Index plumbing (mirrors DPM++) ---------------------------------------++ @property+ def step_index(self) -> Optional[int]:+ return self._step_index++ @property+ def begin_index(self) -> Optional[int]:+ return self._begin_index++ def set_begin_index(self, begin_index: int = 0) -> None:+ self._begin_index = begin_index++ def index_for_timestep(+ self,+ timestep: Union[int, torch.Tensor],+ schedule_timesteps: Optional[torch.Tensor] = None,+ ) -> int:+ if schedule_timesteps is None:+ schedule_timesteps = self.timesteps+ index_candidates = (schedule_timesteps == timestep).nonzero()+ if len(index_candidates) == 0:+ return len(self.timesteps) - 1+ # On the very first step, prefer the second match if duplicated, so+ # img2img doesn't accidentally skip a sigma.+ if len(index_candidates) > 1:+ return index_candidates[1].item()+ return index_candidates[0].item()++ def _init_step_index(self, timestep: Union[int, torch.Tensor]) -> None:+ if self.begin_index is None:+ if isinstance(timestep, torch.Tensor):+ timestep = timestep.to(self.timesteps.device)+ self._step_index = self.index_for_timestep(timestep)+ else:+ self._step_index = self._begin_index++ # ---- Timestep / sigma scheduling ------------------------------------------++ def set_timesteps(+ self,+ num_inference_steps: Optional[int] = None,+ device: Optional[Union[str, torch.device]] = None,+ sigmas: Optional[Union[List[float], np.ndarray, torch.Tensor]] = None,+ timesteps: Optional[List[int]] = None,+ ) -> None:+ """Set the discrete timesteps used for inference.++ Exactly one of ``num_inference_steps``, ``timesteps``, or ``sigmas`` must+ be provided. The ``sigmas`` form (mirroring :class:`EulerDiscreteScheduler`)+ lets Anima/FLUX/Z-Image inject pre-shifted sigma schedules directly.+ """+ n_set = sum(x is not None for x in (num_inference_steps, timesteps, sigmas))+ if n_set != 1:+ raise ValueError("Must pass exactly one of `num_inference_steps`, `timesteps`, or `sigmas`.")++ if sigmas is not None:+ if isinstance(sigmas, torch.Tensor):+ sigmas_np = sigmas.detach().cpu().numpy().astype(np.float32)+ else:+ sigmas_np = np.array(sigmas, dtype=np.float32)+ num_inference_steps = len(sigmas_np) - 1+ # Timesteps in the rectified-flow / Anima convention scale sigma to t.+ # For VP-SDE this approximation is wrong but timesteps are only used+ # for indexing; the algebra runs entirely off self.sigmas.+ timesteps_np = (sigmas_np[:-1] * self.config.num_train_timesteps).astype(np.float32)+ elif timesteps is not None:+ timesteps_np = np.array(timesteps, dtype=np.float32)+ num_inference_steps = len(timesteps_np)+ sigmas_np = self._sigmas_for_timesteps(timesteps_np)+ else:+ assert num_inference_steps is not None+ timesteps_np = self._default_timesteps(num_inference_steps)+ sigmas_np = self._sigmas_for_timesteps(timesteps_np)++ self.num_inference_steps = num_inference_steps+ self.sigmas = torch.from_numpy(sigmas_np.astype(np.float32))+ self.timesteps = torch.from_numpy(timesteps_np.astype(np.float32)).to(device=device)++ # Reset multistep state.+ self.model_outputs = [None] * self.config.solver_order+ self._sigma_history = [None] * self.config.solver_order+ self.lower_order_nums = 0+ self._step_index = None+ self._begin_index = None+ self.sigmas = self.sigmas.to("cpu")++ def _default_timesteps(self, num_inference_steps: int) -> np.ndarray:+ """Standard linspace/leading/trailing schedule (VP-SDE timesteps)."""+ if self.config.timestep_spacing == "linspace":+ timesteps = (+ np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps + 1)+ .round()[::-1][:-1]+ .copy()+ .astype(np.float32)+ )+ elif self.config.timestep_spacing == "leading":+ step_ratio = self.config.num_train_timesteps // (num_inference_steps + 1)+ timesteps = (+ (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.float32)+ )+ timesteps += self.config.steps_offset+ elif self.config.timestep_spacing == "trailing":+ step_ratio = self.config.num_train_timesteps / num_inference_steps+ timesteps = np.arange(self.config.num_train_timesteps, 0, -step_ratio).round().copy().astype(np.float32)+ timesteps -= 1+ else:+ raise ValueError(+ f"timestep_spacing {self.config.timestep_spacing!r} must be one of 'linspace', 'leading', 'trailing'"+ )+ return timesteps++ def _sigmas_for_timesteps(self, timesteps_np: np.ndarray) -> np.ndarray:+ """Build the sigma schedule (with terminal 0 appended) for given timesteps."""+ if self.config.use_flow_sigmas:+ # Rectified-flow sigmas in [0, 1], time-shifted per Anima/FLUX convention.+ num_inference_steps = len(timesteps_np)+ alphas = np.linspace(1, 1 / self.config.num_train_timesteps, num_inference_steps + 1)+ sigmas = 1.0 - alphas+ shift = self.config.flow_shift+ sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy()+ # Terminal sigma is exactly 0.+ return np.concatenate([sigmas, [0.0]]).astype(np.float32)++ # VP-SDE: interpolate against the train sigmas using timestep indexing.+ train_sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)+ sigmas = np.interp(timesteps_np, np.arange(0, len(train_sigmas)), train_sigmas)+ return np.concatenate([sigmas, [0.0]]).astype(np.float32)++ # ---- Math helpers ---------------------------------------------------------++ def _sigma_to_alpha_sigma_t(self, sigma: float) -> Tuple[float, float]:+ """Map ``sigma`` to ``(alpha_t, sigma_t)``.++ Rectified flow: ``alpha_t = 1 - sigma, sigma_t = sigma``.+ VP-SDE: ``alpha_t = 1 / sqrt(1 + sigma^2), sigma_t = sigma * alpha_t``.+ """+ if self.config.use_flow_sigmas:+ return 1.0 - sigma, sigma+ alpha_t = 1.0 / math.sqrt(1.0 + sigma * sigma)+ return alpha_t, sigma * alpha_t++ @staticmethod+ def _lambda(alpha_t: float, sigma_t: float) -> float:+ """ER-SDE ``lambda = sigma_t / alpha_t`` — the noise-to-signal ratio.++ This matches the reference impl's ``lambdas = sigmas / alphas`` in both+ VP and rectified-flow regimes (see ``vp_*_order_*`` in+ ``https://github.com/QinpengCui/ER-SDE-Solver``). For VP-SDE this equals+ the stored sigma; for rectified flow it equals ``sigma / (1 - sigma)``.+ Diverges at ``sigma_t = alpha_t = 0`` (rectified flow at sigma=1) — the+ boundary branch in :meth:`_first_order_update` handles that case.+ """+ if alpha_t == 0.0:+ return float("inf")+ return sigma_t / alpha_t++ # ---- Model output conversion ----------------------------------------------++ def _convert_model_output(self, model_output: torch.Tensor, sample: torch.Tensor) -> torch.Tensor:+ """Convert raw model output to an ``x0`` prediction at the current sigma."""+ sigma = float(self.sigmas[self.step_index].item())+ if self.config.prediction_type == "flow_prediction":+ # v = (x - x0) / sigma => x0 = x - sigma * v+ return sample - sigma * model_output+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)+ if self.config.prediction_type == "epsilon":+ return (sample - sigma_t * model_output) / alpha_t+ if self.config.prediction_type == "v_prediction":+ return alpha_t * sample - sigma_t * model_output+ raise ValueError(f"Unsupported prediction_type {self.config.prediction_type!r}")++ # ---- Order-N updates -------------------------------------------------------++ def _first_order_update(+ self,+ x0: torch.Tensor,+ sample: torch.Tensor,+ sigma_curr: float,+ sigma_next: float,+ noise: Optional[torch.Tensor],+ ) -> torch.Tensor:+ """Order-1 ER-SDE step (ports ``vp_1_order`` / ``er_sde_rf_step`` order-1 branch)."""+ # Rectified-flow boundary: sigma_curr ~= 1 means alpha_curr ~= 0 so lambda diverges.+ # Closed-form limit (er_sde.py:136-142): x_next = (1 - sigma_next) * x0 + sigma_next * noise.+ if self.config.use_flow_sigmas and 1.0 - sigma_curr < self.config.sigma_one_tolerance:+ x_next = (1.0 - sigma_next) * x0+ if self.config.stochastic and noise is not None and sigma_next > 0.0:+ x_next = x_next + sigma_next * noise+ return x_next++ alpha_curr, sigma_curr_t = self._sigma_to_alpha_sigma_t(sigma_curr)+ alpha_next, sigma_next_t = self._sigma_to_alpha_sigma_t(sigma_next)++ # Reference impl uses lambda = sigma_t / alpha_t in both VP and flow regimes.+ lambda_curr = self._lambda(alpha_curr, sigma_curr_t)+ # At the terminal step, sigma_next == 0 so lambda_next == 0 and fn_next == 0.+ lambda_next = self._lambda(alpha_next, sigma_next_t) if sigma_next_t > 0.0 else 0.0++ fn_curr = _fn(lambda_curr)+ fn_next = _fn(lambda_next)+ r_fn = fn_next / fn_curr if fn_curr != 0.0 else 0.0+ r_alphas = alpha_next / alpha_curr++ # Stochastic noise std (paper appendix eq. for ER-SDE_5 variance).+ # ``inner`` can underflow to tiny negatives by roundoff; clip.+ inner = lambda_next**2 - lambda_curr**2 * r_fn**2+ if inner < 0.0:+ inner = 0.0+ noise_std = math.sqrt(inner) * alpha_next++ x_next = r_alphas * r_fn * sample + alpha_next * (1.0 - r_fn) * x0+ if self.config.stochastic and noise is not None and sigma_next > 0.0:+ x_next = x_next + noise_std * noise+ return x_next++ def _second_order_update(+ self,+ sample: torch.Tensor,+ sigma_curr: float,+ sigma_next: float,+ noise: Optional[torch.Tensor],+ ) -> torch.Tensor:+ """Order-2 ER-SDE step (ports ``vp_2_order_taylor``)."""+ x0 = self.model_outputs[-1]+ old_x0 = self.model_outputs[-2]+ sigma_prev_curr = self._sigma_history[-2]+ assert x0 is not None and old_x0 is not None and sigma_prev_curr is not None++ # If the previous step used the sigma=1 closed-form limit, the finite-difference+ # derivative across that boundary is meaningless — fall back to order 1.+ if self.config.use_flow_sigmas and 1.0 - sigma_prev_curr < self.config.sigma_one_tolerance:+ return self._first_order_update(x0, sample, sigma_curr, sigma_next, noise)++ # Order-1 base.+ x_next = self._first_order_update(x0, sample, sigma_curr, sigma_next, noise)++ # Skip the higher-order term at the terminal step — the integral helpers diverge+ # at lambda = 0 (sigma = 0), see _integral_one_over_fn docstring.+ if sigma_next <= 0.0:+ return x_next++ alpha_curr, sigma_curr_t = self._sigma_to_alpha_sigma_t(sigma_curr)+ alpha_next, sigma_next_t = self._sigma_to_alpha_sigma_t(sigma_next)+ alpha_prev, sigma_prev_t = self._sigma_to_alpha_sigma_t(sigma_prev_curr)+ lambda_curr = self._lambda(alpha_curr, sigma_curr_t)+ lambda_next = self._lambda(alpha_next, sigma_next_t)+ lambda_prev = self._lambda(alpha_prev, sigma_prev_t)++ denom = lambda_curr - lambda_prev+ if denom == 0.0:+ return x_next+ d_x0 = (x0 - old_x0) / denom++ fn_next = _fn(lambda_next)+ s_int = _integral_one_over_fn(lambda_next, lambda_curr)+ x_next = x_next + alpha_next * (lambda_next - lambda_curr + s_int * fn_next) * d_x0+ return x_next++ def _third_order_update(+ self,+ sample: torch.Tensor,+ sigma_curr: float,+ sigma_next: float,+ noise: Optional[torch.Tensor],+ ) -> torch.Tensor:+ """Order-3 ER-SDE step (ports ``vp_3_order_taylor``)."""+ x0 = self.model_outputs[-1]+ old_x0 = self.model_outputs[-2]+ old_old_x0 = self.model_outputs[-3]+ sigma_prev_curr = self._sigma_history[-2]+ sigma_prev_prev = self._sigma_history[-3]+ assert (+ x0 is not None+ and old_x0 is not None+ and old_old_x0 is not None+ and sigma_prev_curr is not None+ and sigma_prev_prev is not None+ )++ # If any sigma in the lookback hits the boundary, fall back to order 2.+ if self.config.use_flow_sigmas and (+ 1.0 - sigma_prev_curr < self.config.sigma_one_tolerance+ or 1.0 - sigma_prev_prev < self.config.sigma_one_tolerance+ ):+ return self._second_order_update(sample, sigma_curr, sigma_next, noise)++ # Order-2 base.+ x_next = self._second_order_update(sample, sigma_curr, sigma_next, noise)++ if sigma_next <= 0.0:+ return x_next++ alpha_curr, sigma_curr_t = self._sigma_to_alpha_sigma_t(sigma_curr)+ alpha_next, sigma_next_t = self._sigma_to_alpha_sigma_t(sigma_next)+ alpha_prev, sigma_prev_t = self._sigma_to_alpha_sigma_t(sigma_prev_curr)+ alpha_pprev, sigma_pprev_t = self._sigma_to_alpha_sigma_t(sigma_prev_prev)+ lambda_curr = self._lambda(alpha_curr, sigma_curr_t)+ lambda_next = self._lambda(alpha_next, sigma_next_t)+ lambda_prev = self._lambda(alpha_prev, sigma_prev_t)+ lambda_pprev = self._lambda(alpha_pprev, sigma_pprev_t)++ denom_d = lambda_curr - lambda_prev+ denom_d_prev = lambda_prev - lambda_pprev+ denom_dd = lambda_curr - lambda_pprev+ if denom_d == 0.0 or denom_d_prev == 0.0 or denom_dd == 0.0:+ return x_next++ d_x0 = (x0 - old_x0) / denom_d+ old_d_x0 = (old_x0 - old_old_x0) / denom_d_prev+ dd_x0 = 2.0 * (d_x0 - old_d_x0) / denom_dd++ fn_next = _fn(lambda_next)+ s_d_int = _integral_lam_minus_curr_over_fn(lambda_next, lambda_curr)+ x_next = x_next + alpha_next * ((lambda_next - lambda_curr) ** 2 / 2.0 + s_d_int * fn_next) * dd_x0+ return x_next++ # ---- Public step ----------------------------------------------------------++ def scale_model_input(+ self, sample: torch.Tensor, timestep: Optional[Union[int, torch.Tensor]] = None+ ) -> torch.Tensor:+ """No-op (matches ``FlowMatchEulerDiscreteScheduler``)."""+ return sample++ def step(+ self,+ model_output: torch.Tensor,+ timestep: Union[int, torch.Tensor],+ sample: torch.Tensor,+ generator: Optional[torch.Generator] = None,+ return_dict: bool = True,+ ) -> Union[SchedulerOutput, Tuple]:+ """Predict the sample at the next timestep using one ER-SDE step."""+ if self.num_inference_steps is None:+ raise ValueError("num_inference_steps is None — call `set_timesteps` before calling `step`.")+ if self.step_index is None:+ self._init_step_index(timestep)++ sigma_curr = float(self.sigmas[self.step_index].item())+ sigma_next = float(self.sigmas[self.step_index + 1].item())++ # 1. Convert model output to x0 prediction.+ x0 = self._convert_model_output(model_output, sample)++ # 2. FIFO-shift the multistep history. New entry goes in slot -1.+ for i in range(self.config.solver_order - 1):+ self.model_outputs[i] = self.model_outputs[i + 1]+ self._sigma_history[i] = self._sigma_history[i + 1]+ self.model_outputs[-1] = x0+ self._sigma_history[-1] = sigma_curr++ # 3. Sample noise (only when stochastic and not at terminal step).+ if self.config.stochastic and sigma_next > 0.0:+ noise = randn_tensor(+ model_output.shape,+ generator=generator,+ device=model_output.device,+ dtype=model_output.dtype,+ )+ else:+ noise = None++ # 4. Dispatch by available history.+ if self.config.solver_order == 1 or self.lower_order_nums < 1:+ prev_sample = self._first_order_update(x0, sample, sigma_curr, sigma_next, noise)+ elif self.config.solver_order == 2 or self.lower_order_nums < 2:+ prev_sample = self._second_order_update(sample, sigma_curr, sigma_next, noise)+ else:+ prev_sample = self._third_order_update(sample, sigma_curr, sigma_next, noise)++ if self.lower_order_nums < self.config.solver_order:+ self.lower_order_nums += 1++ # 5. Advance step index.+ self._step_index += 1++ if not return_dict:+ return (prev_sample,)+ return SchedulerOutput(prev_sample=prev_sample)++ # ---- Forward noising (training / img2img) ---------------------------------++ def add_noise(+ self,+ original_samples: torch.Tensor,+ noise: torch.Tensor,+ timesteps: torch.Tensor,+ ) -> torch.Tensor:+ """Forward-noise ``original_samples`` at the given timesteps (img2img style)."""+ sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)+ if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):+ schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)+ timesteps = timesteps.to(original_samples.device, dtype=torch.float32)+ else:+ schedule_timesteps = self.timesteps.to(original_samples.device)+ timesteps = timesteps.to(original_samples.device)++ if self.begin_index is None:+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timesteps]+ elif self.step_index is not None:+ step_indices = [self.step_index] * timesteps.shape[0]+ else:+ step_indices = [self.begin_index] * timesteps.shape[0]++ sigma = sigmas[step_indices].flatten()+ while len(sigma.shape) < len(original_samples.shape):+ sigma = sigma.unsqueeze(-1)++ if self.config.use_flow_sigmas:+ alpha_t = 1.0 - sigma+ sigma_t = sigma+ else:+ alpha_t = 1.0 / torch.sqrt(1.0 + sigma * sigma)+ sigma_t = sigma * alpha_t+ return alpha_t * original_samples + sigma_t * noise++ def __len__(self) -> int:+ return self.config.num_train_timestepsdiff --git a/invokeai/backend/stable_diffusion/schedulers/schedulers.py b/invokeai/backend/stable_diffusion/schedulers/schedulers.pyindex c8836b316a..c883767e82 100644--- a/invokeai/backend/stable_diffusion/schedulers/schedulers.py+++ b/invokeai/backend/stable_diffusion/schedulers/schedulers.py@@ -20,6 +20,8 @@ from diffusers import ()from diffusers.schedulers.scheduling_utils import SchedulerMixin+from invokeai.backend.rectified_flow.er_sde_scheduler import ERSDEScheduler+# TODO: add dpmpp_3s/dpmpp_3s_k when fix released# https://github.com/huggingface/diffusers/issues/9007@@ -50,6 +52,7 @@ SCHEDULER_NAME_VALUES = Literal["dpmpp_3m_k","dpmpp_sde","dpmpp_sde_k",+ "er_sde","unipc","unipc_k","lcm",@@ -89,6 +92,10 @@ SCHEDULER_MAP: dict[SCHEDULER_NAME_VALUES, tuple[Type[SchedulerMixin], dict[str,"dpmpp_3m_k": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True, "solver_order": 3}),"dpmpp_sde": (DPMSolverSDEScheduler, {"use_karras_sigmas": False, "noise_sampler_seed": 0}),"dpmpp_sde_k": (DPMSolverSDEScheduler, {"use_karras_sigmas": True, "noise_sampler_seed": 0}),+ "er_sde": (+ ERSDEScheduler,+ {"solver_order": 3, "use_flow_sigmas": False, "stochastic": True},+ ),"unipc": (UniPCMultistepScheduler, {"use_karras_sigmas": False, "cpu_only": True}),"unipc_k": (UniPCMultistepScheduler, {"use_karras_sigmas": True, "cpu_only": True}),"lcm": (LCMScheduler, {}),diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 0b2aa90e27..76e96cfd87 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -9461,7 +9461,7 @@"scheduler": {"default": "euler","description": "Scheduler (sampler) for the denoising process.",- "enum": ["euler", "heun", "lcm"],+ "enum": ["euler", "heun", "dpmpp_2m", "dpmpp_2m_sde", "er_sde", "lcm"],"field_kind": "input","input": "any","orig_default": "euler",@@ -9471,6 +9471,9 @@"ui_choice_labels": {"euler": "Euler","heun": "Heun (2nd order)",+ "dpmpp_2m": "DPM++ 2M",+ "dpmpp_2m_sde": "DPM++ 2M SDE",+ "er_sde": "ER-SDE","lcm": "LCM"}},@@ -9486,7 +9489,7 @@"tags": ["image", "anima"],"title": "Denoise - Anima","type": "object",- "version": "1.2.0",+ "version": "1.4.0","output": {"$ref": "#/components/schemas/LatentsOutput"}diff --git a/invokeai/frontend/web/src/features/controlLayers/store/paramsSlice.ts b/invokeai/frontend/web/src/features/controlLayers/store/paramsSlice.tsindex 8c3308b0c0..a5200ef1ff 100644--- a/invokeai/frontend/web/src/features/controlLayers/store/paramsSlice.ts+++ b/invokeai/frontend/web/src/features/controlLayers/store/paramsSlice.ts@@ -238,7 +238,10 @@ const slice = createSlice({}state.animaT5EncoderModel = result.data;},- setAnimaScheduler: (state, action: PayloadAction<'euler' | 'heun' | 'lcm'>) => {+ setAnimaScheduler: (+ state,+ action: PayloadAction<'euler' | 'heun' | 'dpmpp_2m' | 'dpmpp_2m_sde' | 'er_sde' | 'lcm'>+ ) => {state.animaScheduler = action.payload;},kleinVaeModelSelected: (state, action: PayloadAction<ParameterVAEModel | null>) => {diff --git a/invokeai/frontend/web/src/features/controlLayers/store/types.ts b/invokeai/frontend/web/src/features/controlLayers/store/types.tsindex 212cc978ee..7a7ebeade7 100644--- a/invokeai/frontend/web/src/features/controlLayers/store/types.ts+++ b/invokeai/frontend/web/src/features/controlLayers/store/types.ts@@ -2,6 +2,7 @@ import { deepClone } from 'common/util/deepClone';import type { CanvasEntityAdapter } from 'features/controlLayers/konva/CanvasEntity/types';import { zMainModelBase, zModelIdentifierField } from 'features/nodes/types/common';import {+ zParameterAnimaScheduler,zParameterCanvasCoherenceMode,zParameterCFGRescaleMultiplier,zParameterCFGScale,@@ -809,7 +810,7 @@ export const zParamsState = z.object({animaVaeModel: zParameterVAEModel.nullable(), // Optional: Separate QwenImage/FLUX VAE for AnimaanimaQwen3EncoderModel: zModelIdentifierField.nullable(), // Optional: Separate Qwen3 0.6B Encoder for AnimaanimaT5EncoderModel: zModelIdentifierField.nullable(), // T5-XXL tokenizer for Anima LLM Adapter- animaScheduler: z.enum(['euler', 'heun', 'lcm']).default('euler'),+ animaScheduler: zParameterAnimaScheduler,// Flux2 Klein model components - uses Qwen3 instead of CLIP+T5kleinVaeModel: zParameterVAEModel.nullable(), // Optional: Separate FLUX.2 VAE for KleinkleinQwen3EncoderModel: zModelIdentifierField.nullable(), // Optional: Separate Qwen3 Encoder for Kleindiff --git a/invokeai/frontend/web/src/features/metadata/parsing.tsx b/invokeai/frontend/web/src/features/metadata/parsing.tsxindex 6c9cb7b21a..c5a31d03a3 100644--- a/invokeai/frontend/web/src/features/metadata/parsing.tsx+++ b/invokeai/frontend/web/src/features/metadata/parsing.tsx@@ -499,8 +499,15 @@ const Scheduler: SingleMetadataHandler<ParameterScheduler> = {store.dispatch(setZImageScheduler(value));}} else if (base === 'anima') {- // Anima supports euler, heun, lcm- if (value === 'euler' || value === 'heun' || value === 'lcm') {+ // Anima supports euler, heun, dpmpp_2m, dpmpp_2m_sde, er_sde, lcm+ if (+ value === 'euler' ||+ value === 'heun' ||+ value === 'dpmpp_2m' ||+ value === 'dpmpp_2m_sde' ||+ value === 'er_sde' ||+ value === 'lcm'+ ) {store.dispatch(setAnimaScheduler(value));}} else {diff --git a/invokeai/frontend/web/src/features/nodes/types/common.ts b/invokeai/frontend/web/src/features/nodes/types/common.tsindex 30d2a561da..fb2a1ce946 100644--- a/invokeai/frontend/web/src/features/nodes/types/common.ts+++ b/invokeai/frontend/web/src/features/nodes/types/common.ts@@ -41,6 +41,7 @@ export const zSchedulerField = z.enum(['dpmpp_3m','dpmpp_2m_sde','dpmpp_sde',+ 'er_sde','heun','kdpm_2','lms',@@ -72,7 +73,7 @@ export const zFluxSchedulerField = z.enum(['euler', 'heun', 'lcm']);// Note: LCM is only supported for Z-Image Turbo, not for Z-Image Base (undistilled)export const zZImageSchedulerField = z.enum(['euler', 'heun', 'lcm']);// Anima scheduler options (same flow-matching schedulers, defined separately to avoid coupling)-export const zAnimaSchedulerField = z.enum(['euler', 'heun', 'lcm']);+export const zAnimaSchedulerField = z.enum(['euler', 'heun', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde', 'lcm']);// Flux DyPE (Dynamic Position Extrapolation) preset options for high-resolution generationexport const zFluxDypePresetField = z.enum(['off', 'manual', 'auto', 'area', '4k']);diff --git a/invokeai/frontend/web/src/features/parameters/components/Core/ParamAnimaScheduler.tsx b/invokeai/frontend/web/src/features/parameters/components/Core/ParamAnimaScheduler.tsxindex f065361136..c52a0dd2d6 100644--- a/invokeai/frontend/web/src/features/parameters/components/Core/ParamAnimaScheduler.tsx+++ b/invokeai/frontend/web/src/features/parameters/components/Core/ParamAnimaScheduler.tsx@@ -7,10 +7,13 @@ import { isParameterAnimaScheduler } from 'features/parameters/types/parameterScimport { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-// Anima scheduler options (same flow-matching schedulers as Z-Image)+// Anima scheduler options. Mirrors ANIMA_SCHEDULER_LABELS in invokeai/backend/flux/schedulers.py.const ANIMA_SCHEDULER_OPTIONS: ComboboxOption[] = [{ value: 'euler', label: 'Euler' },{ value: 'heun', label: 'Heun (2nd order)' },+ { value: 'dpmpp_2m', label: 'DPM++ 2M' },+ { value: 'dpmpp_2m_sde', label: 'DPM++ 2M SDE' },+ { value: 'er_sde', label: 'ER-SDE' },{ value: 'lcm', label: 'LCM' },];diff --git a/invokeai/frontend/web/src/features/parameters/types/constants.ts b/invokeai/frontend/web/src/features/parameters/types/constants.tsindex 0d55785174..a3ffa24cc6 100644--- a/invokeai/frontend/web/src/features/parameters/types/constants.ts+++ b/invokeai/frontend/web/src/features/parameters/types/constants.ts@@ -69,6 +69,7 @@ export const SCHEDULER_OPTIONS: ComboboxOption[] = [{ value: 'dpmpp_3m_k', label: 'DPM++ 3M Karras' },{ value: 'dpmpp_sde', label: 'DPM++ SDE' },{ value: 'dpmpp_sde_k', label: 'DPM++ SDE Karras' },+ { value: 'er_sde', label: 'ER-SDE' },{ value: 'euler', label: 'Euler' },{ value: 'euler_k', label: 'Euler Karras' },{ value: 'euler_a', label: 'Euler Ancestral' },diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex f921b94fcc..62070fcbbb 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -3182,7 +3182,7 @@ export type components = {* @default euler* @enum {string}*/- scheduler?: "euler" | "heun" | "lcm";+ scheduler?: "euler" | "heun" | "dpmpp_2m" | "dpmpp_2m_sde" | "er_sde" | "lcm";/*** type* @default anima_denoise@@ -8298,7 +8298,7 @@ export type components = {* @default euler* @enum {string}*/- scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** UNet* @description UNet (scheduler, LoRAs)@@ -8416,7 +8416,7 @@ export type components = {* @default euler* @enum {string}*/- scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** UNet* @description UNet (scheduler, LoRAs)@@ -19454,7 +19454,7 @@ export type components = {* Scheduler* @description Default scheduler for this model*/- scheduler?: ("ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd") | null;+ scheduler?: ("ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd") | null;/*** Steps* @description Default number of steps for this model@@ -23007,7 +23007,7 @@ export type components = {* @default euler* @enum {string}*/- default_value?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ default_value?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** type* @default metadata_to_scheduler@@ -27302,7 +27302,7 @@ export type components = {* @default euler* @enum {string}*/- scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** type* @default scheduler@@ -27317,7 +27317,7 @@ export type components = {* @description Scheduler to use during inference* @enum {string}*/- scheduler: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ scheduler: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** type* @default scheduler_output@@ -30252,7 +30252,7 @@ export type components = {* @default euler* @enum {string}*/- scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "unipc" | "unipc_k" | "lcm" | "tcd";+ scheduler?: "ddim" | "ddpm" | "deis" | "deis_k" | "lms" | "lms_k" | "pndm" | "heun" | "heun_k" | "euler" | "euler_k" | "euler_a" | "kdpm_2" | "kdpm_2_k" | "kdpm_2_a" | "kdpm_2_a_k" | "dpmpp_2s" | "dpmpp_2s_k" | "dpmpp_2m" | "dpmpp_2m_k" | "dpmpp_2m_sde" | "dpmpp_2m_sde_k" | "dpmpp_3m" | "dpmpp_3m_k" | "dpmpp_sde" | "dpmpp_sde_k" | "er_sde" | "unipc" | "unipc_k" | "lcm" | "tcd";/*** UNet* @description UNet (scheduler, LoRAs)diff --git a/tests/app/invocations/test_anima_denoise_er_sde_dispatch.py b/tests/app/invocations/test_anima_denoise_er_sde_dispatch.pynew file mode 100644index 0000000000..b7682bbc8f--- /dev/null+++ b/tests/app/invocations/test_anima_denoise_er_sde_dispatch.py@@ -0,0 +1,55 @@+"""Dispatch wiring and sigma-contract tests for Anima ER-SDE.++Verifies that ANIMA_SCHEDULER_MAP['er_sde'] produces a correctly configured+ERSDEScheduler, that set_timesteps accepts sigmas= (the contract Anima relies+on to pass its pre-shifted schedule), and that the sigma state is set up as+expected after set_timesteps.+"""++from __future__ import annotations++from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP+from invokeai.backend.rectified_flow.er_sde_scheduler import ERSDEScheduler+++def test_anima_scheduler_map_er_sde_constructs_correctly():+ """The map entry must produce a valid ERSDEScheduler when instantiated."""+ cls, kwargs = ANIMA_SCHEDULER_MAP["er_sde"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ assert isinstance(scheduler, ERSDEScheduler)+ assert scheduler.config.prediction_type == "flow_prediction"+ assert scheduler.config.use_flow_sigmas is True+ assert scheduler.config.solver_order == 3+ assert scheduler.config.stochastic is True+++def test_anima_er_sde_set_timesteps_accepts_sigmas():+ """Anima passes pre-shifted sigmas via set_timesteps(sigmas=...).++ The legacy elif is_er_sde: branch consumed Anima's pre-shifted sigmas+ directly. The universal path requires ERSDEScheduler.set_timesteps to+ accept sigmas= as a keyword argument. This is the contract that makes+ the cutover safe.+ """+ import inspect++ cls, kwargs = ANIMA_SCHEDULER_MAP["er_sde"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ sig = inspect.signature(scheduler.set_timesteps)+ assert "sigmas" in sig.parameters, "ERSDEScheduler.set_timesteps must accept sigmas= for Anima compatibility"+++def test_anima_er_sde_set_timesteps_with_pre_shifted_sigmas():+ """End-to-end set_timesteps with a small pre-shifted sigma schedule."""+ import torch++ cls, kwargs = ANIMA_SCHEDULER_MAP["er_sde"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ # Synthetic 5-step pre-shifted schedule, sigma_max=0.95 down to terminal 0.+ sigmas = torch.tensor([0.95, 0.75, 0.5, 0.3, 0.1, 0.0], dtype=torch.float32)+ scheduler.set_timesteps(sigmas=sigmas, device="cpu")+ assert scheduler.num_inference_steps == 5+ assert torch.allclose(scheduler.sigmas, sigmas)+ # Multistep state must be reset.+ assert scheduler.lower_order_nums == 0+ assert all(x is None for x in scheduler.model_outputs)diff --git a/tests/backend/anima/test_scheduler_driver.py b/tests/backend/anima/test_scheduler_driver.pynew file mode 100644index 0000000000..ec8c8f54e4--- /dev/null+++ b/tests/backend/anima/test_scheduler_driver.py@@ -0,0 +1,195 @@+"""Tests for AnimaSchedulerDriver — the helper that hides per-scheduler API quirks+(sigmas= vs num_inference_steps=, Heun's doubled timestep array, set_begin_index)+behind a uniform iteration interface."""++import inspect++import pytest+import torch++from invokeai.app.invocations.anima_denoise import loglinear_timestep_shift+from invokeai.backend.anima.scheduler_driver import AnimaSchedulerDriver+from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP, ANIMA_SHIFT+++def _anima_sigmas(num_steps: int) -> list[float]:+ return [loglinear_timestep_shift(ANIMA_SHIFT, 1.0 - i / num_steps) for i in range(num_steps + 1)]++[email protected]("scheduler_name", ["heun", "dpmpp_2m", "dpmpp_2m_sde", "er_sde"])+def test_driver_full_schedule_iteration_count(scheduler_name: str) -> None:+ """For full schedules (no clipping), the driver yields enough iterations to+ cover one full denoise. Heun yields 2N-1 iterations for N user steps."""+ num_steps = 8+ sigmas = _anima_sigmas(num_steps)+ driver = AnimaSchedulerDriver(+ scheduler_name=scheduler_name,+ sigmas=sigmas,+ steps=num_steps,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=0,+ )+ iterations = list(driver.iterations())+ if driver.is_heun:+ assert len(iterations) == 2 * num_steps - 1+ else:+ assert len(iterations) == num_steps++[email protected]("scheduler_name", ["dpmpp_2m", "dpmpp_2m_sde", "er_sde"])+def test_driver_single_step_schedulers_complete_user_step_every_iteration(scheduler_name: str) -> None:+ """Non-Heun schedulers report completes_user_step on every iteration."""+ num_steps = 6+ driver = AnimaSchedulerDriver(+ scheduler_name=scheduler_name,+ sigmas=_anima_sigmas(num_steps),+ steps=num_steps,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=0,+ )+ user_step_count = sum(1 for it in driver.iterations() if it.completes_user_step)+ assert user_step_count == num_steps+++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)."""+ num_steps = 4+ driver = AnimaSchedulerDriver(+ scheduler_name="heun",+ sigmas=_anima_sigmas(num_steps),+ steps=num_steps,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=0,+ )+ # state_in_first_order only toggles once scheduler.step runs, so drive a fake+ # step per iteration to mirror production behaviour.+ completes_flags = []+ for it in driver.iterations():+ completes_flags.append(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)),+ )+ # N=4 → 7 iterations: indices 1, 3, 5 (SO halves) + 6 (terminal FO) = 4 completions.+ assert sum(completes_flags) == num_steps+ assert completes_flags[-1] is True, "terminal Heun first-order step must complete its user step"+++ ("denoising_start", "denoising_end"),+ [(0.0, 1.0), (0.2, 1.0), (0.0, 0.8), (0.2, 0.8), (0.5, 0.75)],+)+def test_driver_dpmpp_clipped_schedule_starts_at_correct_sigma(denoising_start: float, denoising_end: float) -> None:+ """DPM++ doesn't accept sigmas= on diffusers 0.35.1; the driver's set_begin_index+ fallback must expose a first iteration whose sigma matches the clipped Anima reference.++ DPM++ constructs its internal flow schedule via ``np.linspace(1, T, N+1)[:-1]`` rather+ than the closed-form Anima loglinear shift, so the leading-edge sigma is offset by up+ to ~2e-3 from the Anima reference. That offset is a property of the scheduler family,+ not the driver — same offset exists in the pre-refactor code path.+ """+ num_steps = 30+ full_sigmas = _anima_sigmas(num_steps)+ k_start = int(denoising_start * num_steps)+ expected_first_sigma = full_sigmas[k_start]++ cls, _ = ANIMA_SCHEDULER_MAP["dpmpp_2m"]+ accepts_sigmas = "sigmas" in inspect.signature(cls(num_train_timesteps=1000).set_timesteps).parameters++ driver = AnimaSchedulerDriver(+ scheduler_name="dpmpp_2m",+ sigmas=full_sigmas[k_start : int(denoising_end * num_steps) + 1] if accepts_sigmas else full_sigmas,+ steps=num_steps,+ denoising_start=denoising_start,+ denoising_end=denoising_end,+ device=torch.device("cpu"),+ seed=0,+ )+ first_iter = next(driver.iterations())+ 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."""+ full_sigmas = _anima_sigmas(steps)+ k_start = int(denoising_start * steps)+ k_end = int(denoising_end * steps)++ driver = AnimaSchedulerDriver(+ scheduler_name="heun",+ sigmas=full_sigmas,+ steps=steps,+ denoising_start=denoising_start,+ denoising_end=denoising_end,+ device=torch.device("cpu"),+ seed=0,+ )++ # 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+++def test_driver_terminal_sigma_prev_is_zero() -> None:+ """The last iteration's sigma_prev must be 0.0 (terminal noise level)."""+ driver = AnimaSchedulerDriver(+ scheduler_name="dpmpp_2m",+ sigmas=_anima_sigmas(8),+ steps=8,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=0,+ )+ last_iter = list(driver.iterations())[-1]+ assert last_iter.sigma_prev == 0.0+++def test_driver_seed_determinism() -> None:+ """Same seed → identical step_generator state → reproducible SDE noise."""+ sigmas = _anima_sigmas(8)+ driver_a = AnimaSchedulerDriver(+ scheduler_name="er_sde",+ sigmas=sigmas,+ steps=8,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=42,+ )+ driver_b = AnimaSchedulerDriver(+ scheduler_name="er_sde",+ sigmas=sigmas,+ steps=8,+ denoising_start=0.0,+ denoising_end=1.0,+ device=torch.device("cpu"),+ seed=42,+ )+ # Same seed → same first random draw.+ a = torch.randn((1, 4), generator=driver_a.step_generator)+ b = torch.randn((1, 4), generator=driver_b.step_generator)+ assert torch.equal(a, b)diff --git a/tests/backend/flux/test_anima_schedulers.py b/tests/backend/flux/test_anima_schedulers.pynew file mode 100644index 0000000000..b5b690c655--- /dev/null+++ b/tests/backend/flux/test_anima_schedulers.py@@ -0,0 +1,319 @@+"""Tests for Anima scheduler registry."""++import typing++import pytest+from diffusers.schedulers.scheduling_utils import SchedulerMixin++from invokeai.backend.flux.schedulers import (+ ANIMA_SCHEDULER_LABELS,+ ANIMA_SCHEDULER_MAP,+ ANIMA_SCHEDULER_NAME_VALUES,+)+++def test_anima_scheduler_map_entries_are_class_kwargs_tuples():+ """Every entry must be (SchedulerClass, kwargs_dict)."""+ for name, entry in ANIMA_SCHEDULER_MAP.items():+ assert isinstance(entry, tuple), f"{name} is not a tuple"+ assert len(entry) == 2, f"{name} tuple has wrong arity"+ cls, kwargs = entry+ assert isinstance(cls, type) and issubclass(cls, SchedulerMixin), (+ f"{name} first element is not a SchedulerMixin subclass"+ )+ assert isinstance(kwargs, dict), f"{name} second element is not a dict"+++def test_anima_scheduler_map_entries_can_be_constructed():+ """Every entry must construct cleanly by splatting its kwargs."""+ for name, (cls, kwargs) in ANIMA_SCHEDULER_MAP.items():+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ assert isinstance(scheduler, SchedulerMixin), f"{name} did not produce a SchedulerMixin"+++def test_anima_scheduler_labels_cover_every_map_key():+ for name in ANIMA_SCHEDULER_MAP.keys():+ assert name in ANIMA_SCHEDULER_LABELS, f"{name} has no label"+++def test_anima_scheduler_map_includes_new_dpmpp_entries():+ assert "dpmpp_2m" in ANIMA_SCHEDULER_MAP+ assert "dpmpp_2m_sde" in ANIMA_SCHEDULER_MAP+++def test_anima_dpmpp_2m_uses_flow_prediction():+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT++ cls, kwargs = ANIMA_SCHEDULER_MAP["dpmpp_2m"]+ assert kwargs["prediction_type"] == "flow_prediction"+ assert kwargs["use_flow_sigmas"] is True+ assert kwargs["flow_shift"] == ANIMA_SHIFT+ assert kwargs["solver_order"] == 2+ assert "algorithm_type" not in kwargs # deterministic, default algorithm+++def test_anima_dpmpp_2m_sde_uses_sde_algorithm():+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT++ cls, kwargs = ANIMA_SCHEDULER_MAP["dpmpp_2m_sde"]+ assert kwargs["prediction_type"] == "flow_prediction"+ assert kwargs["use_flow_sigmas"] is True+ assert kwargs["flow_shift"] == ANIMA_SHIFT+ assert kwargs["algorithm_type"] == "sde-dpmsolver++"+ assert kwargs["solver_order"] == 2+++def test_anima_dpmpp_2m_produces_anima_compatible_sigma_schedule():+ """The DPM++ 2M scheduler, when run through the same dispatch logic as+ anima_denoise._run_diffusion, must produce a sigma schedule equivalent+ to Anima's reference schedule (loglinear_timestep_shift with shift=3.0).++ On diffusers 0.35.1, DPMSolverMultistepScheduler.set_timesteps does not+ accept `sigmas=`, so the runtime falls back to num_inference_steps and+ relies on the scheduler's internal flow_shift=3.0 to compute equivalent+ sigmas. This test verifies that equivalence end-to-end.+ """+ import inspect++ from invokeai.app.invocations.anima_denoise import loglinear_timestep_shift+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT++ num_steps = 10++ # Reference: Anima's own pre-shifted sigma schedule.+ anima_sigmas = [loglinear_timestep_shift(ANIMA_SHIFT, 1.0 - i / num_steps) for i in range(num_steps + 1)]++ cls, kwargs = ANIMA_SCHEDULER_MAP["dpmpp_2m"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)++ # Mirror anima_denoise.py:502-506 dispatch.+ sig = inspect.signature(scheduler.set_timesteps)+ if "sigmas" in sig.parameters:+ scheduler.set_timesteps(sigmas=anima_sigmas, device="cpu")+ else:+ scheduler.set_timesteps(num_inference_steps=num_steps, device="cpu")++ diffusers_sigmas = [float(s) for s in scheduler.sigmas[: len(anima_sigmas)]]+ max_diff = max(abs(a - b) for a, b in zip(anima_sigmas, diffusers_sigmas, strict=True))+ assert max_diff < 1e-3, f"DPM++ 2M sigma schedule diverges from Anima reference (max abs diff = {max_diff:.6f})"+++def test_anima_dpmpp_2m_with_denoising_start_honors_clipped_schedule():+ """DPM++ img2img: the set_begin_index path must start at the correct sigma.++ When DPMSolverMultistepScheduler doesn't accept sigmas=, anima_denoise falls back to+ set_timesteps(num_inference_steps=full_steps) + set_begin_index(start_idx). The+ effective first sigma must match the clipped Anima reference schedule within 1e-3.+ """+ import inspect++ from invokeai.app.invocations.anima_denoise import loglinear_timestep_shift+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT++ num_steps = 30+ denoising_start = 0.5+ start_idx = int(denoising_start * num_steps) # mirrors anima_denoise clipping math++ full_sigmas = [loglinear_timestep_shift(ANIMA_SHIFT, 1.0 - i / num_steps) for i in range(num_steps + 1)]+ expected_first_sigma = full_sigmas[start_idx]++ cls, kwargs = ANIMA_SCHEDULER_MAP["dpmpp_2m"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ sig = inspect.signature(scheduler.set_timesteps)++ if "sigmas" in sig.parameters:+ # Future diffusers: sigmas= supported, clipped schedule passed directly.+ scheduler.set_timesteps(sigmas=full_sigmas[start_idx:], device="cpu")+ actual_first_sigma = float(scheduler.sigmas[0])+ else:+ # Current diffusers: use set_begin_index on the full schedule.+ scheduler.set_timesteps(num_inference_steps=num_steps, device="cpu")+ scheduler.set_begin_index(start_idx)+ actual_first_sigma = float(scheduler.sigmas[start_idx])++ assert abs(actual_first_sigma - expected_first_sigma) < 1e-3, (+ f"DPM++ first sigma with denoising_start=0.5: got {actual_first_sigma:.6f}, expected {expected_first_sigma:.6f}"+ )+++def test_anima_set_begin_index_path_step_count_with_denoising_end():+ """set_begin_index fallback must honour denoising_end, not just denoising_start.++ Regression test: the old formula (len(timesteps) - begin_index) ignored denoising_end+ and ran past it. For steps=30, denoising_start=0.2, denoising_end=0.8 the correct+ step count is 18, not 24.+ """+ import inspect++ from invokeai.app.invocations.anima_denoise import loglinear_timestep_shift+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT++ num_steps = 30+ denoising_start = 0.2+ denoising_end = 0.8++ # Reference step count from the Euler path (clipped sigmas).+ full_sigmas = [loglinear_timestep_shift(ANIMA_SHIFT, 1.0 - i / num_steps) for i in range(num_steps + 1)]+ total_sigmas = len(full_sigmas)+ start_idx = int(denoising_start * (total_sigmas - 1))+ end_idx = int(denoising_end * (total_sigmas - 1)) + 1+ expected_steps = (end_idx - start_idx) - 1 # 18++ cls, kwargs = ANIMA_SCHEDULER_MAP["dpmpp_2m"]+ scheduler = cls(num_train_timesteps=1000, **kwargs)+ sig = inspect.signature(scheduler.set_timesteps)++ scheduler_begin_index = int(denoising_start * num_steps)+ if "sigmas" in sig.parameters:+ clipped = full_sigmas[start_idx:end_idx]+ scheduler.set_timesteps(sigmas=clipped, device="cpu")+ num_scheduler_steps = len(scheduler.timesteps)+ else:+ scheduler.set_timesteps(num_inference_steps=num_steps, device="cpu")+ scheduler.set_begin_index(scheduler_begin_index)+ num_scheduler_steps = int(denoising_end * num_steps) - scheduler_begin_index++ assert num_scheduler_steps == expected_steps, (+ f"DPM++ scheduler step count with denoising_start={denoising_start}, "+ f"denoising_end={denoising_end}: got {num_scheduler_steps}, expected {expected_steps}"+ )+++ ["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+ via runtime introspection but type-check tooling would not."""+ literal_values = set(typing.get_args(ANIMA_SCHEDULER_NAME_VALUES))+ for name in ANIMA_SCHEDULER_MAP:+ assert name in literal_values, f"{name} is in the map but missing from the Literal"+++def test_anima_scheduler_literal_includes_er_sde():+ """er_sde must appear in the literal type, have a label, and be+ registered in ANIMA_SCHEDULER_MAP for dispatch through the universal+ scheduler path."""+ literal_args = typing.get_args(ANIMA_SCHEDULER_NAME_VALUES)+ assert "er_sde" in literal_args+ assert "er_sde" in ANIMA_SCHEDULER_LABELS+ assert ANIMA_SCHEDULER_LABELS["er_sde"] == "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_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.++ This is the wiring that lets Anima dispatch er_sde through the universal scheduler+ path (replacing the legacy elif is_er_sde: branch in anima_denoise.py).+ """+ from invokeai.backend.flux.schedulers import ANIMA_SHIFT+ from invokeai.backend.rectified_flow.er_sde_scheduler import ERSDEScheduler++ assert "er_sde" in ANIMA_SCHEDULER_MAP, "er_sde must be in ANIMA_SCHEDULER_MAP"+ cls, kwargs = ANIMA_SCHEDULER_MAP["er_sde"]+ assert cls is ERSDEScheduler+ assert kwargs["use_flow_sigmas"] is True+ assert kwargs["prediction_type"] == "flow_prediction"+ assert kwargs["solver_order"] == 3+ assert kwargs["stochastic"] is True+ assert kwargs["flow_shift"] == ANIMA_SHIFTdiff --git a/tests/backend/rectified_flow/test_er_sde_scheduler.py b/tests/backend/rectified_flow/test_er_sde_scheduler.pynew file mode 100644index 0000000000..a0669fc8b6--- /dev/null+++ b/tests/backend/rectified_flow/test_er_sde_scheduler.py@@ -0,0 +1,304 @@+"""Smoke / structural tests for ``ERSDEScheduler`` (PoC).++Parity against the existing ``er_sde_rf_step`` (Anima ground truth) is+deliberately deferred to Task D and lives in a separate test file.+"""++from __future__ import annotations++import pytest+import torch++from invokeai.backend.rectified_flow.er_sde_scheduler import ERSDEScheduler++# --- Construction ----------------------------------------------------------------+++ "prediction_type, solver_order, use_flow_sigmas",+ [+ ("epsilon", 1, False),+ ("epsilon", 2, False),+ ("epsilon", 3, False),+ ("v_prediction", 2, False),+ ("flow_prediction", 1, True),+ ("flow_prediction", 2, True),+ ("flow_prediction", 3, True),+ ],+)+def test_construction_smoke(prediction_type: str, solver_order: int, use_flow_sigmas: bool) -> None:+ sched = ERSDEScheduler(+ prediction_type=prediction_type,+ solver_order=solver_order,+ use_flow_sigmas=use_flow_sigmas,+ )+ assert sched.config.prediction_type == prediction_type+ assert sched.config.solver_order == solver_order+ assert sched.config.use_flow_sigmas == use_flow_sigmas+ # History containers are right length.+ assert len(sched.model_outputs) == solver_order+ assert len(sched._sigma_history) == solver_order+ assert all(m is None for m in sched.model_outputs)+ assert all(s is None for s in sched._sigma_history)+++def test_flow_prediction_requires_flow_sigmas() -> None:+ with pytest.raises(ValueError):+ ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=False)+++# --- set_timesteps ---------------------------------------------------------------+++def test_set_timesteps_accepts_user_sigmas() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3)+ user_sigmas = [1.0, 0.8, 0.5, 0.2, 0.0]+ sched.set_timesteps(sigmas=user_sigmas)+ # self.sigmas should match (terminal 0 already in the user list).+ assert sched.sigmas.tolist() == pytest.approx(user_sigmas, rel=0, abs=1e-6)+ assert sched.num_inference_steps == len(user_sigmas) - 1+++def test_set_timesteps_resets_history() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3)+ # Pre-populate state.+ sched.model_outputs = [torch.zeros(1), torch.ones(1), torch.full((1,), 2.0)]+ sched._sigma_history = [0.9, 0.5, 0.1]+ sched.lower_order_nums = 3+ sched._step_index = 5++ sched.set_timesteps(sigmas=[1.0, 0.5, 0.0])++ assert all(m is None for m in sched.model_outputs)+ assert all(s is None for s in sched._sigma_history)+ assert sched.lower_order_nums == 0+ assert sched._step_index is None+++def test_set_timesteps_default_path() -> None:+ sched = ERSDEScheduler(prediction_type="epsilon", use_flow_sigmas=False, solver_order=2)+ sched.set_timesteps(num_inference_steps=10)+ assert sched.num_inference_steps == 10+ assert len(sched.sigmas) == 11 # n + terminal 0+ assert sched.sigmas[-1].item() == pytest.approx(0.0, abs=1e-7)+++# --- Boundary handling -----------------------------------------------------------+++def test_first_order_at_sigma_one_boundary_returns_finite() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=1)+ sched.set_timesteps(sigmas=[1.0, 0.95, 0.0])+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float64)+ v = torch.randn_like(sample)+ out = sched.step(+ model_output=v,+ timestep=sched.timesteps[0],+ sample=sample,+ generator=torch.Generator().manual_seed(0),+ )+ prev = out.prev_sample+ assert torch.isfinite(prev).all(), "boundary step produced non-finite values"+ assert prev.shape == sample.shape+++def test_no_zero_division_when_prev_sigma_is_one() -> None:+ """Regression: prior step at sigma=1 must not crash subsequent higher-order branches."""+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3)+ sched.set_timesteps(sigmas=[1.0, 0.9, 0.7, 0.0])+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float64)+ gen = torch.Generator().manual_seed(0)+ for ts in sched.timesteps:+ v = torch.randn_like(sample)+ out = sched.step(model_output=v, timestep=ts, sample=sample, generator=gen)+ sample = out.prev_sample+ assert torch.isfinite(sample).all()+++# --- Multistep ramp --------------------------------------------------------------+++def test_multistep_ramp_engages_higher_orders() -> None:+ """``lower_order_nums`` ramps 0->1->2->3 and order-2 / order-3 branches actually engage."""+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3)+ # Avoid sigma=1 boundary so all three orders engage cleanly.+ sched.set_timesteps(sigmas=[0.95, 0.7, 0.5, 0.3, 0.0])++ sample = torch.randn(1, 4, 8, 8, dtype=torch.float64)+ gen = torch.Generator().manual_seed(0)++ nums_seen = [sched.lower_order_nums]+ # Run enough steps to fully ramp.+ for ts in sched.timesteps[:3]:+ v = torch.randn_like(sample)+ sched.step(model_output=v, timestep=ts, sample=sample, generator=gen)+ nums_seen.append(sched.lower_order_nums)++ assert nums_seen == [0, 1, 2, 3], f"unexpected ramp: {nums_seen}"++ # Behavioural check: deterministic (no-noise) order-3 trajectory must diverge from+ # deterministic order-1 trajectory after multiple steps — the higher-order Taylor+ # terms have to actually contribute.+ sigmas = [0.95, 0.7, 0.5, 0.3, 0.0]+ sched_d3 = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3, stochastic=False)+ sched_d3.set_timesteps(sigmas=sigmas)+ sched_d1 = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=1, stochastic=False)+ sched_d1.set_timesteps(sigmas=sigmas)++ torch.manual_seed(42)+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float64)+ vs = [torch.randn_like(sample) for _ in range(len(sigmas) - 1)]++ sample_d3 = sample.clone()+ sample_d1 = sample.clone()+ for i, ts in enumerate(sched_d3.timesteps):+ sample_d3 = sched_d3.step(model_output=vs[i], timestep=ts, sample=sample_d3).prev_sample+ sample_d1 = sched_d1.step(model_output=vs[i], timestep=ts, sample=sample_d1).prev_sample++ assert not torch.allclose(sample_d3, sample_d1, atol=1e-4), (+ "order-3 multistep produced same result as order-1 — higher-order branches not engaging"+ )+++# --- Stochastic vs deterministic -------------------------------------------------+++def test_stochastic_and_deterministic_diverge() -> None:+ """Same seed; stochastic=True vs False must produce visibly different trajectories."""+ sigmas = [0.95, 0.7, 0.5, 0.3, 0.0]+ sched_s = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=2, stochastic=True)+ sched_d = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=2, stochastic=False)+ sched_s.set_timesteps(sigmas=sigmas)+ sched_d.set_timesteps(sigmas=sigmas)++ torch.manual_seed(0)+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float64)+ sample_s = sample.clone()+ sample_d = sample.clone()++ torch.manual_seed(123)+ vs = [torch.randn_like(sample) for _ in range(len(sigmas) - 1)]++ gen_s = torch.Generator().manual_seed(7)+ gen_d = torch.Generator().manual_seed(7)+ for i, ts in enumerate(sched_s.timesteps):+ sample_s = sched_s.step(model_output=vs[i], timestep=ts, sample=sample_s, generator=gen_s).prev_sample+ sample_d = sched_d.step(model_output=vs[i], timestep=ts, sample=sample_d, generator=gen_d).prev_sample++ assert not torch.allclose(sample_s, sample_d, atol=1e-5), (+ "stochastic and deterministic runs are identical — noise injection not happening"+ )+++# --- Long-run stability ----------------------------------------------------------+++def test_30_step_flow_trajectory_no_nan() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=3)+ sched.set_timesteps(num_inference_steps=30)+ torch.manual_seed(0)+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float32)+ gen = torch.Generator().manual_seed(0)+ for ts in sched.timesteps:+ # Synthetic "model": small constant velocity so trajectory stays bounded.+ v = torch.randn_like(sample) * 0.1+ out = sched.step(model_output=v, timestep=ts, sample=sample, generator=gen)+ sample = out.prev_sample+ assert torch.isfinite(sample).all(), f"non-finite output at timestep {ts}"+++def test_30_step_vp_trajectory_no_nan() -> None:+ sched = ERSDEScheduler(prediction_type="epsilon", use_flow_sigmas=False, solver_order=3)+ sched.set_timesteps(num_inference_steps=30)+ torch.manual_seed(0)+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float32) * sched.init_noise_sigma+ gen = torch.Generator().manual_seed(0)+ for ts in sched.timesteps:+ eps = torch.randn_like(sample) * 0.1+ out = sched.step(model_output=eps, timestep=ts, sample=sample, generator=gen)+ sample = out.prev_sample+ assert torch.isfinite(sample).all(), f"non-finite output at timestep {ts}"+++def test_vp_smoke_full_gate() -> None:+ """SD/SDXL VP-mode gate test for the universal-scheduler wiring (Task E).++ Constructs ERSDEScheduler in the SD/SDXL configuration (epsilon prediction,+ VP sigmas, third-order multistep, stochastic), then walks 30 steps with+ synthetic epsilon predictions and asserts:++ 1. Every intermediate sample is finite (no NaN/Inf).+ 2. L2 norm stays in a sane range — not exploding, not collapsing.+ 3. ``lower_order_nums`` ramps 0 -> 1 -> 2 -> 3 (higher-order branches engage).+ """+ sched = ERSDEScheduler(+ prediction_type="epsilon",+ use_flow_sigmas=False,+ solver_order=3,+ stochastic=True,+ )+ sched.set_timesteps(num_inference_steps=30)+ assert sched.num_inference_steps == 30+ assert sched.lower_order_nums == 0++ torch.manual_seed(0)+ # Initial sample at the VP-SDE init scale (sigma_max ~ sqrt(sigma_train_max^2)).+ sample = torch.randn(1, 4, 8, 8, dtype=torch.float32) * float(sched.sigmas[0].item())+ gen = torch.Generator().manual_seed(0)++ # Track ramp + per-step norms.+ ramp = [sched.lower_order_nums]+ norms: list[float] = []++ for i, ts in enumerate(sched.timesteps):+ # Synthetic epsilon prediction — small random tensor.+ eps = torch.randn_like(sample) * 0.1+ out = sched.step(model_output=eps, timestep=ts, sample=sample, generator=gen)+ sample = out.prev_sample+ ramp.append(sched.lower_order_nums)++ norm = float(torch.linalg.vector_norm(sample).item())+ norms.append(norm)++ assert torch.isfinite(sample).all(), f"non-finite sample at step {i} (timestep={ts})"+ # Sanity bounds — won't catch subtle bugs but will catch explosion/collapse.+ assert norm < 1e6, f"norm exploded at step {i}: {norm}"+ assert norm > 1e-6, f"norm collapsed at step {i}: {norm}"++ # Ramp must have hit each multistep order. After 3 steps, lower_order_nums == 3.+ assert ramp[0] == 0+ assert ramp[1] == 1+ assert ramp[2] == 2+ assert ramp[3] == 3+ # And it should saturate at 3 thereafter.+ assert all(n == 3 for n in ramp[3:]), f"lower_order_nums did not saturate at 3: {ramp}"+++# --- Misc ------------------------------------------------------------------------+++def test_scale_model_input_is_noop() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True)+ x = torch.randn(2, 3)+ assert torch.equal(sched.scale_model_input(x, timestep=0), x)+++def test_step_advances_step_index() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, solver_order=2)+ sched.set_timesteps(sigmas=[0.9, 0.5, 0.0])+ sample = torch.randn(1, 4, 8, 8)+ v = torch.randn_like(sample)+ sched.step(model_output=v, timestep=sched.timesteps[0], sample=sample)+ assert sched.step_index == 1+ sched.step(model_output=v, timestep=sched.timesteps[1], sample=sample)+ assert sched.step_index == 2+++def test_add_noise_shape() -> None:+ sched = ERSDEScheduler(prediction_type="flow_prediction", use_flow_sigmas=True)+ sched.set_timesteps(num_inference_steps=10)+ sample = torch.randn(2, 4, 8, 8)+ noise = torch.randn_like(sample)+ timesteps = sched.timesteps[:2]+ noisy = sched.add_noise(sample, noise, timesteps)+ assert noisy.shape == sample.shape