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.

Merge remote-tracking branch 'origin/main' into feat/flux2-klein-int8

Alexander Eichhornb08453799685
diff --cc docs/src/content/docs/start-here/system-requirements.mdx
index a86e11bbf8,2e84df4412..fa8dcb8aeb
--- a/docs/src/content/docs/start-here/system-requirements.mdx
+++ b/docs/src/content/docs/start-here/system-requirements.mdx
@@@ -28,8 -28,8 +28,8 @@@ The requirements below are rough guidel
| SDXL | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | |
| FLUX.1 | 1024x1024 | Nvidia 20xx+ | 10GB | 32GB | |
| FLUX.2 Klein 4B | 1024x1024 | Nvidia 30xx+ | 12GB | 16GB | FP8 works with 8GB+; Diffusers + encoder |
-| FLUX.2 Klein 9B | 1024x1024 | Nvidia 40xx | 24GB | 32GB | FP8 works with 12GB+; Diffusers + encoder |
+| FLUX.2 Klein 9B | 1024x1024 | Nvidia 30xx+ | 12GB | 32GB | int8 9.5GB on any supported GPU; FP8 needs a 40xx **and** `fp8_compute` (off by default) to stay that small, else ~18GB. The Qwen3 8B encoder is 15GB and streams on a 12GB card |
- | Z-Image Turbo | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | Q4_K 8GB; Q8/BF16 16GB+ |
+ | Z-Image Turbo | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | Q4_K / NVFP4 8GB; Q8/BF16 16GB+ |
| Krea-2 (Turbo / Raw) | 1024x1024 | Nvidia 40xx | 24GB | 32GB | FP8 works with 16GB+; GGUF Q4_K ~12GB. Diffusers ~26GB; GGUF needs a standalone VAE + Qwen3-VL encoder |
| Wan 2.2 A14B (T2V/I2V) | 1280x720 | Nvidia 30xx+ | 12GB | 32GB | Dual-expert MoE; Q4_K_M 12GB; Q8 18GB+; Diffusers requires 32GB+ |
| Wan 2.2 TI2V-5B | 1280x720 | Nvidia 20xx+ | 8GB | 16GB | Single transformer; Q4_K_M 6GB+; Q8 8GB+; Diffusers 12GB+ |
diff --cc invokeai/app/invocations/flux2/flux2_denoise.py
index c1058e3697,33725938a4..7bd838f7ac
--- a/invokeai/app/invocations/flux2/flux2_denoise.py
+++ b/invokeai/app/invocations/flux2/flux2_denoise.py
@@@ -47,10 -47,6 +47,10 @@@ from invokeai.backend.patches.lora_conv
)
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
- from invokeai.backend.quantization.int8_convrot import (
- peak_int8_dequant_transient_bytes,
++from invokeai.backend.quantization.dequantizing_linear import (
++ peak_dequant_transient_bytes,
+ requires_sidecar_patching,
+)
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import FLUXConditioningInfo
@@@ -516,18 -512,11 +516,18 @@@ class Flux2DenoiseInvocation(BaseInvoca
)
with ExitStack() as exit_stack:
+ transformer_info = context.models.load(self.transformer.transformer)
+
+ # An `int8_tensorwise` build materializes each linear's dequantized weight per forward.
+ # That transient is not part of the model's resident size, so it is added to the
+ # activation estimate -- the two are alive at the same time -- rather than taking its
+ # chances against whatever slack the estimate happens to have. Read from the unlocked
+ # model, before the VRAM lock the reservation applies to; zero for every other build.
- int8_dequant_bytes = peak_int8_dequant_transient_bytes(transformer_info.model, inference_dtype)
++ int8_dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
+
# Load the transformer model
(cached_weights, transformer) = exit_stack.enter_context(
- context.models.load(self.transformer.transformer).model_on_device(
- working_mem_bytes=estimated_working_memory
- )
+ transformer_info.model_on_device(working_mem_bytes=estimated_working_memory + int8_dequant_bytes)
)
config = transformer_config
diff --cc invokeai/backend/model_manager/load/model_loaders/flux.py
index b5acffd457,eb056e8293..ca3f6ac0a5
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@@ -1109,74 -1080,38 +1111,74 @@@ class Flux2CheckpointModel(ModelLoader)
for k, v in sd.items()
}
- # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale, optionally an input scale). Until now
- # these were folded into bf16 at load, so a FLUX.2 checkpoint that ships them ran as fp8
- # *storage* at best and never reached the tensor cores.
- #
- # Hints ship in the safetensors header or as per-layer `.comfy_quant` markers, and both name
- # layers in the checkpoint's BFL scheme. The scales are read after the rename, so the hints
- # have to be renamed too -- a fused `qkv` becomes three diffusers layers.
- header_hints = strip_layer_path_prefix(
- parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ # Which of the two ComfyUI side channels this file carries is decided once, and int8 first:
+ # an int8 layer ships a `.weight_scale` too, so probing for scales without ruling int8 out
+ # would take the whole checkpoint down the fp8 path -- scaled, never dequantized to a dtype
+ # torch computes in, and for a `convrot` repack never un-rotated either.
+ has_int8_weights = any(
+ isinstance(key, str) and key.endswith(".weight") and getattr(value, "dtype", None) is torch.int8
+ for key, value in sd.items()
)
- layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
- path_map = remap_flux2_layer_paths(layer_hints.keys())
- layer_hints = {
- renamed: hints for name, hints in layer_hints.items() for renamed in (path_map.get(name) or [name])
- }
- # Convert BFL format state dict to diffusers format. Scales and markers are carried to
- # wherever their weight landed, including across the fused-qkv split.
- converted_sd = convert_flux2_bfl_to_diffusers(sd)
+ int8_markers: dict[str, dict[str, Any]] = {}
+ fp8_layers: dict[str, Fp8ScaledLayer] = {}
+
+ if has_int8_weights:
+ # The converter carries `.comfy_quant` and `.weight_scale` to wherever their weight
+ # landed, so the markers are read *after* the rename and already name diffusers modules
+ # -- including the three a fused `qkv` becomes, which each inherit the fused layer's
+ # per-tensor scale and marker.
+ converted_sd = convert_flux2_bfl_to_diffusers(sd)
+ int8_markers = extract_int8_convrot_markers(converted_sd)
+ # The header is the other place a repack declares its scheme, and for FLUX.2 that is
+ # not hypothetical: Comfy-Org's own fp8 build of this model carries *no* per-layer
+ # markers and names every layer in `_quantization_metadata`. A build from that tooling
+ # would otherwise be refused for a marker it never had to write. Header entries name
+ # layers in the BFL scheme, so they need the same one-to-many rename the fp8 branch
+ # applies, and a per-layer marker wins where both are present -- only that one can
+ # carry `convrot` and the group size.
+ header_markers = {
+ renamed: marker
+ for name, marker in strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ ).items()
+ if marker.get("format") == INT8_TENSORWISE_FORMAT
+ for renamed in (remap_flux2_layer_paths([name]).get(name) or [name])
+ }
+ int8_markers = {**header_markers, **int8_markers}
+ else:
+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale, optionally an input scale). Until
+ # now these were folded into bf16 at load, so a FLUX.2 checkpoint that ships them ran as
+ # fp8 *storage* at best and never reached the tensor cores.
+ #
+ # Hints ship in the safetensors header or as per-layer `.comfy_quant` markers, and both
+ # name layers in the checkpoint's BFL scheme. The scales are read after the rename, so
+ # the hints have to be renamed too -- a fused `qkv` becomes three diffusers layers.
+ header_hints = strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ )
+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
+ path_map = remap_flux2_layer_paths(layer_hints.keys())
+ layer_hints = {
+ renamed: hints for name, hints in layer_hints.items() for renamed in (path_map.get(name) or [name])
+ }
+
+ # Convert BFL format state dict to diffusers format. Scales and markers are carried to
+ # wherever their weight landed, including across the fused-qkv split.
+ converted_sd = convert_flux2_bfl_to_diffusers(sd)
- fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)
- if fp8_layers and not keep_fp8:
- # Neither the matmul nor FP8 Storage asked for them, so keeping them quantized would
- # dequantize on every forward to save memory nobody wanted saved. Fold the scale in --
- # the legacy result, except reached through the shared helper.
- dequantize_fp8_scaled(converted_sd, fp8_layers, torch.bfloat16)
- fp8_layers = {}
+ fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)
+ if fp8_layers and not keep_fp8:
- # Without the matmul, keeping them quantized would halve VRAM but dequantize on
- # every forward. Fold the scale into the weight instead -- the legacy result, except
- # reached through the shared helper.
++ # Neither the matmul nor FP8 Storage asked for them, so keeping them quantized would
++ # dequantize on every forward to save memory nobody wanted saved. Fold the scale in
++ # -- the legacy result, except reached through the shared helper.
+ dequantize_fp8_scaled(converted_sd, fp8_layers, torch.bfloat16)
+ fp8_layers = {}
- # Safety net for scale layouts the shared extractor does not model (block-wise scales whose
- # shape has to be expanded to the weight's). It is a no-op on every checkpoint measured so
- # far, because extraction has already taken the scales it understood.
- converted_sd = self._dequantize_fp8_weights(converted_sd, keep_fp8=keep_fp8)
+ # Safety net for scale layouts the shared extractor does not model (block-wise scales
+ # whose shape has to be expanded to the weight's). It is a no-op on every checkpoint
+ # measured so far, because extraction has already taken the scales it understood.
+ converted_sd = self._dequantize_fp8_weights(converted_sd, keep_fp8=keep_fp8)
# Detect architecture from checkpoint keys
double_block_indices = [
@@@ -1321,18 -1209,11 +1323,20 @@@
# Load the state dict - guidance weights were already initialized above if missing
load_state_dict_ignoring_extras(model, converted_sd, source="FLUX.2 transformer checkpoint", assign=True)
+ if int8_markers:
+ # No setting behind this one and nothing to fall back to: `Int8ConvrotLinear` holds the
+ # stored codes and dequantizes per forward, so an 8.8 GiB file stays 8.8 GiB resident on
+ # every device. What it does not get is int8 *compute*.
+ self._logger.info(
+ f"FLUX.2: kept {len(quantized)} layer(s) in int8 (int8_tensorwise checkpoint, dequantized per forward)"
+ )
+ return model
+
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
- self._logger.info(f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ self._logger.info(
+ f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
warn_on_unattached_scales(self._logger, "FLUX.2", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
if marked and full_precision_hints_respected():
diff --cc tests/app/invocations/test_flux2_working_memory.py
index 01a32f07d1,e5899df397..dea23d130d
--- a/tests/app/invocations/test_flux2_working_memory.py
+++ b/tests/app/invocations/test_flux2_working_memory.py
@@@ -1242,104 -1223,3 +1242,104 @@@ class TestDiffusersAttentionDispatchIsC
side_effect=AttributeError("moved"),
):
assert _diffusers_attention_dispatch() == "math"
+
+
+class TestTheInt8DequantTransientReachesTheReservation:
+ """A helper existing is not the same as it being called.
+
+ An `int8_tensorwise` build materializes each linear's dequantized weight inside `forward`, and
+ that peak is not part of the model's resident size. Deleting `+ int8_dequant_bytes` from the
+ node leaves every other test in this file green, because they drive it with a `MagicMock` whose
+ module tree is empty -- so this is the only place the wire is pinned. For Klein 9B the term is
+ 576 MiB, against a card this build exists to fit into.
+ """
+
+ @staticmethod
+ def _int8_transformer() -> torch.nn.Module:
+ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+
+ model = torch.nn.Module()
+ model.dense = torch.nn.Linear(64, 64, bias=False).to(torch.bfloat16)
+ model.quantized = Int8ConvrotLinear(
+ weight=torch.zeros(128, 64, dtype=torch.int8),
+ weight_scale=torch.ones(()),
+ convrot=False,
+ )
+ return model
+
+ def test_an_int8_build_adds_its_transient_on_top_of_the_activation_estimate(self):
+ harness = TestFlux2DenoiseRequestsWorkingMemory()
+ model = self._int8_transformer()
+
+ dense = harness._run(num_ref_tokens=0)
+ with_int8 = harness._run(num_ref_tokens=0, transformer=model)
+
+ # Two weight-sized tensors in the compute dtype, over the largest quantized layer.
+ assert with_int8 - dense == 2 * 128 * 64 * torch.bfloat16.itemsize
+
+ def test_a_dense_build_adds_nothing(self):
+ # The other half: a bf16 or fp8 checkpoint must not be charged for a dequantization it
+ # never performs.
+ harness = TestFlux2DenoiseRequestsWorkingMemory()
+ dense_model = torch.nn.Linear(64, 64).to(torch.bfloat16)
+
+ assert harness._run(num_ref_tokens=0, transformer=dense_model) == harness._run(num_ref_tokens=0)
+
+
+class TestTheSidecarDecisionReachesThePatcher:
+ """An int8 checkpoint carries `ModelFormat.Checkpoint` like any other single file.
+
+ Asking the format alone therefore answers "not quantized", and `LayerPatcher` picks direct
+ patching -- which calls `get_parameter("weight")` on an `Int8ConvrotLinear` that owns only
+ buffers. Verified consequence: `RuntimeError: generator raised StopIteration`, i.e. every LoRA
+ on an int8 Klein 9B dies with an error that names nothing. So the question has to be put to the
+ loaded module tree.
+ """
+
+ @staticmethod
+ def _sidecar_flag_for(transformer: torch.nn.Module, model_format) -> bool:
- from invokeai.backend.quantization.int8_convrot import requires_sidecar_patching
++ from invokeai.backend.quantization.dequantizing_linear import requires_sidecar_patching
+
+ return requires_sidecar_patching(transformer, model_format)
+
+ def test_an_int8_checkpoint_is_patched_as_a_sidecar(self):
+ from invokeai.backend.model_manager.taxonomy import ModelFormat
+
+ model = TestTheInt8DequantTransientReachesTheReservation._int8_transformer()
+
+ assert self._sidecar_flag_for(model, ModelFormat.Checkpoint) is True
+
+ def test_a_dense_checkpoint_is_not(self):
+ from invokeai.backend.model_manager.taxonomy import ModelFormat
+
+ assert self._sidecar_flag_for(torch.nn.Linear(4, 4), ModelFormat.Checkpoint) is False
+
+ @staticmethod
+ def _flag_at_the_node(transformer: torch.nn.Module) -> bool:
+ """What the node actually hands `LayerPatcher`, driven through `_run_diffusion`.
+
+ The wire, not the helper: the node used to key on a hardcoded format list, and a list
+ cannot see an int8 build at all.
+ """
+ from contextlib import contextmanager
+
+ captured: dict = {}
+
+ @contextmanager
+ def on_device(**_kwargs):
+ yield (None, transformer)
+
+ def apply_patches(**kwargs):
+ captured["force_sidecar_patching"] = kwargs["force_sidecar_patching"]
+ raise _StopBeforeLoad
+
+ harness = TestFlux2DenoiseRequestsWorkingMemory()
+ with patch.object(LayerPatcher, "apply_smart_model_patches", staticmethod(apply_patches)):
+ harness._run(num_ref_tokens=0, transformer=transformer, on_device=on_device)
+ return captured["force_sidecar_patching"]
+
+ def test_the_node_asks_the_model_and_not_only_the_format(self):
+ int8 = TestTheInt8DequantTransientReachesTheReservation._int8_transformer()
+
+ assert self._flag_at_the_node(int8) is True
+ assert self._flag_at_the_node(torch.nn.Linear(4, 4).to(torch.bfloat16)) is False
diff --cc tests/app/invocations/test_z_image_denoise_working_memory.py
index 0000000000,0c6582acca..3340bb38c9
mode 000000,100644..100644
--- a/tests/app/invocations/test_z_image_denoise_working_memory.py
+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py
@@@ -1,0 -1,286 +1,286 @@@
+ """Z-Image denoise working memory: the estimate, and what the node hands `model_on_device()`.
+
+ Until this estimate existed the node reserved only the per-forward dequant transient, so the model cache kept just
+ `device_working_mem_gb` free. Where SDPA materializes the score matrices -- ROCm on Windows, MPS -- a 1024px
+ generation needs several times that, and on Windows the driver pages the shortfall into shared system memory instead
+ of failing: 7.7 GB of it, and a 185 s denoise, on an RX 9060 XT.
+
+ The `MEASURED_*` tables are peak *reserved* memory on CUDA (RTX 4090) in bf16 with a 512-token caption, from
+ `scripts/calibrate_z_image_working_memory.py`. Every estimate must stay an upper bound on them.
+
+ MiniMax H3 and Krea-2 add the same dequant transient to their own estimates. Krea-2's wiring is pinned in
-`tests/app/invocations/test_krea2_denoise.py`; MiniMax H3's is not, since reaching its `model_on_device()` call needs a
-packed sequence.
++`tests/app/invocations/test_krea2_denoise.py` and FLUX.2's in `tests/app/invocations/test_flux2_working_memory.py`;
++MiniMax H3's is not, since reaching its `model_on_device()` call needs a packed sequence.
+ """
+
+ from contextlib import ExitStack, contextmanager, nullcontext
+ from types import SimpleNamespace
+ from unittest.mock import MagicMock, patch
+
+ import pytest
+ import torch
+
+ from invokeai.app.invocations.fields import ZImageConditioningField
+ from invokeai.app.invocations.z_image.z_image_control import ZImageControlField
+ from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
+ from invokeai.backend.util import attention
+ from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension
+ from invokeai.backend.z_image.text_conditioning import ZImageRegionalTextConditioning
+ from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+
+ MB = 1024**2
+ GB = 1024**3
+
+ # Only the device's type is read: every question the estimate asks about it is answered by `_sdpa` below.
+ DEVICE = torch.device("cuda")
+
+
+ @contextmanager
+ def _sdpa(materializes):
+ """Answer the three dispatch questions `sdpa_score_matrix_bytes` asks, so no test depends on the torch build, the
+ diffusers attention backend or the ROCm head-dim guard of the machine it runs on."""
+ with (
+ patch.object(attention, "_diffusers_attention_dispatch", return_value=attention._DISPATCH_TORCH),
+ patch.object(attention, "rocm_sdpa_uses_math_kernel", return_value=False),
+ patch.object(
+ attention, "_torch_sdpa_materializes_score_matrix", side_effect=lambda *args: materializes(args[-1])
+ ),
+ ):
+ yield
+
+
+ def _estimate(image_seq_len, text_seq_len=512, num_control_blocks=0, has_mask=False, materializes=lambda mask: False):
+ with _sdpa(materializes):
+ return ZImageDenoiseInvocation._estimate_working_memory(
+ image_seq_len=image_seq_len,
+ text_seq_len=text_seq_len,
+ num_loras=0,
+ num_control_blocks=num_control_blocks,
+ has_attention_mask=has_mask,
+ device=DEVICE,
+ )
+
+
+ def _image_tokens(px: int) -> int:
+ return (px // 16) ** 2
+
+
+ class TestEstimate:
+ # (pixels per side, ControlNet blocks, measured peak reserved MiB)
+ MEASURED_FUSED = [
+ (1024, 0, 1012),
+ (1440, 0, 2004),
+ (2048, 0, 3942),
+ (1024, 1, 1122),
+ (1024, 6, 1212),
+ (1024, 15, 1650),
+ ]
+
+ @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
+ def test_estimate_is_an_upper_bound_on_measured_peak(self, px, control_blocks, measured_mb):
+ """The cache treats the estimate as the amount it must keep free, so under-estimating runs out of memory."""
+ assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) >= measured_mb * MB
+
+ @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
+ def test_estimate_does_not_wildly_over_reserve(self, px, control_blocks, measured_mb):
+ """Every byte reserved beyond need is transformer offloaded to RAM and run over PCIe."""
+ assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) <= measured_mb * MB + 2 * GB
+
+ def test_image_and_caption_are_counted_as_the_transformer_pads_them(self):
+ """Each run is padded to a multiple of 32 before the two are joined, and the padding is attended too."""
+ assert _estimate(4096, text_seq_len=97) == _estimate(4096, text_seq_len=128)
+ assert _estimate(4001, text_seq_len=128) == _estimate(4032, text_seq_len=128)
+ assert _estimate(4096, text_seq_len=129) > _estimate(4096, text_seq_len=128)
+
+
+ class TestMaterializedScoreMatrix:
+ def test_the_score_matrix_is_charged_only_where_it_is_built(self):
+ """Measured at 1024px: a forced math kernel took 9.4 GiB where the fused one took 1.0. The attention mask
+ decides the dispatch, so it has to reach the probe."""
+ seq_len = 4096 + 512
+ unmasked = _estimate(4096, materializes=lambda has_mask: has_mask)
+ masked = _estimate(4096, has_mask=True, materializes=lambda has_mask: has_mask)
+
+ assert unmasked == _estimate(4096)
+ assert masked - unmasked == 30 * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+ def test_estimate_bounds_the_measured_math_kernel(self):
+ assert _estimate(_image_tokens(1024), materializes=lambda has_mask: True) >= 9632 * MB
+
+
+ class TestRegionalAttentionBias:
+ def test_no_regional_mask_costs_nothing(self):
+ assert ZImageDenoiseInvocation._regional_attention_bias_bytes(None, 4096, torch.bfloat16) == 0
+
+ def test_bias_is_sized_on_the_padded_unified_sequence(self):
+ """4096 image tokens and a 100-token caption: the boolean copy covers the 4196 real tokens, the additive bias
+ the 4096 + 128 padded ones, and `torch.where` fills the image block from a 4096 x 4096 scratch."""
+ mask = torch.empty((4196, 4196), dtype=torch.float16, device="meta")
+
+ bias_bytes = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 4096, torch.bfloat16)
+
+ assert bias_bytes == 4196**2 + 4224**2 * 2 + 4096**2 * 2
+
+
+ class _StopBeforeLoad(Exception):
+ """Raised out of a mocked `model_on_device()` so the node stops at a reservation."""
+
+
+ # Stands in for the activation estimate, which is tested above; any value the transient cannot produce.
+ ACTIVATION_ESTIMATE = 3_000_000_007
+ POSITIVE_TOKENS = 8
+
+
+ def _dense_transformer() -> torch.nn.Module:
+ model = torch.nn.Module()
+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
+ return model
+
+
+ class TestNodeReservation:
+ """The wire from the node to `model_on_device()`: deleting any of these arguments leaves the estimate's own tests
+ green."""
+
+ def _run(self, transformer=None, *, control_blocks=None, negative_tokens=None, loras=0, regional_mask=None):
+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
+ ConditioningFieldData,
+ ZImageConditioningInfo,
+ )
+
+ transformer = transformer if transformer is not None else _dense_transformer()
+ transformer_info = MagicMock()
+ transformer_info.model = transformer
+
+ control = None
+ control_info = MagicMock()
+ if control_blocks is None:
+ transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+ else:
+ # Past the transformer's lock, up to the adapter's.
+ transformer_info.model_on_device = MagicMock(return_value=nullcontext((None, transformer)))
+ control = ZImageControlField.model_construct(control_model=MagicMock(), image_name="control")
+ control_info.model = MagicMock(spec=ZImageControlAdapter)
+ control_info.model.control_layers = [torch.nn.Identity()] * control_blocks
+ control_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+
+ caption_tokens = {"pos": POSITIVE_TOKENS, "neg": negative_tokens}
+ context = MagicMock()
+ context.models.load.side_effect = lambda identifier: (
+ control_info if control is not None and identifier is control.control_model else transformer_info
+ )
+ context.models.get_config.return_value = SimpleNamespace(
+ base=BaseModelType.ZImage, type=ModelType.Main, format=ModelFormat.Checkpoint
+ )
+ context.conditioning.load.side_effect = lambda name: ConditioningFieldData(
+ conditionings=[ZImageConditioningInfo(prompt_embeds=torch.zeros(caption_tokens[name], 2560))]
+ )
+
+ invocation = ZImageDenoiseInvocation.model_construct(
+ latents=None,
+ noise=None,
+ denoise_mask=None,
+ denoising_start=0.0,
+ denoising_end=1.0,
+ add_noise=True,
+ transformer=MagicMock(transformer=MagicMock(), loras=[MagicMock() for _ in range(loras)]),
+ positive_conditioning=ZImageConditioningField(conditioning_name="pos"),
+ negative_conditioning=ZImageConditioningField(conditioning_name="neg") if negative_tokens else None,
+ control=control,
+ vae=None,
+ guidance_scale=2.0 if negative_tokens else 1.0,
+ width=256,
+ height=256,
+ steps=2,
+ scheduler="euler",
+ seed=0,
+ )
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_torch_device",
+ return_value=torch.device("cpu"),
+ )
+ )
+ stack.enter_context(
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_bfloat16_safe_dtype",
+ return_value=torch.bfloat16,
+ )
+ )
+ stack.enter_context(
+ patch.object(ZImageDenoiseInvocation, "_get_noise", return_value=torch.zeros(1, 16, 32, 32))
+ )
+ estimate = stack.enter_context(
+ patch.object(ZImageDenoiseInvocation, "_estimate_working_memory", return_value=ACTIVATION_ESTIMATE)
+ )
+ if regional_mask is not None:
+ regional = ZImageRegionalPromptingExtension(
+ regional_text_conditioning=ZImageRegionalTextConditioning(
+ prompt_embeds=torch.zeros(POSITIVE_TOKENS, 2560), image_masks=[None], embedding_ranges=[]
+ ),
+ regional_attn_mask=regional_mask,
+ )
+ stack.enter_context(
+ patch.object(ZImageRegionalPromptingExtension, "from_text_conditionings", return_value=regional)
+ )
+ with pytest.raises(_StopBeforeLoad):
+ invocation._run_diffusion(context)
+
+ return SimpleNamespace(
+ reserved=transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"],
+ estimate=estimate.call_args.kwargs,
+ adapter_reserved=(
+ control_info.model_on_device.call_args.kwargs.get("working_mem_bytes") if control is not None else None
+ ),
+ )
+
+ def test_an_unquantized_transformer_reserves_the_estimate_for_its_sequence(self):
+ run = self._run()
+
+ assert run.reserved == ACTIVATION_ESTIMATE
+ # 256px is a 16x16 token grid.
+ assert (run.estimate["image_seq_len"], run.estimate["text_seq_len"]) == (256, POSITIVE_TOKENS)
+ assert (run.estimate["num_loras"], run.estimate["num_control_blocks"]) == (0, 0)
+ assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (0, False)
+
+ def test_the_dequant_transient_is_added_to_the_estimate(self):
+ """An int8 layer materializes two weight-sized bf16 tensors per forward, alive alongside the activations."""
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(
+ torch.zeros(1024, CONVROT_GROUP_SIZE, dtype=torch.int8), torch.ones(1024, 1), convrot=False
+ )
+
+ run = self._run(model)
+
+ assert run.reserved == ACTIVATION_ESTIMATE + 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
+
+ def test_a_longer_negative_caption_sizes_the_sequence(self):
+ """With CFG the unconditional pass runs its own forward, so the longer of the two captions is the peak."""
+ assert self._run(negative_tokens=40).estimate["text_seq_len"] == 40
+
+ def test_loras_are_counted(self):
+ assert self._run(loras=2).estimate["num_loras"] == 2
+
+ def test_a_regional_mask_reaches_the_estimate(self):
+ mask = torch.zeros((256 + POSITIVE_TOKENS, 256 + POSITIVE_TOKENS), dtype=torch.float16)
+
+ run = self._run(regional_mask=mask)
+
+ expected_bias = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 256, torch.bfloat16)
+ assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (
+ expected_bias,
+ True,
+ )
+
+ def test_a_control_adapter_reaches_the_estimate_and_keeps_the_reservation(self):
+ """The adapter's block count sizes the hints and its forward always passes a padding mask. It is locked after
+ the transformer, which can then no longer be offloaded -- so it must ask for the same working memory, or its
+ weights fill the room kept for the forward."""
+ run = self._run(control_blocks=15)
+
+ assert (run.estimate["num_control_blocks"], run.estimate["has_attention_mask"]) == (15, True)
+ assert run.adapter_reserved == run.reserved == ACTIVATION_ESTIMATE