Skip to content

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

fix(flux): stop extrapolating the FLUX.1 schedule shift past its fit

Alexander Eichhornaa307a91969a
diff --git a/invokeai/backend/flux/sampling_utils.py b/invokeai/backend/flux/sampling_utils.py
index be81d6458d..f0b8e2f1ee 100644
--- a/invokeai/backend/flux/sampling_utils.py
+++ b/invokeai/backend/flux/sampling_utils.py
@@ -34,7 +34,16 @@ def time_shift(mu: float, sigma: float, t: torch.Tensor) -> torch.Tensor:
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
-def get_lin_function(x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15) -> Callable[[float], float]:
+# The two points the mu fit below is built on. 4096 image tokens is a 1024x1024 frame -- one
+# megapixel, and the resolution the reference pipeline defaults to. The line says nothing beyond it.
+MU_FIT_MIN_SEQ_LEN = 256
+MU_FIT_MAX_SEQ_LEN = 4096
+
+
+def get_lin_function(
+ x1: float = MU_FIT_MIN_SEQ_LEN, y1: float = 0.5, x2: float = MU_FIT_MAX_SEQ_LEN, y2: float = 1.15
+) -> Callable[[float], float]:
+ """A line through two points. Callers must not evaluate it past `x2` -- see `get_schedule`."""
m = (y2 - y1) / (x2 - x1)
b = y1 - m * x1
return lambda x: m * x + b
@@ -52,8 +61,26 @@ def get_schedule(
# shifting the schedule to favor high timesteps for higher signal images
if shift:
- # estimate mu based on linear estimation between two points
- mu = get_lin_function(y1=base_shift, y2=max_shift)(image_seq_len)
+ # The fit is a straight line through two points, so it is not evaluated past the second one.
+ # Extrapolated, mu reaches 3.23 at 2048px, 6.70 at 3072px and 11.55 at 4096px, and the
+ # schedule flattens with it -- the smallest non-zero timestep rises to 0.47, 0.97 and
+ # 0.9997. `clip_timestep_schedule_fractional` then has almost nothing left below
+ # `1 - denoising_start`. Steps surviving a 30-step request at `denoising_start=0.5`:
+ # 8 at 1 MP, 6 at 1.6 MP, 4 at 2.4 MP, 2 at 4.2 MP, and from ~3376px square every
+ # `denoising_start` a user can set leaves exactly one.
+ #
+ # The effect is graded, not a cliff: between 1 MP and ~1.6 MP the unclamped schedule is not
+ # degenerate, and holding mu there is a judgement -- never evaluate the fit outside the
+ # range it was built on -- rather than a defect fix. `invokeai/backend/ltx2/sampling.py`
+ # holds its own mu at both anchors on the same reasoning; ComfyUI's default FLUX.1 sampling
+ # uses a fixed shift of 1.15 at every resolution.
+ #
+ # Only the upper anchor is held. Below 256 tokens mu merely sags to 0.457, which is
+ # harmless, and clamping there would cost small frames the interpolation they rely on.
+ #
+ # At or below 4096 tokens this is a no-op -- note that is an *area*, so a 1024x1280 canvas
+ # is already above it.
+ mu = get_lin_function(y1=base_shift, y2=max_shift)(min(image_seq_len, MU_FIT_MAX_SEQ_LEN))
timesteps = time_shift(mu, 1.0, timesteps)
return timesteps.tolist()
diff --git a/tests/app/invocations/test_denoise_noise_inputs.py b/tests/app/invocations/test_denoise_noise_inputs.py
index 76336f9b85..40cf0836b4 100644
--- a/tests/app/invocations/test_denoise_noise_inputs.py
+++ b/tests/app/invocations/test_denoise_noise_inputs.py
@@ -21,7 +21,7 @@ from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvoca
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional, get_schedule
from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP, FLUX_SCHEDULER_MAP, ZIMAGE_SCHEDULER_MAP
from invokeai.backend.flux2.sampling_utils import get_schedule_flux2
-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.model_manager.taxonomy import BaseModelType, FluxVariantType, ModelType
def test_flux_prepare_noise_uses_external_noise():
@@ -96,6 +96,67 @@ def test_flux_add_noise_false_ignores_connected_noise():
assert torch.equal(result, init_latents)
+ ["variant", "expects_shift"],
+ [(FluxVariantType.Schnell, False), (FluxVariantType.Dev, True)],
+)
+def test_flux_derives_the_schedule_shift_and_token_count_from_the_model(variant: FluxVariantType, expects_shift: bool):
+ """Two wirings that live only at the node, and that cells on `get_schedule` cannot see.
+
+ `shift=not is_schnell` is the only thing deciding whether FLUX.1 shifts its schedule at all.
+ And `image_seq_len` is a *packed* token count -- 4096 for a 1024x1024 frame -- which is the unit
+ the shift's fit and its clamp are expressed in; passing latent dimensions instead would be four
+ times too large and, above one megapixel, now invisible because both values clamp alike.
+ """
+ invocation = FluxDenoiseInvocation.model_construct(
+ latents=MagicMock(latents_name="latents"),
+ add_noise=False,
+ width=1024,
+ height=1024,
+ num_steps=4,
+ denoising_start=0.25,
+ denoising_end=0.25,
+ positive_text_conditioning=MagicMock(conditioning_name="positive"),
+ transformer=MagicMock(transformer="transformer"),
+ seed=123,
+ )
+ init_latents = torch.full((1, 16, 128, 128), 2.0)
+ dummy_conditioning = SimpleNamespace(
+ t5_embeds=torch.zeros(1, 4, 16),
+ clip_embeds=torch.zeros(1, 768),
+ to=lambda **_: dummy_conditioning,
+ )
+ mock_context = MagicMock()
+ mock_context.tensors.load.return_value = init_latents
+ mock_context.conditioning.load.return_value = SimpleNamespace(conditionings=[dummy_conditioning])
+ mock_context.models.get_config.return_value = SimpleNamespace(
+ base=BaseModelType.Flux, type=ModelType.Main, variant=variant
+ )
+ schedule_calls: list[dict[str, object]] = []
+
+ with (
+ patch(
+ "invokeai.app.invocations.flux.flux_denoise.TorchDevice.choose_torch_device",
+ return_value=torch.device("cpu"),
+ ),
+ patch("invokeai.app.invocations.flux.flux_denoise.FLUXConditioningInfo", object),
+ patch(
+ "invokeai.app.invocations.flux.flux_denoise.RegionalPromptingExtension.from_text_conditioning",
+ return_value=MagicMock(),
+ ),
+ patch.object(invocation, "_load_redux_conditioning", return_value=[]),
+ patch(
+ "invokeai.app.invocations.flux.flux_denoise.get_schedule",
+ side_effect=lambda **kwargs: schedule_calls.append(kwargs) or [0.75],
+ ),
+ ):
+ invocation._run_diffusion(mock_context)
+
+ assert len(schedule_calls) == 1
+ assert schedule_calls[0]["shift"] is expects_shift
+ assert schedule_calls[0]["image_seq_len"] == 4096
+
+
def test_flux2_prepare_noise_uses_external_noise():
invocation = Flux2DenoiseInvocation.model_construct(
width=64, height=64, seed=0, noise=MagicMock(latents_name="noise")
diff --git a/tests/backend/flux/test_sampling_utils.py b/tests/backend/flux/test_sampling_utils.py
index a74204ea3e..34ba29b9f7 100644
--- a/tests/backend/flux/test_sampling_utils.py
+++ b/tests/backend/flux/test_sampling_utils.py
@@ -1,7 +1,16 @@
+import math
+
import pytest
import torch
-from invokeai.backend.flux.sampling_utils import clip_timestep_schedule, clip_timestep_schedule_fractional
+from invokeai.backend.flux.sampling_utils import (
+ MU_FIT_MAX_SEQ_LEN,
+ MU_FIT_MIN_SEQ_LEN,
+ clip_timestep_schedule,
+ clip_timestep_schedule_fractional,
+ get_lin_function,
+ get_schedule,
+)
def float_lists_almost_equal(list1: list[float], list2: list[float], tol: float = 1e-6) -> bool:
@@ -74,3 +83,87 @@ def test_clip_timestep_schedule_fractional(
assert float_lists_almost_equal(
clip_timestep_schedule_fractional(timesteps, denoising_start, denoising_end), expected_timesteps
)
+
+
+def mu_of(image_seq_len: int) -> float:
+ """Recover the shift the schedule was built with, through the public function.
+
+ `get_schedule(2, n)` is [1.0, x, 0.0] with x = exp(mu) / (exp(mu) + 1), because `time_shift`'s
+ `(1 / t - 1) ** sigma` term is 1 at t = 0.5 for every sigma. That makes the readback exact but
+ blind to the *shape* of the shift -- `test_the_shift_has_the_shape_this_readback_assumes` pins
+ that separately, and without it a changed sigma would slip past every cell below.
+ """
+ x = get_schedule(num_steps=2, image_seq_len=image_seq_len, shift=True)[1]
+ return math.log(x / (1.0 - x))
+
+
+def test_the_shift_has_the_shape_this_readback_assumes():
+ """One schedule pinned outright, computed by hand from exp(mu) / (exp(mu) + (1 / t - 1)).
+
+ The interesting entries are the asymmetric ones: at t = 0.75 and t = 0.25 a sigma of 2 would
+ give 0.966 and 0.260 instead, while t = 0.5 would be unchanged.
+ """
+ assert float_lists_almost_equal(
+ get_schedule(num_steps=4, image_seq_len=MU_FIT_MAX_SEQ_LEN, shift=True),
+ [1.0, 0.904531, 0.759511, 0.512844, 0.0],
+ tol=1e-5,
+ )
+
+
+def test_the_anchors_are_where_the_clamp_assumes_they_are():
+ """Written as literals on purpose.
+
+ Asserting `line(MU_FIT_MAX_SEQ_LEN) == 1.15` would hold for any anchor value, because the
+ constants are also `get_lin_function`'s own defaults -- it would pass with the anchor moved to
+ 8192, which is exactly the drift it is supposed to catch.
+ """
+ assert MU_FIT_MIN_SEQ_LEN == 256
+ assert MU_FIT_MAX_SEQ_LEN == 4096
+ assert get_lin_function()(4096) == pytest.approx(1.15)
+
+
+ ["image_seq_len", "expected_mu"],
+ [
+ (MU_FIT_MIN_SEQ_LEN, 0.5), # 256px: the lower point of the fit
+ (1024, 0.63), # 512px: interpolation, unaffected
+ (MU_FIT_MAX_SEQ_LEN, 1.15), # 1024px: the upper point, where the fit ends
+ (9216, 1.15), # 1536px: beyond the fit, held
+ (16384, 1.15), # 2048px: extrapolation would give 3.23
+ (36864, 1.15), # 3072px: extrapolation would give 6.70
+ (65536, 1.15), # 4096px: extrapolation would give 11.55
+ ],
+)
+def test_the_shift_is_not_extrapolated_past_the_fit(image_seq_len: int, expected_mu: float):
+ assert mu_of(image_seq_len) == pytest.approx(expected_mu, abs=1e-3)
+
+
+def test_the_fit_is_still_live_below_its_upper_point():
+ """Holding the fit at its endpoint is not the same as replacing it with a constant, and this
+ names that choice: below one megapixel the schedule still adapts to the frame."""
+ assert mu_of(512) < mu_of(1024) < mu_of(2048) < mu_of(MU_FIT_MAX_SEQ_LEN)
+
+
+ ["image_seq_len", "why"],
+ [
+ (MU_FIT_MAX_SEQ_LEN, "1024px: the anchor, a control -- unchanged by the clamp either way"),
+ (16384, "2048px: 2 of 30 steps survived before the clamp"),
+ (36864, "3072px: 1 of 30 survived, whatever the user asked for"),
+ ],
+)
+def test_the_clipped_schedule_keeps_the_same_steps_at_every_frame_size(image_seq_len: int, why: str):
+ """An extrapolated shift pushed the schedule above the `denoising_start` line, so the clip was
+ left with one or two steps no matter how many were requested -- an img2img or upscale pass that
+ silently did almost nothing.
+
+ 0.499 is not arbitrary: it is what the upscale widget's creativity slider sends at its middle
+ position, ((0 * -1 + 10) * 4.99) / 100 (`features/upscale/core/graph.ts`).
+ """
+ timesteps = get_schedule(num_steps=30, image_seq_len=image_seq_len, shift=True)
+ assert len(clip_timestep_schedule_fractional(timesteps, 0.499, 1.0)) - 1 == 8, why
+
+
+def test_schnell_is_untouched_because_it_does_not_shift():
+ unshifted = get_schedule(num_steps=4, image_seq_len=65536, shift=False)
+ assert float_lists_almost_equal(unshifted, torch.linspace(1, 0, 5).tolist())