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): seed LCM step noise for FLUX.1, FLUX.2 and Z-Image

GokayAIb6f4a8d16616
diff --git a/invokeai/app/invocations/flux/flux_denoise.py b/invokeai/app/invocations/flux/flux_denoise.py
index 5542aaba5a..82106a3a42 100644
--- a/invokeai/app/invocations/flux/flux_denoise.py
+++ b/invokeai/app/invocations/flux/flux_denoise.py
@@ -543,6 +543,10 @@ class FluxDenoiseInvocation(BaseInvocation):
img_cond_seq_ids=img_cond_seq_ids,
dype_extension=dype_extension,
scheduler=scheduler,
+ # LCM re-noises the sample on every step. Without an explicit generator that noise
+ # comes from the global RNG and the same seed gives a different image each run.
+ # XOR keeps the step noise decorrelated from the initial noise (as in ERNIE-Image).
+ generator=torch.Generator(device="cpu").manual_seed(self.seed ^ 0xFFFFFFFF),
)
x = unpack(x.float(), self.height, self.width)
diff --git a/invokeai/app/invocations/flux2/flux2_denoise.py b/invokeai/app/invocations/flux2/flux2_denoise.py
index 19e4fd4873..928d2e1d11 100644
--- a/invokeai/app/invocations/flux2/flux2_denoise.py
+++ b/invokeai/app/invocations/flux2/flux2_denoise.py
@@ -643,6 +643,10 @@ class Flux2DenoiseInvocation(BaseInvocation):
img_cond_seq=img_cond_seq,
img_cond_seq_ids=img_cond_seq_ids,
pos_joint_attention_kwargs=pos_joint_attention_kwargs,
+ # LCM re-noises the sample on every step. Without an explicit generator that noise
+ # comes from the global RNG and the same seed gives a different image each run.
+ # XOR keeps the step noise decorrelated from the initial noise (as in ERNIE-Image).
+ generator=torch.Generator(device="cpu").manual_seed(self.seed ^ 0xFFFFFFFF),
)
# Apply BN denormalization if BN stats are available
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index a440c3d6c8..f9a6cea6f7 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -713,6 +713,10 @@ class ZImageDenoiseInvocation(BaseInvocation):
# Use diffusers scheduler for stepping
# Use tqdm with total_steps (user-facing steps) not num_scheduler_steps (internal steps)
# This ensures progress bar shows 1/8, 2/8, etc. even when scheduler uses more internal steps
+ # LCM re-noises the sample on every step. Without an explicit generator that noise
+ # comes from the global RNG and the same seed gives a different image each run.
+ # XOR keeps the step noise decorrelated from the initial noise (as in ERNIE-Image).
+ step_generator = torch.Generator(device="cpu").manual_seed(self.seed ^ 0xFFFFFFFF)
pbar = tqdm(total=total_steps, desc=f"Denoising{TorchDevice.get_session_device_label()}")
for step_index in range(num_scheduler_steps):
sched_timestep = scheduler.timesteps[step_index]
@@ -787,7 +791,9 @@ class ZImageDenoiseInvocation(BaseInvocation):
noise_pred = noise_pred_cond
# Use scheduler.step() for the update
- step_output = scheduler.step(model_output=noise_pred, timestep=sched_timestep, sample=latents)
+ step_output = scheduler.step(
+ model_output=noise_pred, timestep=sched_timestep, sample=latents, generator=step_generator
+ )
latents = step_output.prev_sample
# Get sigma_prev for inpainting (next sigma value)
diff --git a/invokeai/backend/flux/denoise.py b/invokeai/backend/flux/denoise.py
index 49783bc1aa..db0f990ab6 100644
--- a/invokeai/backend/flux/denoise.py
+++ b/invokeai/backend/flux/denoise.py
@@ -44,6 +44,8 @@ def denoise(
dype_extension: DyPEExtension | None = None,
# Defaults to Diffusers Euler when omitted.
scheduler: SchedulerMixin | None = None,
+ # RNG for stochastic schedulers. FlowMatchLCMScheduler.step re-noises the sample every step.
+ generator: torch.Generator | None = None,
):
if len(timesteps) <= 1:
return img
@@ -217,8 +219,9 @@ def denoise(
) and user_step < total_steps
preview_img = img - t_curr * pred if should_emit_preview else None
- # Use scheduler.step() for the update
- step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img)
+ # Use scheduler.step() for the update. `generator` matters for LCM, which re-noises every
+ # step; Euler and Heun only consult it when `s_churn > 0`, which is 0 here.
+ step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img, generator=generator)
img = step_output.prev_sample
# Get t_prev for inpainting (next sigma value)
diff --git a/invokeai/backend/flux2/denoise.py b/invokeai/backend/flux2/denoise.py
index 4dbb99a5b1..a273d2cd77 100644
--- a/invokeai/backend/flux2/denoise.py
+++ b/invokeai/backend/flux2/denoise.py
@@ -44,6 +44,8 @@ def denoise(
# Optional joint_attention_kwargs (e.g. {"attention_mask": ...}) applied to positive forward
# passes only. Negative forwards always run unmasked.
pos_joint_attention_kwargs: dict[str, Any] | None = None,
+ # RNG for stochastic schedulers. FlowMatchLCMScheduler.step re-noises the sample every step.
+ generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Denoise latents using a FLUX.2 Klein transformer model.
@@ -185,8 +187,9 @@ def denoise(
neg_pred = neg_pred[:, :original_seq_len]
pred = neg_pred + step_cfg_scale * (pred - neg_pred)
- # Use scheduler.step() for the update
- step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img)
+ # Use scheduler.step() for the update. `generator` matters for LCM, which re-noises every
+ # step; Euler and Heun only consult it when `s_churn > 0`, which is 0 here.
+ step_output = scheduler.step(model_output=pred, timestep=timestep, sample=img, generator=generator)
img = step_output.prev_sample
# Get t_prev for inpainting (next sigma value)
diff --git a/tests/app/invocations/test_denoise_noise_inputs.py b/tests/app/invocations/test_denoise_noise_inputs.py
index 26cca59255..a292f7242d 100644
--- a/tests/app/invocations/test_denoise_noise_inputs.py
+++ b/tests/app/invocations/test_denoise_noise_inputs.py
@@ -766,7 +766,13 @@ def test_flux2_lcm_scheduler_setup_passes_mu():
def set_timesteps(self, num_inference_steps: int, device: str | torch.device, mu: float | None = None) -> None:
self.received_mu = mu
- def step(self, model_output: torch.Tensor, timestep: torch.Tensor, sample: torch.Tensor):
+ def step(
+ self,
+ model_output: torch.Tensor,
+ timestep: torch.Tensor,
+ sample: torch.Tensor,
+ generator: torch.Generator | None = None,
+ ):
return SimpleNamespace(prev_sample=sample)
class DummyModel(torch.nn.Module):
@@ -801,6 +807,40 @@ def test_flux2_lcm_scheduler_setup_passes_mu():
assert scheduler.received_mu == pytest.approx(0.42)
[email protected](FLUX_SCHEDULER_MAP.get("lcm") is None, reason="FlowMatchLCMScheduler not available")
+def test_flux2_lcm_step_noise_follows_the_generator():
+ """LCM re-noises the sample on every step, so FLUX.2 must draw that noise from the seeded
+ generator instead of the global RNG."""
+ from invokeai.backend.flux2.denoise import denoise
+
+ class DummyModel(torch.nn.Module):
+ def forward(self, hidden_states: torch.Tensor, **kwargs: object):
+ del kwargs
+ return (0.1 * hidden_states,)
+
+ img = torch.randn(1, 4, 8, generator=torch.Generator().manual_seed(7))
+
+ def run(seed: int) -> torch.Tensor:
+ # Advance the global RNG between runs, like a long-lived server process does.
+ torch.rand(64)
+ return denoise(
+ model=DummyModel(),
+ img=img.clone(),
+ img_ids=torch.zeros(1, 4, 4, dtype=torch.long),
+ txt=torch.zeros(1, 4, 8),
+ txt_ids=torch.zeros(1, 4, 4, dtype=torch.long),
+ timesteps=[1.0, 0.75, 0.5, 0.25, 0.0],
+ step_callback=lambda _: None,
+ guidance=1.0,
+ cfg_scale=[1.0] * 4,
+ scheduler=FLUX_SCHEDULER_MAP["lcm"](num_train_timesteps=1000),
+ generator=torch.Generator().manual_seed(seed),
+ )
+
+ assert torch.equal(run(1234), run(1234))
+ assert not torch.equal(run(1), run(2))
+
+
@pytest.mark.parametrize(
"scheduler_name",
[
diff --git a/tests/backend/flux/test_denoise.py b/tests/backend/flux/test_denoise.py
index c699ee610c..5cccb5fbd4 100644
--- a/tests/backend/flux/test_denoise.py
+++ b/tests/backend/flux/test_denoise.py
@@ -544,6 +544,25 @@ def test_lcm_preview_uses_the_model_evaluation_sample_and_sigma(monkeypatch):
assert torch.allclose(callbacks[0].latents, expected_preview)
[email protected](not _HAS_LCM, reason="FlowMatchLCMScheduler not available in this Diffusers version")
+def test_lcm_step_noise_follows_the_generator(monkeypatch):
+ """LCM re-noises the sample on every step. With a seeded generator the result must not depend
+ on the global RNG, otherwise the same seed gives a different image on each run."""
+ monkeypatch.setattr("invokeai.backend.flux.denoise.tqdm", _fake_tqdm)
+
+ def run(seed: int) -> torch.Tensor:
+ # Advance the global RNG between runs, like a long-lived server process does.
+ torch.rand(64)
+ scheduler = FLUX_SCHEDULER_MAP["lcm"](num_train_timesteps=1000)
+ result, _, _, _ = _run_with_scheduler(
+ scheduler, [1.0, 0.75, 0.5, 0.25, 0.0], generator=torch.Generator().manual_seed(seed)
+ )
+ return result
+
+ assert torch.equal(run(1234), run(1234))
+ assert not torch.equal(run(1), run(2))
+
+
def test_denoise_rejects_an_unrelated_scheduler_with_custom_sigmas_support(monkeypatch):
class _UnrelatedScheduler:
def __init__(self) -> None: