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.

7.4 KB
Raw Blame
"""Flow Matching scheduler definitions and mapping.

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 Any, Literal, Type

import torch
from 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 versions
try:
    from diffusers import FlowMatchLCMScheduler

    _HAS_LCM = True
except ImportError:
    _HAS_LCM = False

# Scheduler name literal type for type checking
FLUX_SCHEDULER_NAME_VALUES = Literal["euler", "heun", "lcm"]

# Human-readable labels for the UI
FLUX_SCHEDULER_LABELS: dict[str, str] = {
    "euler": "Euler",
    "heun": "Heun (2nd order)",
    "lcm": "LCM",
}

# Mapping from scheduler names to scheduler classes
FLUX_SCHEDULER_MAP: dict[str, Type[SchedulerMixin]] = {
    "euler": FlowMatchEulerDiscreteScheduler,
    "heun": FlowMatchHeunDiscreteScheduler,
}

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 Diffusers Heun scheduler's layout from InvokeAI's shifted model sigmas."""
    if not sigmas:
        raise ValueError("At least one model-evaluation sigma is required")

    # Diffusers' Heun set_timesteps() creates a schedule with the first
    # sigma evaluated once and every later sigma twice. The final interval ends
    # at the terminal sigma and has no second-order evaluation.
    scheduler.set_timesteps(num_inference_steps=len(sigmas), device=device)
    model_sigmas = torch.tensor(sigmas, dtype=torch.float32, device=device)
    expanded_sigmas = torch.cat((model_sigmas[:1], model_sigmas[1:].repeat_interleave(2)))
    scheduler.timesteps = expanded_sigmas * scheduler.config.num_train_timesteps
    scheduler.sigmas = torch.cat((expanded_sigmas, model_sigmas.new_tensor([terminal_sigma])))

    # set_timesteps() resets derivative, timestep-index and begin-index state.
    # It does not clear the stored sample when reusing an interrupted scheduler.
    scheduler.sample = None


def set_timesteps_from_sigmas(
    scheduler: SchedulerMixin,
    sigmas: list[float],
    terminal_sigma: float,
    device: str | torch.device | None,
) -> None:
    """Set InvokeAI's shifted model sigmas on a scheduler whose set_timesteps() takes them (Euler, LCM)."""
    # set_timesteps() appends a terminal sigma of 0, and step() reads sigmas[step_index + 1], so the
    # requested terminal sigma has to replace it for a pass that ends before the schedule does.
    scheduler.set_timesteps(sigmas=sigmas, device=device)
    # step() otherwise finds its index by value, which lands past the first entry when the leading sigma repeats.
    scheduler.set_begin_index(0)
    scheduler.sigmas[-1] = torch.as_tensor(terminal_sigma, dtype=scheduler.sigmas.dtype, device=scheduler.sigmas.device)


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).
ZIMAGE_SCHEDULER_NAME_VALUES = Literal["euler", "heun", "lcm"]

# Human-readable labels for the UI
ZIMAGE_SCHEDULER_LABELS: dict[str, str] = {
    "euler": "Euler",
    "heun": "Heun (2nd order)",
    "lcm": "LCM",
}

# Mapping from scheduler names to scheduler classes
ZIMAGE_SCHEDULER_MAP: dict[str, Type[SchedulerMixin]] = {
    "euler": FlowMatchEulerDiscreteScheduler,
    "heun": FlowMatchHeunDiscreteScheduler,
}

if _HAS_LCM:
    ZIMAGE_SCHEDULER_MAP["lcm"] = FlowMatchLCMScheduler


# ERNIE-Image schedulers (also Flow Matching). Standard ERNIE-Image runs 50 steps
# with CFG 4.0, ERNIE-Image-Turbo runs 8 steps with CFG 1.0.
ERNIE_IMAGE_SCHEDULER_NAME_VALUES = Literal["euler", "heun", "lcm"]

ERNIE_IMAGE_SCHEDULER_LABELS: dict[str, str] = {
    "euler": "Euler",
    "heun": "Heun (2nd order)",
    "lcm": "LCM",
}

ERNIE_IMAGE_SCHEDULER_MAP: dict[str, Type[SchedulerMixin]] = {
    "euler": FlowMatchEulerDiscreteScheduler,
    "heun": FlowMatchHeunDiscreteScheduler,
}

if _HAS_LCM:
    ERNIE_IMAGE_SCHEDULER_MAP["lcm"] = FlowMatchLCMScheduler

# The shift both released ERNIE-Image pipelines ship in `scheduler/scheduler_config.json`
# (base and Turbo alike), against diffusers' default of 1.0. Unlike Anima below, the ERNIE
# driver hands the scheduler *raw* sigmas and relies on it to apply the shift, so this belongs
# on the scheduler rather than being folded into the sigmas. A single-file checkpoint ships no
# scheduler config at all, which is what makes the constant necessary.
ERNIE_IMAGE_SHIFT = 4.0


# Anima scheduler types.
# Anima uses rectified flow with shift=3.0. The driver passes pre-shifted sigmas, so Euler, Heun and LCM
# entries carry shift=1.0 to avoid double-shifting: Euler and LCM take them through set_timesteps(sigmas=...),
# Heun through set_heun_timesteps_from_sigmas. DPM++ on diffusers takes no sigmas= and builds its own
# internal schedule, so it needs flow_shift=ANIMA_SHIFT in kwargs to match Anima's reference loglinear schedule.

# Fixed shift factor for the Anima rectified-flow noise schedule.
ANIMA_SHIFT = 3.0

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",
}

# 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 driver passes the scheduler pre-shifted sigmas,
# use shift=1.0; otherwise use shift=ANIMA_SHIFT so the scheduler builds the correct internal schedule.
ANIMA_SCHEDULER_MAP: dict[str, tuple[Type[SchedulerMixin], dict[str, Any]]] = {
    "euler": (FlowMatchEulerDiscreteScheduler, {"shift": 1.0}),
    "heun": (FlowMatchHeunDiscreteScheduler, {"shift": 1.0}),
    "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, {"shift": 1.0})