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(flux2): img2img posterization - noise scaling and sigma schedule (#9556)
Alexander Eichhorn02709b21ee69
diff --git a/invokeai/app/invocations/flux2_denoise.py b/invokeai/app/invocations/flux2_denoise.pyindex 33725938a4..2cdb0444ff 100644--- a/invokeai/app/invocations/flux2_denoise.py+++ b/invokeai/app/invocations/flux2_denoise.py@@ -31,11 +31,14 @@ from invokeai.backend.flux2.denoise import denoisefrom invokeai.backend.flux2.extensions.regional_prompting_extension import Flux2RegionalPromptingExtensionfrom invokeai.backend.flux2.ref_image_extension import Flux2RefImageExtensionfrom invokeai.backend.flux2.sampling_utils import (+ FLUX2_TXT2IMG_SCHEDULER_KWARGS,compute_empirical_mu,generate_img_ids_flux2,get_noise_flux2,get_schedule_flux2,pack_flux2,+ redensify_schedule_flux2,+ time_shift_flux2,unpack_flux2,)from invokeai.backend.flux2.text_conditioning import Flux2TextConditioning@@ -252,6 +255,46 @@ class Flux2DenoiseInvocation(BaseInvocation):bn_std = bn_std.to(x.device, x.dtype)return x * bn_std + bn_mean+ def _prepare_normalized_start_latents(+ self,+ init_latents_packed: torch.Tensor,+ noise_packed: Optional[torch.Tensor],+ t_0: float,+ bn_mean: Optional[torch.Tensor],+ bn_std: Optional[torch.Tensor],+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ """Build the img2img/inpainting start latents in the transformer's BN-normalized space.++ Only the init latents are normalized. The noise must NOT be: it is already N(0, 1),+ exactly the distribution the transformer expects in normalized space. The rectified-flow+ preblend is therefore computed *from* the normalized operands rather than by normalizing+ the raw mixture -- normalizing the mixture would divide its noise term by bn_std (~1.77 for+ the FLUX.2 VAE) as well, so the sample would carry only ~57% of the noise implied by the+ timestep it is handed to the transformer with. The model then over-denoises and flattens+ fine detail into posterized patches, progressively worse at higher denoise strengths+ (see #8964).++ Args:+ init_latents_packed: Packed, un-normalized init latents of shape (B, seq, 128).+ noise_packed: Packed N(0, 1) noise of shape (B, seq, 128). Required if add_noise.+ t_0: First timestep of the clipped schedule.+ bn_mean: BN running mean of shape (128,), or None if the VAE exposes no BN stats.+ bn_std: BN running std of shape (128,), or None if the VAE exposes no BN stats.++ Returns:+ Tuple of (start latents, normalized init latents), both of shape (B, seq, 128).+ """+ if bn_mean is not None and bn_std is not None:+ init_latents_packed = self._bn_normalize(init_latents_packed, bn_mean, bn_std)++ if self.add_noise:+ assert noise_packed is not None+ x = t_0 * noise_packed + (1.0 - t_0) * init_latents_packed+ else:+ x = init_latents_packed++ return x, init_latents_packed+@torch.no_grad()def invoke(self, context: InvocationContext) -> LatentsOutput:latents = self._run_diffusion(context)@@ -342,9 +385,35 @@ class Flux2DenoiseInvocation(BaseInvocation):# Compute mu for dynamic schedule shifting (used by FlowMatchEulerDiscreteScheduler)mu = compute_empirical_mu(image_seq_len=image_seq_len, num_steps=self.num_steps)+ # img2img and inpainting step this schedule manually (see the scheduler setup below), while+ # txt2img hands it to the scheduler, which applies the exponential shift from mu itself. Apply+ # the same shift here so both paths follow one schedule, and apply it before clipping so the+ # clip selects from the schedule the model is actually run on. The clip works by sigma value,+ # not by step count, so shifting first does not change what a given denoising_start means --+ # it only changes how many steps fall below that sigma.+ #+ # Keyed on the same condition that decides whether a scheduler gets built below. Manual Euler+ # also runs when the requested scheduler is unavailable (e.g. "lcm" when FlowMatchLCMScheduler+ # cannot be imported); keying on denoise_mask/denoising_start alone would leave that run on the+ # unshifted linear schedule -- the one this fix exists to avoid.+ uses_manual_euler = (+ self.denoise_mask is not None or self.denoising_start > 1e-5 or self.scheduler not in FLUX_SCHEDULER_MAP+ )+ if uses_manual_euler:+ timesteps = time_shift_flux2(timesteps, mu)+# Clip the timesteps schedule based on denoising_start and denoising_endtimesteps = clip_timestep_schedule_fractional(timesteps, self.denoising_start, self.denoising_end)+ # Clipping keeps only the sigmas that fall inside the denoising window, so a narrow window+ # runs fewer steps than were requested. Under the shift that is severe: at 4 steps and+ # strength 0.2 only two steps survive, and the last has to cover sigma 0.715 -> 0 in one+ # Euler jump, which wipes out the source image's fine detail. Re-space the window so the+ # requested number of steps is actually taken. The endpoints are preserved exactly, so the+ # preblend below and the denoising range itself are unaffected.+ if uses_manual_euler:+ timesteps = redensify_schedule_flux2(timesteps, self.num_steps, mu)+# Prepare input latent imageif init_latents is not None:if self.add_noise:@@ -367,10 +436,6 @@ class Flux2DenoiseInvocation(BaseInvocation):assert noise is not Nonex = noise- # If len(timesteps) == 1, then short-circuit- if len(timesteps) <= 1:- return x-# Generate image position IDs (FLUX.2 uses 4D coordinates)# Position IDs use int64 dtype like diffusersimg_ids = generate_img_ids_flux2(h=latent_h, w=latent_w, batch_size=b, device=device)@@ -384,34 +449,32 @@ class Flux2DenoiseInvocation(BaseInvocation):noise_packed = pack_flux2(noise) if noise is not None else Nonex = pack_flux2(x)- # BN normalization for img2img/inpainting:- # - The init_latents from VAE encode are NOT BN-normalized- # - The transformer operates in BN-normalized space- # - We must normalize x, init_latents, AND noise for InpaintExtension- # - Output MUST be denormalized after denoising before VAE decode- #- # This ensures that:- # 1. x starts in the correct normalized space for the transformer- # 2. When InpaintExtension merges intermediate_latents with noised_init_latents,- # both are in the same scale/space (noise and init_latents must be in same space- # for the linear interpolation: noised = noise * t + init * (1-t))- if bn_mean is not None and bn_std is not None:- if init_latents_packed is not None:- init_latents_packed = self._bn_normalize(init_latents_packed, bn_mean, bn_std)- # Also normalize noise for InpaintExtension - it's used to compute- # noised_init_latents = noise * t + init_latents * (1-t)- # Both operands must be in the same normalized space- if noise_packed is not None:- noise_packed = self._bn_normalize(noise_packed, bn_mean, bn_std)- # For img2img/inpainting, x is computed from init_latents and must also be normalized- # For txt2img, x is pure noise (already N(0,1)) - normalizing it would be incorrect- # We detect img2img by checking if init_latents was provided- if init_latents is not None:- x = self._bn_normalize(x, bn_mean, bn_std)+ # The init latents from VAE encode are NOT BN-normalized, but the transformer operates in+ # BN-normalized space, so the img2img/inpainting start latents are rebuilt there. The noise+ # is left untouched -- see _prepare_normalized_start_latents. pack_flux2 is a pure rearrange,+ # so blending before or after packing is equivalent. Output is denormalized again below,+ # after denoising, before it goes to the VAE.+ if init_latents_packed is not None:+ x, init_latents_packed = self._prepare_normalized_start_latents(+ init_latents_packed=init_latents_packed,+ noise_packed=noise_packed,+ t_0=timesteps[0],+ bn_mean=bn_mean,+ bn_std=bn_std,+ )# Verify packed dimensionsassert packed_h * packed_w == x.shape[1]+ # Nothing left to step (denoising_start == denoising_end, say). Hand the start latents back+ # through the same denormalization the full path uses. Returning the raw-space blend here+ # instead would leave the noise term unscaled, so a downstream FLUX.2 denoise that normalizes+ # this output would divide it by bn_std a second time.+ if len(timesteps) <= 1:+ if bn_mean is not None and bn_std is not None:+ x = self._bn_denormalize(x, bn_mean, bn_std)+ return unpack_flux2(x.float(), self.height, self.width)+# Prepare inpaint extensioninpaint_extension: Optional[RectifiedFlowInpaintExtension] = Noneif inpaint_mask_packed is not None:@@ -427,9 +490,6 @@ class Flux2DenoiseInvocation(BaseInvocation):num_steps = len(timesteps) - 1cfg_scale_list = [self.cfg_scale] * num_steps- # Check if we're doing inpainting (have a mask or a clipped schedule)- is_inpainting = self.denoise_mask is not None or self.denoising_start > 1e-5-# Create scheduler with FLUX.2 Klein configuration# For inpainting/img2img, use manual Euler stepping to preserve the exact# clipped timestep schedule used for the initial latent/noise preblend.@@ -439,7 +499,7 @@ class Flux2DenoiseInvocation(BaseInvocation):# change the first effective timestep/sigma and break parity with the# preblend computed above.scheduler = None- if self.scheduler in FLUX_SCHEDULER_MAP and not is_inpainting:+ if not uses_manual_euler:# Only use scheduler for txt2img - use manual Euler for inpainting to preserve exact timestepsscheduler_class = FLUX_SCHEDULER_MAP[self.scheduler]# FlowMatchHeunDiscreteScheduler only supports num_train_timesteps and shift parameters@@ -450,16 +510,7 @@ class Flux2DenoiseInvocation(BaseInvocation):shift=3.0,)else:- scheduler = scheduler_class(- num_train_timesteps=1000,- shift=3.0,- use_dynamic_shifting=True,- base_shift=0.5,- max_shift=1.15,- base_image_seq_len=256,- max_image_seq_len=4096,- time_shift_type="exponential",- )+ scheduler = scheduler_class(**FLUX2_TXT2IMG_SCHEDULER_KWARGS)# Prepare reference image extension for FLUX.2 Klein built-in editingref_image_extension = Nonediff --git a/invokeai/backend/flux2/sampling_utils.py b/invokeai/backend/flux2/sampling_utils.pyindex 3981e91275..98d69cd04d 100644--- a/invokeai/backend/flux2/sampling_utils.py+++ b/invokeai/backend/flux2/sampling_utils.py@@ -107,6 +107,21 @@ def unpack_flux2(x: torch.Tensor, height: int, width: int) -> torch.Tensor:)+# Config for the scheduler the FLUX.2 txt2img path builds. Shared with the schedule-shift test so the+# manual shift used by img2img/inpainting is always checked against the scheduler the node actually+# uses, rather than against a copy that can drift out of sync.+FLUX2_TXT2IMG_SCHEDULER_KWARGS = {+ "num_train_timesteps": 1000,+ "shift": 3.0,+ "use_dynamic_shifting": True,+ "base_shift": 0.5,+ "max_shift": 1.15,+ "base_image_seq_len": 256,+ "max_image_seq_len": 4096,+ "time_shift_type": "exponential",+}++def compute_empirical_mu(image_seq_len: int, num_steps: int) -> float:"""Compute mu for FLUX.2 schedule shifting.@@ -162,6 +177,104 @@ def get_schedule_flux2(return sigmas_list+def time_shift_flux2(sigmas: list[float], mu: float) -> list[float]:+ """Apply the exponential schedule shift that the txt2img scheduler applies internally.++ ``get_schedule_flux2()`` returns an unshifted linear schedule because the+ FlowMatchEulerDiscreteScheduler used for txt2img shifts it itself from ``mu``. Code paths that+ step the schedule manually (img2img, inpainting) must apply the shift themselves, otherwise they+ run the model on a completely different sigma trajectory than txt2img does: with 9 steps the+ shifted schedule bottoms out at sigma 0.485, the linear one at 0.111. A distilled model such as+ FLUX.2 Klein is never trained at the low end of the linear schedule and leaves a grainy residue+ there.++ Mirrors diffusers' ``FlowMatchEulerDiscreteScheduler._time_shift_exponential`` with an exponent+ of 1.0, which is how the scheduler invokes it::++ sigma' = exp(mu) / (exp(mu) + (1 / sigma - 1))++ Args:+ sigmas: Unshifted sigma schedule, descending from 1.0 to 0.0.+ mu: Shift parameter, as returned by ``compute_empirical_mu()``.++ Returns:+ The shifted schedule. The 1.0 and 0.0 endpoints are fixed points of the transform and are+ passed through directly to avoid a division by zero.+ """+ exp_mu = math.exp(mu)+ return [+ 1.0 if sigma >= 1.0 else 0.0 if sigma <= 0.0 else exp_mu / (exp_mu + (1.0 / sigma - 1.0)) for sigma in sigmas+ ]+++def unshift_flux2(sigmas: list[float], mu: float) -> list[float]:+ """Invert :func:`time_shift_flux2`.++ Solving ``sigma' = exp(mu) / (exp(mu) + (1 / sigma - 1))`` for ``sigma`` gives::++ sigma = 1 / (exp(mu) * (1 / sigma' - 1) + 1)++ Args:+ sigmas: Shifted sigmas, descending from 1.0 to 0.0.+ mu: The same shift parameter that produced them.++ Returns:+ The unshifted sigmas. As in the forward transform, 1.0 and 0.0 are fixed points and are+ passed through directly to avoid a division by zero.+ """+ exp_mu = math.exp(mu)+ return [+ 1.0 if sigma >= 1.0 else 0.0 if sigma <= 0.0 else 1.0 / (exp_mu * (1.0 / sigma - 1.0) + 1.0) for sigma in sigmas+ ]+++def redensify_schedule_flux2(timesteps: list[float], num_steps: int, mu: float) -> list[float]:+ """Re-space a clipped FLUX.2 schedule so it still takes ``num_steps`` steps.++ Clipping a schedule to a denoising window keeps only the sigmas that happen to fall inside it, so+ img2img at low strength runs far fewer steps than were requested. The shift makes that much worse+ than it is on the unshifted schedule, because it pushes sigmas up and leaves the low end sparse:+ at 4 steps and strength 0.2 the clipped window holds two steps, the last of which has to cover+ 0.715 -> 0 in a single Euler jump. The model reconstructs the whole image from that one jump and+ the fine detail of the source image -- skin texture, pores, film grain -- does not survive it.++ Resampling the window to the requested number of steps fixes that: the endpoints are held fixed+ (so the img2img preblend at ``timesteps[0]`` is unaffected) and the interior is re-spaced. The+ spacing is done in unshifted space and shifted back, so the result is the same curve the full+ schedule follows through this window, just sampled more finely.++ The schedule is only ever made denser, never sparser: if the clipped window already holds+ ``num_steps`` steps or more -- which is the case for txt2img, and for any window wide enough not+ to lose steps -- it is returned unchanged.++ Args:+ timesteps: The clipped, shifted schedule, descending.+ num_steps: The number of steps that was requested.+ mu: The shift parameter the schedule was shifted with.++ Returns:+ A schedule over the same sigma range with ``num_steps`` steps, or ``timesteps`` unchanged.+ """+ if num_steps < 1 or len(timesteps) < 2 or len(timesteps) - 1 >= num_steps:+ return timesteps++ start, end = unshift_flux2([timesteps[0], timesteps[-1]], mu)+ if start <= end:+ # Degenerate window: nothing to space out.+ return timesteps++ unshifted = [start + (end - start) * (i / num_steps) for i in range(num_steps + 1)]+ respaced = time_shift_flux2(unshifted, mu)++ # Pin the endpoints to the values that went in. Shifting back and forth is exact in theory but+ # not in floating point, and both endpoints are load-bearing: timesteps[0] is the sigma the+ # img2img start latents are blended at, and timesteps[-1] has to be exactly the end of the+ # requested denoising range.+ respaced[0] = timesteps[0]+ respaced[-1] = timesteps[-1]+ return respaced++def generate_img_ids_flux2(h: int, w: int, batch_size: int, device: torch.device) -> torch.Tensor:"""Generate tensor of image position ids for FLUX.2 with RoPE scaling.diff --git a/tests/app/invocations/test_flux2_denoise_img2img_normalization.py b/tests/app/invocations/test_flux2_denoise_img2img_normalization.pynew file mode 100644index 0000000000..70fc3006d6--- /dev/null+++ b/tests/app/invocations/test_flux2_denoise_img2img_normalization.py@@ -0,0 +1,124 @@+"""Regression tests for the FLUX.2 img2img/inpainting latent normalization (see #8964).++The FLUX.2 transformer operates on BN-normalized latents, while the VAE encode node emits raw+latents. The img2img preblend used to be computed in raw space and normalized afterwards, which+divided the noise term by bn_std (~1.77 for the FLUX.2 VAE) as well. The start latents then carried+only ~57% of the noise implied by their timestep, the model over-denoised, and fine detail collapsed+into posterized patches -- progressively worse the higher the denoise strength.+"""++import pytest+import torch++from invokeai.app.invocations.flux2_denoise import Flux2DenoiseInvocation++# Measured on the BFL FLUX.2 VAE (bn.running_mean / bn.running_var): mean ~0, var ~3.13.+BN_STD_VALUE = 1.7676+PACKED_CHANNELS = 128+++def _bn_stats() -> tuple[torch.Tensor, torch.Tensor]:+ bn_mean = torch.full((PACKED_CHANNELS,), 0.05)+ bn_std = torch.full((PACKED_CHANNELS,), BN_STD_VALUE)+ return bn_mean, bn_std+++def _packed(seed: int) -> torch.Tensor:+ generator = torch.Generator().manual_seed(seed)+ return torch.randn(1, 64, PACKED_CHANNELS, generator=generator)++[email protected]("t_0", [0.2, 0.5, 0.85, 1.0])+def test_noise_keeps_unit_scale_in_normalized_start_latents(t_0: float) -> None:+ """The noise term must survive the preblend at full N(0, 1) scale, for every denoise strength."""+ bn_mean, bn_std = _bn_stats()+ init_latents = _packed(1)+ noise = _packed(2)+ invocation = Flux2DenoiseInvocation.model_construct(add_noise=True)++ x, normalized_init = invocation._prepare_normalized_start_latents(+ init_latents_packed=init_latents,+ noise_packed=noise,+ t_0=t_0,+ bn_mean=bn_mean,+ bn_std=bn_std,+ )++ # x == t_0 * noise + (1 - t_0) * normalize(init), so peeling off the init term must recover the+ # noise unscaled -- not noise / bn_std, which is what normalizing the raw mixture produced.+ recovered_noise = (x - (1.0 - t_0) * normalized_init) / t_0+ assert torch.allclose(recovered_noise, noise, atol=1e-5)+++def test_start_latents_differ_from_normalizing_the_raw_mixture() -> None:+ """Guard against a regression back to normalizing the blended tensor as a whole."""+ bn_mean, bn_std = _bn_stats()+ init_latents = _packed(3)+ noise = _packed(4)+ t_0 = 0.6+ invocation = Flux2DenoiseInvocation.model_construct(add_noise=True)++ x, _ = invocation._prepare_normalized_start_latents(+ init_latents_packed=init_latents,+ noise_packed=noise,+ t_0=t_0,+ bn_mean=bn_mean,+ bn_std=bn_std,+ )++ buggy = invocation._bn_normalize(t_0 * noise + (1.0 - t_0) * init_latents, bn_mean, bn_std)+ # The buggy variant attenuates the noise term by 1 / bn_std.+ assert not torch.allclose(x, buggy, atol=1e-3)+ assert torch.allclose(x - buggy, t_0 * (noise - (noise - bn_mean) / bn_std), atol=1e-5)+++def test_init_latents_are_normalized() -> None:+ bn_mean, bn_std = _bn_stats()+ init_latents = _packed(5)+ invocation = Flux2DenoiseInvocation.model_construct(add_noise=True)++ _, normalized_init = invocation._prepare_normalized_start_latents(+ init_latents_packed=init_latents,+ noise_packed=_packed(6),+ t_0=0.4,+ bn_mean=bn_mean,+ bn_std=bn_std,+ )++ assert torch.allclose(normalized_init, (init_latents - bn_mean) / bn_std, atol=1e-6)+++def test_without_add_noise_start_latents_are_the_normalized_init_latents() -> None:+ bn_mean, bn_std = _bn_stats()+ init_latents = _packed(7)+ invocation = Flux2DenoiseInvocation.model_construct(add_noise=False)++ x, normalized_init = invocation._prepare_normalized_start_latents(+ init_latents_packed=init_latents,+ noise_packed=_packed(8),+ t_0=0.4,+ bn_mean=bn_mean,+ bn_std=bn_std,+ )++ assert torch.allclose(x, normalized_init, atol=1e-6)+ assert torch.allclose(x, (init_latents - bn_mean) / bn_std, atol=1e-6)+++def test_without_bn_stats_the_raw_preblend_is_preserved() -> None:+ """VAE formats that expose no BN stats keep the previous raw-space behaviour."""+ init_latents = _packed(9)+ noise = _packed(10)+ t_0 = 0.3+ invocation = Flux2DenoiseInvocation.model_construct(add_noise=True)++ x, normalized_init = invocation._prepare_normalized_start_latents(+ init_latents_packed=init_latents,+ noise_packed=noise,+ t_0=t_0,+ bn_mean=None,+ bn_std=None,+ )++ assert torch.allclose(normalized_init, init_latents, atol=1e-6)+ assert torch.allclose(x, t_0 * noise + (1.0 - t_0) * init_latents, atol=1e-6)diff --git a/tests/app/invocations/test_flux2_denoise_wiring.py b/tests/app/invocations/test_flux2_denoise_wiring.pynew file mode 100644index 0000000000..3d82eeb1dc--- /dev/null+++ b/tests/app/invocations/test_flux2_denoise_wiring.py@@ -0,0 +1,306 @@+"""Regression tests for how ``Flux2DenoiseInvocation._run_diffusion`` wires the schedule and the+start latents together.++``_prepare_normalized_start_latents`` and ``time_shift_flux2`` are covered on their own elsewhere;+what those tests cannot see is the code that *calls* them. Each of these one-line breakages used to+pass the whole suite:++* dropping the ``time_shift_flux2`` call, so img2img runs the unshifted linear schedule again;+* shifting unconditionally, which shifts txt2img twice (the scheduler already applies ``mu``);+* re-normalizing ``noise_packed`` before the inpaint extension is built, bringing back the half of+ the noise-scaling bug that lives in the unmasked region;+* handing ``_prepare_normalized_start_latents`` a ``t_0`` from the unclipped schedule;+* skipping the respacing of the clipped schedule, so img2img at low strength runs one or two steps+ instead of the requested number and the final Euler jump flattens the source image's detail.++These tests drive the real ``_run_diffusion`` up to the transformer load and assert on what the+wiring actually produced.+"""++from unittest.mock import MagicMock, patch++import pytest+import torch++import invokeai.app.invocations.flux2_denoise as flux2_denoise+from invokeai.app.invocations.flux2_denoise import Flux2DenoiseInvocation+from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional+from invokeai.backend.flux2.sampling_utils import (+ compute_empirical_mu,+ get_schedule_flux2,+ pack_flux2,+ redensify_schedule_flux2,+ time_shift_flux2,+ unpack_flux2,+)+from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension++# Measured on the BFL FLUX.2 VAE; a value far enough from 1.0 that a stray normalization is obvious.+BN_STD_VALUE = 1.7676+BN_MEAN_VALUE = 0.05+PACKED_CHANNELS = 128++# 128px -> a 16x16 latent -> an 8x8 packed grid -> 64 image tokens.+SIZE = 128+LATENT = SIZE // 8+IMAGE_SEQ_LEN = (LATENT // 2) ** 2+NUM_STEPS = 4+++class _StopBeforeLoad(Exception):+ """Raised in place of entering the transformer's device context, to end _run_diffusion early."""+++def _bn_stats() -> tuple[torch.Tensor, torch.Tensor]:+ return (+ torch.full((PACKED_CHANNELS,), BN_MEAN_VALUE),+ torch.full((PACKED_CHANNELS,), BN_STD_VALUE),+ )+++def _latents(seed: int) -> torch.Tensor:+ # _run_diffusion pins inference_dtype to bfloat16, so feed it bf16 and compute the expectations in+ # bf16 too -- an fp32 expectation differs from the node's result by ~1e-3 for precision reasons alone.+ return torch.randn(1, 32, LATENT, LATENT, generator=torch.Generator().manual_seed(seed)).to(torch.bfloat16)+++def _drive(+ *,+ denoising_start: float = 0.0,+ denoising_end: float = 1.0,+ with_init: bool = True,+ with_mask: bool = False,+ scheduler: str = "euler",+ bn: bool = True,+):+ """Run `_run_diffusion` far enough to build the schedule, start latents and inpaint extension."""+ from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType, ModelFormat, ModelType+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (+ ConditioningFieldData,+ FLUXConditioningInfo,+ )++ noise = _latents(7)+ init_latents = _latents(8)+ mask = torch.full_like(noise, 0.5)+ captured: dict = {"shift_calls": [], "start_kwargs": [], "inpaint": [], "redensify_calls": []}++ transformer_info = MagicMock()+ transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)++ context = MagicMock()+ context.models.load.return_value = transformer_info+ context.models.get_config.return_value = MagicMock(+ base=BaseModelType.Flux2,+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+ variant=Flux2VariantType("klein_9b"),+ )+ context.conditioning.load.return_value = ConditioningFieldData(+ conditionings=[FLUXConditioningInfo(clip_embeds=torch.zeros(1, 768), t5_embeds=torch.zeros(1, 64, 12288))]+ )+ context.tensors.load.return_value = init_latents++ invocation = Flux2DenoiseInvocation.model_construct(+ latents=MagicMock(latents_name="init") if with_init else None,+ noise=None,+ denoise_mask=MagicMock(mask_name="mask") if with_mask else None,+ denoising_start=denoising_start,+ denoising_end=denoising_end,+ add_noise=True,+ transformer=MagicMock(transformer=MagicMock(), loras=[]),+ positive_text_conditioning=MagicMock(conditioning_name="pos", mask=None),+ negative_text_conditioning=None,+ guidance=4.0,+ cfg_scale=1.0,+ width=SIZE,+ height=SIZE,+ num_steps=NUM_STEPS,+ scheduler=scheduler,+ seed=0,+ vae=MagicMock(vae=MagicMock()),+ kontext_conditioning=None,+ )++ real_shift = flux2_denoise.time_shift_flux2++ def recording_shift(timesteps, mu):+ captured["shift_calls"].append((list(timesteps), mu))+ return real_shift(timesteps, mu)++ real_redensify = flux2_denoise.redensify_schedule_flux2++ def recording_redensify(timesteps, num_steps, mu):+ result = real_redensify(timesteps, num_steps, mu)+ captured["redensify_calls"].append({"clipped": list(timesteps), "num_steps": num_steps, "result": result})+ return result++ real_prepare = Flux2DenoiseInvocation._prepare_normalized_start_latents++ def recording_prepare(self, **kwargs):+ captured["start_kwargs"].append(kwargs)+ return real_prepare(self, **kwargs)++ class _RecordingInpaintExtension(RectifiedFlowInpaintExtension):+ def __init__(self, *, init_latents, inpaint_mask, noise):+ captured["inpaint"].append({"init_latents": init_latents, "inpaint_mask": inpaint_mask, "noise": noise})+ super().__init__(init_latents, inpaint_mask, noise)++ with (+ patch.object(Flux2DenoiseInvocation, "_get_bn_stats", return_value=_bn_stats() if bn else None),+ patch.object(Flux2DenoiseInvocation, "_prepare_noise_tensor", return_value=noise),+ patch.object(Flux2DenoiseInvocation, "_prep_inpaint_mask", return_value=mask if with_mask else None),+ patch.object(Flux2DenoiseInvocation, "_prepare_normalized_start_latents", recording_prepare),+ patch("invokeai.backend.util.devices.TorchDevice.choose_torch_device", return_value=torch.device("cpu")),+ patch.object(flux2_denoise, "time_shift_flux2", recording_shift),+ patch.object(flux2_denoise, "redensify_schedule_flux2", recording_redensify),+ patch.object(flux2_denoise, "RectifiedFlowInpaintExtension", _RecordingInpaintExtension),+ ):+ try:+ result = invocation._run_diffusion(context)+ except _StopBeforeLoad:+ result = None++ captured["result"] = result+ captured["noise"] = noise+ captured["init_latents"] = init_latents+ captured["reached_transformer"] = transformer_info.model_on_device.called+ return captured+++def _expected_schedule(denoising_start: float, denoising_end: float = 1.0, shifted: bool = True) -> list[float]:+ linear = get_schedule_flux2(num_steps=NUM_STEPS, image_seq_len=IMAGE_SEQ_LEN)+ mu = compute_empirical_mu(image_seq_len=IMAGE_SEQ_LEN, num_steps=NUM_STEPS)+ timesteps = time_shift_flux2(linear, mu) if shifted else linear+ clipped = clip_timestep_schedule_fractional(timesteps, denoising_start, denoising_end)+ return redensify_schedule_flux2(clipped, NUM_STEPS, mu) if shifted else clipped+++def test_txt2img_does_not_shift_the_schedule() -> None:+ """The txt2img scheduler applies mu itself; shifting here too would shift twice."""+ captured = _drive(denoising_start=0.0, with_init=False)++ assert captured["shift_calls"] == []+ assert captured["reached_transformer"]++[email protected](("denoising_start", "with_mask"), [(0.5, False), (0.0, True)])+def test_manual_euler_paths_shift_the_schedule_once(denoising_start: float, with_mask: bool) -> None:+ """img2img and inpainting step the schedule themselves, so they must apply the shift."""+ captured = _drive(denoising_start=denoising_start, with_mask=with_mask)++ assert len(captured["shift_calls"]) == 1+ shifted_timesteps, mu = captured["shift_calls"][0]+ assert mu == pytest.approx(compute_empirical_mu(image_seq_len=IMAGE_SEQ_LEN, num_steps=NUM_STEPS))+ # Shifted before clipping, so the call still sees the full linear schedule.+ assert shifted_timesteps == pytest.approx(get_schedule_flux2(num_steps=NUM_STEPS, image_seq_len=IMAGE_SEQ_LEN))+++def test_a_scheduler_that_falls_back_to_manual_euler_still_shifts() -> None:+ """Manual Euler also runs when the requested scheduler is unavailable (e.g. lcm without LCM support).++ Keying the shift on denoise_mask/denoising_start alone left that path on the unshifted schedule.+ """+ captured = _drive(denoising_start=0.0, with_init=False, scheduler="not_a_real_scheduler")++ assert len(captured["shift_calls"]) == 1+++def test_start_latents_use_the_first_sigma_of_the_clipped_schedule() -> None:+ """A t_0 taken from the unclipped schedule would noise the init latents to the wrong level."""+ captured = _drive(denoising_start=0.5)++ assert len(captured["start_kwargs"]) == 1+ expected = _expected_schedule(denoising_start=0.5)+ assert captured["start_kwargs"][0]["t_0"] == pytest.approx(expected[0])+ # Sanity: the clip actually moved t_0, so the assertion above can fail.+ assert expected[0] != pytest.approx(1.0)+++def test_the_inpaint_extension_gets_unit_scale_noise_and_normalized_init() -> None:+ """The extension mixes noise into the unmasked region, so its noise must match the timestep.++ Normalizing it (again) here would divide it by bn_std and reintroduce the bug for the region+ outside the mask.+ """+ captured = _drive(denoising_start=0.0, with_mask=True)++ assert len(captured["inpaint"]) == 1+ recorded = captured["inpaint"][0]+ expected_noise = pack_flux2(captured["noise"])+ assert torch.equal(recorded["noise"], expected_noise)++ bn_mean, bn_std = (t.to(torch.bfloat16) for t in _bn_stats())+ expected_init = (pack_flux2(captured["init_latents"]) - bn_mean) / bn_std+ assert torch.allclose(recorded["init_latents"], expected_init, atol=1e-2)+++def test_a_degenerate_schedule_returns_denormalized_start_latents() -> None:+ """denoising_start == denoising_end leaves nothing to step.++ The early return must still hand back latents in the same raw space the full path returns, or a+ downstream FLUX.2 denoise that normalizes them divides the noise term by bn_std a second time.+ """+ captured = _drive(denoising_start=0.5, denoising_end=0.5)++ timesteps = _expected_schedule(denoising_start=0.5, denoising_end=0.5)+ assert len(timesteps) == 1, "this test only means something while the schedule is degenerate"+ assert not captured["reached_transformer"]++ bn_mean, bn_std = (t.to(torch.bfloat16) for t in _bn_stats())+ t_0 = timesteps[0]+ normalized_init = (pack_flux2(captured["init_latents"]) - bn_mean) / bn_std+ expected_packed = t_0 * pack_flux2(captured["noise"]) + (1.0 - t_0) * normalized_init+ expected = unpack_flux2((expected_packed * bn_std + bn_mean).float(), SIZE, SIZE)++ assert captured["result"] is not None+ assert torch.allclose(captured["result"], expected, atol=1e-2)+++def test_the_degenerate_return_is_not_the_raw_space_blend() -> None:+ """Guard against a regression to returning the un-denormalized mixture."""+ captured = _drive(denoising_start=0.5, denoising_end=0.5)++ t_0 = _expected_schedule(denoising_start=0.5, denoising_end=0.5)[0]+ raw_blend = (t_0 * captured["noise"] + (1.0 - t_0) * captured["init_latents"]).float()++ # The two differ by the bn_std scaling of the noise term, far beyond bf16 precision.+ assert not torch.allclose(captured["result"], raw_blend, atol=1e-1)+++def test_img2img_still_takes_the_requested_number_of_steps() -> None:+ """Clipping the shifted schedule dropped most of the steps; the node has to space them back in.++ At 4 steps and denoising_start 0.5 the clipped window holds a single step, from sigma 0.5 straight+ to 0. One Euler jump that large destroys the source image's fine detail, which is what users saw+ as a loss of skin texture.+ """+ captured = _drive(denoising_start=0.5)++ assert len(captured["redensify_calls"]) == 1+ call = captured["redensify_calls"][0]+ assert call["num_steps"] == NUM_STEPS+ assert len(call["clipped"]) - 1 < NUM_STEPS, "precondition: clipping dropped steps"+ assert len(call["result"]) - 1 == NUM_STEPS+ # The respacing must not move the window: t_0 feeds the img2img preblend.+ assert call["result"][0] == call["clipped"][0]+ assert call["result"][-1] == call["clipped"][-1]+++def test_txt2img_is_not_respaced() -> None:+ """txt2img hands the full schedule to the scheduler; there is nothing clipped to space out."""+ captured = _drive(denoising_start=0.0, with_init=False)++ assert captured["redensify_calls"] == []+++def test_respacing_leaves_full_strength_img2img_alone() -> None:+ """denoising_start == 0 with init latents keeps every sigma of the shifted schedule.++ This is the endpoint that must stay identical to txt2img, so respacing may not touch it.+ """+ captured = _drive(denoising_start=0.0, with_mask=True)++ assert len(captured["redensify_calls"]) == 1+ call = captured["redensify_calls"][0]+ assert call["result"] == call["clipped"]diff --git a/tests/backend/flux2/test_flux2_schedule_shift.py b/tests/backend/flux2/test_flux2_schedule_shift.pynew file mode 100644index 0000000000..3a7f0c6fd7--- /dev/null+++ b/tests/backend/flux2/test_flux2_schedule_shift.py@@ -0,0 +1,153 @@+"""Regression tests for the FLUX.2 schedule shift shared by the txt2img and img2img paths.++``get_schedule_flux2()`` returns an unshifted linear schedule because the txt2img scheduler applies+the exponential shift from ``mu`` itself. img2img and inpainting step the schedule manually and must+apply the same shift, otherwise they run the model on a sigma trajectory txt2img never visits -- with+9 steps the shifted schedule bottoms out at 0.485 while the linear one runs down to 0.111, and a+distilled model like FLUX.2 Klein leaves a grainy residue down there.+"""++import numpy as np+import pytest+from diffusers import FlowMatchEulerDiscreteScheduler++from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional+from invokeai.backend.flux2.sampling_utils import (+ FLUX2_TXT2IMG_SCHEDULER_KWARGS,+ compute_empirical_mu,+ get_schedule_flux2,+ redensify_schedule_flux2,+ time_shift_flux2,+ unshift_flux2,+)+++def _txt2img_scheduler() -> FlowMatchEulerDiscreteScheduler:+ """The scheduler exactly as Flux2DenoiseInvocation builds it for txt2img.++ Built from the same config the node uses rather than a copy of it, so the two cannot drift apart+ without this test noticing.+ """+ return FlowMatchEulerDiscreteScheduler(**FLUX2_TXT2IMG_SCHEDULER_KWARGS)++[email protected]("num_steps", [4, 9, 20, 30])+def test_shift_matches_the_txt2img_scheduler(num_steps: int) -> None:+ """The manual shift must reproduce the sigmas the txt2img scheduler produces."""+ image_seq_len = 64 * 64+ timesteps = get_schedule_flux2(num_steps=num_steps, image_seq_len=image_seq_len)+ mu = compute_empirical_mu(image_seq_len=image_seq_len, num_steps=num_steps)++ scheduler = _txt2img_scheduler()+ scheduler.set_timesteps(sigmas=timesteps[:-1], mu=mu)++ shifted = time_shift_flux2(timesteps, mu)+ np.testing.assert_allclose(shifted, [float(s) for s in scheduler.sigmas], rtol=0, atol=1e-6)+++def test_shift_is_a_no_op_at_the_endpoints() -> None:+ """1.0 and 0.0 are fixed points, and 0.0 must not divide by zero."""+ shifted = time_shift_flux2([1.0, 0.5, 0.0], mu=2.02)+ assert shifted[0] == 1.0+ assert shifted[-1] == 0.0+++def test_shift_is_strictly_decreasing_and_bounded() -> None:+ timesteps = get_schedule_flux2(num_steps=30, image_seq_len=64 * 64)+ shifted = time_shift_flux2(timesteps, mu=compute_empirical_mu(image_seq_len=64 * 64, num_steps=30))++ assert all(0.0 <= s <= 1.0 for s in shifted)+ assert all(a > b for a, b in zip(shifted[:-1], shifted[1:], strict=True))+++def test_shift_raises_the_schedule_floor_above_the_linear_one() -> None:+ """The property that matters: the model is never asked for the low sigmas of the linear schedule."""+ num_steps = 9+ linear = get_schedule_flux2(num_steps=num_steps, image_seq_len=64 * 64)+ shifted = time_shift_flux2(linear, mu=compute_empirical_mu(image_seq_len=64 * 64, num_steps=num_steps))++ # Lowest sigma the model is actually evaluated at (the final 0.0 entry is the step target, not a+ # timestep the model is called with).+ assert linear[-2] == pytest.approx(1 / num_steps)+ assert shifted[-2] > 0.45+ assert all(s >= lin for s, lin in zip(shifted, linear, strict=True))+++def test_unshift_inverts_the_shift() -> None:+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=9)+ sigmas = [i / 200 for i in range(201)]++ assert unshift_flux2(time_shift_flux2(sigmas, mu), mu) == pytest.approx(sigmas, abs=1e-12)++[email protected]("num_steps", [4, 9, 20])[email protected]("strength", [0.05, 0.2, 0.5, 0.75])+def test_redensify_restores_the_requested_step_count(num_steps: int, strength: float) -> None:+ """A clipped window is stepped with the number of steps that was actually requested.++ This is the img2img case: the canvas maps UI strength to ``denoising_start = 1 - s**0.2``, and+ clipping the shifted schedule to that window drops most of the steps.+ """+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=num_steps)+ shifted = time_shift_flux2(get_schedule_flux2(num_steps=num_steps, image_seq_len=64 * 64), mu)+ clipped = clip_timestep_schedule_fractional(shifted, 1 - strength**0.2, 1.0)+ assert len(clipped) - 1 < num_steps, "precondition: clipping must have dropped steps"++ respaced = redensify_schedule_flux2(clipped, num_steps, mu)++ assert len(respaced) - 1 == num_steps+ # The endpoints define the denoising range and the sigma the start latents are blended at, so+ # they must come back bit-exact, not merely close.+ assert respaced[0] == clipped[0]+ assert respaced[-1] == clipped[-1]+ assert all(a > b for a, b in zip(respaced[:-1], respaced[1:], strict=True))+++def test_redensify_follows_the_full_schedule_through_the_window() -> None:+ """Respacing samples the shifted curve, it does not draw a straight line across the window.++ Spacing the interior points evenly in shifted space instead of unshifted space would still give+ the right number of steps and the right endpoints, and every other test here would still pass --+ but the sigmas in between would be wrong. This pins them: the unshifted schedule is uniform, so+ respacing the window between two of its sigmas has to reproduce the full schedule's own sigmas+ in between, exactly.+ """+ num_steps = 8+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=num_steps)+ linear = get_schedule_flux2(num_steps=num_steps, image_seq_len=64 * 64)+ assert np.allclose(np.diff(linear), np.diff(linear)[0]), "precondition: the linear schedule is evenly spaced"+ full = time_shift_flux2(linear, mu)++ # The bare endpoints of the schedule's second half, respaced back to the 4 steps that span it.+ respaced = redensify_schedule_flux2([full[4], full[-1]], 4, mu)++ assert respaced == pytest.approx(full[4:], abs=1e-12)+ # Sanity: the interior is genuinely curved, so a straight line across the window would differ.+ straight = np.linspace(full[4], full[-1], 5)+ assert not np.allclose(respaced, straight, atol=1e-6)++[email protected]("num_steps", [4, 9, 20])+def test_redensify_leaves_an_unclipped_schedule_alone(num_steps: int) -> None:+ """Strength 1.0 / txt2img must be untouched: the fix may only ever add steps back."""+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=num_steps)+ shifted = time_shift_flux2(get_schedule_flux2(num_steps=num_steps, image_seq_len=64 * 64), mu)+ clipped = clip_timestep_schedule_fractional(shifted, 0.0, 1.0)++ assert redensify_schedule_flux2(clipped, num_steps, mu) == clipped+++def test_redensify_never_makes_a_schedule_sparser() -> None:+ """A window that already holds enough steps keeps every one of them."""+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=4)+ dense = [0.9, 0.8, 0.7, 0.6, 0.5, 0.0]++ assert redensify_schedule_flux2(dense, 4, mu) == dense++[email protected]("degenerate", [[], [0.5], [0.5, 0.5]])+def test_redensify_passes_degenerate_schedules_through(degenerate: list[float]) -> None:+ """denoising_start == denoising_end leaves nothing to space out; the caller handles that case."""+ mu = compute_empirical_mu(image_seq_len=64 * 64, num_steps=4)++ assert redensify_schedule_flux2(degenerate, 4, mu) == degenerate