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
fix(flux): address scheduler review follow-ups
JPPhoto7358fb083af9
diff --git a/invokeai/backend/flux/controlnet/controlnet_flux_output.py b/invokeai/backend/flux/controlnet/controlnet_flux_output.pyindex 55940460c3..9dd0ef5dbd 100644--- a/invokeai/backend/flux/controlnet/controlnet_flux_output.py+++ b/invokeai/backend/flux/controlnet/controlnet_flux_output.py@@ -52,6 +52,8 @@ def sum_controlnet_flux_outputs() -> ControlNetFluxOutput:controlnet_output_sum = ControlNetFluxOutput(single_block_residuals=None, double_block_residuals=None)+ # TODO: summing residuals materializes tensors that may otherwise share references,+ # increasing peak memory when several ControlNets are active.for controlnet_output in controlnet_outputs:controlnet_output_sum = add_controlnet_flux_outputs(controlnet_output_sum, controlnet_output)diff --git a/invokeai/backend/flux/denoise.py b/invokeai/backend/flux/denoise.pyindex ce025d9ae6..49783bc1aa 100644--- a/invokeai/backend/flux/denoise.py+++ b/invokeai/backend/flux/denoise.py@@ -1,4 +1,3 @@-import inspectimport mathfrom typing import Callable@@ -53,30 +52,26 @@ def denoise(# Initialize scheduler with timesteps# The timesteps list contains values in [0, 1] range (sigmas)- # LCM should use num_inference_steps (it has its own sigma schedule),- # while other schedulers can use custom sigmas if supported- is_lcm = is_flow_match_lcm_scheduler(scheduler)- set_timesteps_sig = inspect.signature(scheduler.set_timesteps)+ # Euler and Heun use InvokeAI's custom sigmas; LCM owns its schedule.if isinstance(scheduler, FlowMatchHeunDiscreteScheduler):set_heun_timesteps_from_sigmas(scheduler, timesteps[:-1], timesteps[-1], img.device)- elif not is_lcm and "sigmas" in set_timesteps_sig.parameters:+ elif isinstance(scheduler, FlowMatchEulerDiscreteScheduler):# InvokeAI supplies model-evaluation sigmas plus its requested terminal endpoint.scheduler.set_timesteps(sigmas=timesteps[:-1], device=img.device)- if hasattr(scheduler, "sigmas"):- scheduler.sigmas[-1] = torch.as_tensor(- timesteps[-1], dtype=scheduler.sigmas.dtype, device=scheduler.sigmas.device- )- else:- # LCM or scheduler doesn't support custom sigmas - use num_inference_steps- # The schedule will be computed by the scheduler itself. For LCM,- # clipping controls the requested step count but not exact start/end- # sigmas; keep that scheduler-defined behavior intact.+ scheduler.sigmas[-1] = torch.as_tensor(+ timesteps[-1], dtype=scheduler.sigmas.dtype, device=scheduler.sigmas.device+ )+ elif is_flow_match_lcm_scheduler(scheduler):+ # LCM owns its schedule; clipping controls the requested evaluation count,+ # while its exact start/end sigmas remain scheduler-defined.## Important for img2img callers: if the initial latent/noise blend was# computed from a separate pre-scheduler schedule, that preblend may not# match this scheduler's true first step exactly.num_inference_steps = len(timesteps) - 1scheduler.set_timesteps(num_inference_steps=num_inference_steps, device=img.device)+ else:+ raise TypeError(f"Unsupported FLUX scheduler: {type(scheduler).__name__}")# For schedulers like Heun, the number of actual steps may differ# (Heun doubles timesteps internally)@@ -123,7 +118,7 @@ def denoise()# For Heun scheduler, track if we're in first or second order step- is_heun = hasattr(scheduler, "state_in_first_order")+ is_heun = isinstance(scheduler, FlowMatchHeunDiscreteScheduler)in_first_order = scheduler.state_in_first_order if is_heun else True# Run ControlNet models@@ -190,6 +185,8 @@ def denoise(neg_img_input = torch.cat((neg_img_input, img_cond), dim=-1)if img_cond_seq is not None:+ # Keep positive and negative spatial contexts aligned for Kontext; omitting+ # reference tokens from the negative pass creates visible artifacts.neg_img_input = torch.cat((neg_img_input, img_cond_seq), dim=1)neg_img_input_ids = torch.cat((neg_img_input_ids, img_cond_seq_ids), dim=1)@@ -249,7 +246,9 @@ def denoise(step_callback(PipelineIntermediateState(step=user_step,- order=2 if not in_first_order else 1,+ # This callback aggregates a completed user-facing interval; its+ # order is progress semantics, not the solver's internal order.+ order=1,total_steps=total_steps,timestep=int(t_curr * 1000),latents=preview_img,diff --git a/invokeai/backend/flux/schedulers.py b/invokeai/backend/flux/schedulers.pyindex 82859ee99a..64ab9a6993 100644--- a/invokeai/backend/flux/schedulers.py+++ b/invokeai/backend/flux/schedulers.py@@ -50,24 +50,22 @@ def set_heun_timesteps_from_sigmas(terminal_sigma: float,device: str | torch.device | None,) -> None:- """Set the pinned Diffusers Heun layout from InvokeAI's shifted model sigmas."""+ """Set Diffusers 0.41.0's Heun layout from InvokeAI's shifted model sigmas."""if not sigmas:raise ValueError("At least one model-evaluation sigma is required")- # Diffusers 0.40.0 evaluates the first sigma once, later sigmas twice, then- # uses one terminal interval without a second-order evaluation.+ # In Diffusers 0.41.0, 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.num_inference_steps = len(sigmas)scheduler.timesteps = expanded_sigmas * scheduler.config.num_train_timestepsscheduler.sigmas = torch.cat((expanded_sigmas, model_sigmas.new_tensor([terminal_sigma])))- # Reset the state used by Diffusers step() and state_in_first_order.- scheduler.prev_derivative = None- scheduler.dt = None+ # 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- scheduler._step_index = None- scheduler._begin_index = Nonedef is_flow_match_lcm_scheduler(scheduler: SchedulerMixin) -> bool:diff --git a/tests/backend/flux/test_denoise.py b/tests/backend/flux/test_denoise.pyindex 27f18ca557..c699ee610c 100644--- a/tests/backend/flux/test_denoise.py+++ b/tests/backend/flux/test_denoise.py@@ -4,6 +4,7 @@ import pytestimport torchfrom diffusers import FlowMatchEulerDiscreteScheduler, FlowMatchHeunDiscreteScheduler+from invokeai.app.util.step_callback import calc_percentagefrom invokeai.backend.flux.denoise import denoisefrom invokeai.backend.flux.schedulers import _HAS_LCM, FLUX_SCHEDULER_MAP@@ -61,6 +62,26 @@ class _SampleDependentFluxModel:return 0.1 * img + 0.2 * sigma+class _NonUniformCFGFluxModel:+ def __init__(self) -> None:+ self.calls: list[tuple[int, float, torch.Tensor]] = []++ def __call__(+ self,+ img: torch.Tensor,+ txt: torch.Tensor,+ timesteps: torch.Tensor,+ timestep_index: int,+ **kwargs: object,+ ) -> torch.Tensor:+ del kwargs+ sigma = float(timesteps[0])+ prompt_value = float(txt.mean())+ if prompt_value > 0:+ self.calls.append((timestep_index, prompt_value, img.clone()))+ return 0.1 * img + prompt_value * sigma++class _RecordingInpaintExtension:def __init__(self) -> None:self.sigmas: list[float] = []@@ -81,45 +102,6 @@ class _FakeDyPEExtension:self.sigmas.append(sigma)-class _FakeScheduler:- def __init__(self) -> None:- self.config = SimpleNamespace(num_train_timesteps=1000)- self.timesteps = torch.tensor([], dtype=torch.float32)- self.sigmas = torch.tensor([], dtype=torch.float32)-- def set_timesteps(self, sigmas: list[float], device: torch.device) -> None:- del device- self.sigmas = torch.tensor([*sigmas, 0.0], dtype=torch.float32)- self.timesteps = torch.tensor([900.0, 400.0], dtype=torch.float32)-- def step(self, model_output: torch.Tensor, timestep: torch.Tensor, sample: torch.Tensor) -> SimpleNamespace:- del model_output, timestep- return SimpleNamespace(prev_sample=sample)---class _FakeHeunScheduler:- def __init__(self) -> None:- self.config = SimpleNamespace(num_train_timesteps=1000)- self.timesteps = torch.tensor([], dtype=torch.float32)- self.sigmas = torch.tensor([], dtype=torch.float32)- self.state_in_first_order = True- self._step_index = 0-- def set_timesteps(self, sigmas: list[float], device: torch.device) -> None:- del device- # Duplicate each user-facing step to mimic a second-order scheduler.- self.sigmas = torch.tensor([1.0, 1.0, 0.25, 0.25, 0.0], dtype=torch.float32)- self.timesteps = torch.tensor([900.0, 850.0, 400.0, 350.0], dtype=torch.float32)- self._step_index = 0- self.state_in_first_order = True-- def step(self, model_output: torch.Tensor, timestep: torch.Tensor, sample: torch.Tensor) -> SimpleNamespace:- del model_output, timestep- self._step_index += 1- self.state_in_first_order = self._step_index % 2 == 0- return SimpleNamespace(prev_sample=sample)--class _FakePbar:def update(self, value: int) -> None:del value@@ -185,7 +167,7 @@ def test_denoise_scheduler_path_prefers_scheduler_sigmas_for_dype(monkeypatch):monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)model = _FakeFluxModel()- scheduler = _FakeScheduler()+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=1.0)dype_extension = _FakeDyPEExtension()img = torch.zeros(1, 2, 4)img_ids = torch.zeros(1, 2, 3)@@ -217,42 +199,6 @@ def test_denoise_scheduler_path_prefers_scheduler_sigmas_for_dype(monkeypatch):assert dype_extension.sigmas == [1.0, 0.25]-def test_denoise_heun_scheduler_path_uses_internal_scheduler_sigmas(monkeypatch):- monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)-- model = _FakeFluxModel()- scheduler = _FakeHeunScheduler()- dype_extension = _FakeDyPEExtension()- img = torch.zeros(1, 2, 4)- img_ids = torch.zeros(1, 2, 3)- regional_prompting_extension = _build_regional_prompting_extension(batch_size=1)- callback_steps: list[int] = []-- denoise(- model=model,- img=img,- img_ids=img_ids,- pos_regional_prompting_extension=regional_prompting_extension,- neg_regional_prompting_extension=None,- timesteps=[1.0, 0.25, 0.0],- step_callback=lambda state: callback_steps.append(state.step),- guidance=1.0,- cfg_scale=[1.0, 1.0],- inpaint_extension=None,- controlnet_extensions=[],- pos_ip_adapter_extensions=[],- neg_ip_adapter_extensions=[],- img_cond=None,- img_cond_seq=None,- img_cond_seq_ids=None,- dype_extension=dype_extension,- scheduler=scheduler,- )-- assert dype_extension.sigmas == [1.0, 1.0, 0.25, 0.25]- assert callback_steps == [1, 2]--@pytest.mark.parametrize("scheduler_name", sorted(FLUX_SCHEDULER_MAP))def test_denoise_real_flux_schedulers_update_dype_from_internal_sigma_schedule(monkeypatch, scheduler_name):monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)@@ -295,17 +241,20 @@ def test_denoise_real_flux_schedulers_update_dype_from_internal_sigma_schedule(mdef _run_with_scheduler(scheduler, timesteps: list[float], **kwargs):model = kwargs.pop("model", _ConstantFluxModel(0.25))img = kwargs.pop("img", torch.tensor([[[1.0], [-0.5]]], dtype=torch.float32))+ cfg_scale = kwargs.pop("cfg_scale", [1.0] * (len(timesteps) - 1))+ prompt = kwargs.pop("pos_regional_prompting_extension", _build_regional_prompting_extension(batch_size=1))+ negative_prompt = kwargs.pop("neg_regional_prompting_extension", None)callbacks = []result = denoise(model=model,img=img,img_ids=torch.zeros(1, img.shape[1], 3),- pos_regional_prompting_extension=_build_regional_prompting_extension(batch_size=1),- neg_regional_prompting_extension=None,+ pos_regional_prompting_extension=prompt,+ neg_regional_prompting_extension=negative_prompt,timesteps=timesteps,step_callback=callbacks.append,guidance=1.0,- cfg_scale=[1.0] * (len(timesteps) - 1),+ cfg_scale=cfg_scale,inpaint_extension=None,controlnet_extensions=[],pos_ip_adapter_extensions=[],@@ -355,6 +304,21 @@ def test_default_scheduler_matches_explicit_euler_and_clean_preview(monkeypatch,assert all(torch.allclose(callback.latents, expected_clean) for callback in callbacks)[email protected]("step_count", [4, 5])+def test_heun_progress_is_linear_across_completed_user_steps(monkeypatch, step_count):+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)+ schedule = torch.linspace(1.0, 0.0, step_count + 1).tolist()+ scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000)++ _, _, _, callbacks = _run_with_scheduler(scheduler, schedule)++ progress = [calc_percentage(callback) for callback in callbacks]+ assert [callback.step for callback in callbacks] == list(range(1, step_count + 1))+ assert [callback.order for callback in callbacks] == [1] * step_count+ assert progress == pytest.approx([step / step_count for step in range(1, step_count + 1)])+ assert progress[-1] == 1.0++def test_heun_uses_custom_schedule_and_completes_each_user_step(monkeypatch):monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)schedule = [1.0, 0.7, 0.35, 0.2]@@ -366,11 +330,11 @@ def test_heun_uses_custom_schedule_and_completes_each_user_step(monkeypatch):expected_timesteps = torch.tensor([1000.0, 700.0, 700.0, 350.0, 350.0])expected_sigmas = torch.tensor([1.0, 0.7, 0.7, 0.35, 0.35, 0.2])assert torch.allclose(result, expected, atol=1e-6, rtol=0)- assert torch.equal(scheduler.timesteps.cpu(), expected_timesteps)- assert torch.equal(scheduler.sigmas.cpu(), expected_sigmas)+ assert torch.allclose(scheduler.timesteps.cpu(), expected_timesteps, atol=1e-6, rtol=0)+ assert torch.allclose(scheduler.sigmas.cpu(), expected_sigmas, atol=1e-6, rtol=0)assert len(model.timesteps) == 2 * (len(schedule) - 1) - 1assert [callback.step for callback in callbacks] == [1, 2, 3]- assert [callback.order for callback in callbacks] == [2, 2, 1]+ assert [callback.order for callback in callbacks] == [1, 1, 1]def test_heun_partial_start_and_end_use_custom_sigmas(monkeypatch):@@ -381,11 +345,35 @@ def test_heun_partial_start_and_end_use_custom_sigmas(monkeypatch):result, img, model, callbacks = _run_with_scheduler(scheduler, schedule)assert torch.allclose(result, img + (0.2 - 0.7) * 0.25, atol=1e-6, rtol=0)- assert torch.equal(scheduler.timesteps.cpu(), torch.tensor([700.0, 450.0, 450.0]))- assert torch.equal(scheduler.sigmas.cpu(), torch.tensor([0.7, 0.45, 0.45, 0.2]))+ assert torch.allclose(scheduler.timesteps.cpu(), torch.tensor([700.0, 450.0, 450.0]), atol=1e-6, rtol=0)+ assert torch.allclose(scheduler.sigmas.cpu(), torch.tensor([0.7, 0.45, 0.45, 0.2]), atol=1e-6, rtol=0)assert len(model.timesteps) == 3assert [callback.step for callback in callbacks] == [1, 2]- assert [callback.order for callback in callbacks] == [2, 1]+ assert [callback.order for callback in callbacks] == [1, 1]+++def test_heun_custom_schedule_resets_an_interrupted_diffusers_scheduler():+ from invokeai.backend.flux.schedulers import set_heun_timesteps_from_sigmas++ scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000)+ set_heun_timesteps_from_sigmas(scheduler, [0.9, 0.6, 0.3], 0.1, "cpu")+ scheduler.step(torch.ones(1, 1, 1), scheduler.timesteps[0], torch.ones(1, 1, 1))++ assert scheduler.state_in_first_order is False+ assert scheduler.prev_derivative is not None+ assert scheduler.dt is not None+ assert scheduler.sample is not None+ assert scheduler.step_index == 1++ set_heun_timesteps_from_sigmas(scheduler, [0.8, 0.4], 0.2, "cpu")++ assert scheduler.state_in_first_order is True+ assert scheduler.prev_derivative is None+ assert scheduler.dt is None+ assert scheduler.sample is None+ assert scheduler.step_index is None+ assert scheduler._begin_index is None+ assert scheduler.num_inference_steps == 2def test_heun_preserves_cfg_and_inpainting_callback_behavior(monkeypatch):@@ -423,7 +411,7 @@ def test_heun_preserves_cfg_and_inpainting_callback_behavior(monkeypatch):assert torch.allclose(result, img + (schedule[-1] - schedule[0]) * guided_prediction)assert model.outputs == [1.0, -1.0] * 5assert [callback.step for callback in callbacks] == [1, 2, 3]- assert [callback.order for callback in callbacks] == [2, 2, 1]+ assert [callback.order for callback in callbacks] == [1, 1, 1]assert all(torch.allclose(callback.latents, img - guided_prediction) for callback in callbacks)assert extension.sigmas == pytest.approx([0.7, 0.7, 0.0, 0.35, 0.35, 0.0, 0.0, 0.0])@@ -448,7 +436,57 @@ def test_heun_keeps_second_order_correction_for_sample_dependent_predictions(monassert torch.allclose(result, expected, atol=1e-6, rtol=0)assert len(model.evaluations) == 2 * (len(schedule) - 1) - 1- assert [callback.order for callback in callbacks] == [2, 2, 1]+ assert [callback.order for callback in callbacks] == [1, 1, 1]+ callback_evaluations = [1, 3, 4]+ for callback, evaluation_index in zip(callbacks, callback_evaluations, strict=True):+ sigma, sample = model.evaluations[evaluation_index]+ prediction = 0.1 * sample + 0.2 * sigma+ assert torch.allclose(callback.latents, sample - sigma * prediction)+++def test_heun_uses_each_cfg_scale_for_both_interval_evaluations_and_matches_reference(monkeypatch):+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)+ schedule = [0.9, 0.6, 0.3, 0.1]+ cfg_scales = [2.0, 3.0, 4.0]+ scheduler = FlowMatchHeunDiscreteScheduler(num_train_timesteps=1000)+ model = _NonUniformCFGFluxModel()+ img = torch.tensor([[[1.0], [-0.5]]])+ prompt = _build_regional_prompting_extension(batch_size=1)+ negative_prompt = _build_regional_prompting_extension(batch_size=1)+ prompt.regional_text_conditioning.t5_embeddings.fill_(0.2)+ negative_prompt.regional_text_conditioning.t5_embeddings.fill_(-0.1)++ result, _, _, callbacks = _run_with_scheduler(+ scheduler,+ schedule,+ img=img,+ model=model,+ cfg_scale=cfg_scales,+ pos_regional_prompting_extension=prompt,+ neg_regional_prompting_extension=negative_prompt,+ )++ expected = img.clone()+ for index, sigma in enumerate(schedule[:-2]):+ sigma_next = schedule[index + 1]+ scale = cfg_scales[index]+ pos_first = 0.1 * expected + 0.2 * sigma+ neg_first = 0.1 * expected - 0.1 * sigma+ first_prediction = neg_first + scale * (pos_first - neg_first)+ euler_sample = expected + (sigma_next - sigma) * first_prediction+ pos_second = 0.1 * euler_sample + 0.2 * sigma_next+ neg_second = 0.1 * euler_sample - 0.1 * sigma_next+ second_prediction = neg_second + scale * (pos_second - neg_second)+ expected = expected + (sigma_next - sigma) * (first_prediction + second_prediction) / 2+ sigma = schedule[-2]+ scale = cfg_scales[-1]+ pos_final = 0.1 * expected + 0.2 * sigma+ neg_final = 0.1 * expected - 0.1 * sigma+ expected = expected + (schedule[-1] - sigma) * (neg_final + scale * (pos_final - neg_final))++ assert torch.allclose(result, expected, atol=1e-6, rtol=0)+ assert [call[0] for call in model.calls] == [0, 0, 1, 1, 2]+ assert [callback.step for callback in callbacks] == [1, 2, 3]def test_scheduler_preview_preserves_cfg_and_inpainting_callback(monkeypatch):@@ -501,9 +539,33 @@ def test_lcm_preview_uses_the_model_evaluation_sample_and_sigma(monkeypatch):assert model.timesteps == pytest.approx([float(timestep / scheduler.config.num_train_timesteps) for timestep in scheduler.timesteps])+ assert model.timesteps == pytest.approx([1.0, 0.001])+ assert not torch.allclose(scheduler.sigmas, torch.tensor([1.0, 0.5, 0.0]))assert torch.allclose(callbacks[0].latents, expected_preview)+def test_denoise_rejects_an_unrelated_scheduler_with_custom_sigmas_support(monkeypatch):+ class _UnrelatedScheduler:+ def __init__(self) -> None:+ self.config = SimpleNamespace(num_train_timesteps=1000)+ self.timesteps = torch.tensor([])+ self.sigmas = torch.tensor([])++ def set_timesteps(self, sigmas: list[float], device: torch.device) -> None:+ self.sigmas = torch.tensor([*sigmas, 0.0], device=device)+ self.timesteps = torch.tensor(sigmas, device=device) * 1000++ def step(self, model_output: torch.Tensor, timestep: torch.Tensor, sample: torch.Tensor) -> SimpleNamespace:+ del model_output, timestep+ return SimpleNamespace(prev_sample=sample)++ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)+ scheduler = _UnrelatedScheduler()++ with pytest.raises(TypeError, match="Unsupported FLUX scheduler"):+ _run_with_scheduler(scheduler, [1.0, 0.5, 0.0])++@pytest.mark.parametrize("schedule", [[], [0.4]])def test_default_scheduler_without_intervals_returns_input(schedule):result, img, model, callbacks = _run_with_scheduler(None, schedule)