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
refactor(loaders): reserve through one function instead of assembling the sum
Alexander Eichhorn6e6ec6b2a99b
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex 62bce3ad5a..d795142203 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -28,13 +28,13 @@ from invokeai.backend.quantization.fp8_scaled import (extract_fp8_scaled_layers,full_precision_hints_respected,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reject_quantized_side_channel,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILoggerfrom invokeai.backend.util.state_dict_loading import log_unexpected_keys, reject_incomplete_load@@ -202,15 +202,15 @@ class AnimaCheckpointModel(ModelLoader):# not kept the prediction charges every float at `model_dtype`, folded yet or not, so the# number is the same on either side of the fold -- what changes is when the room exists.# Building the model first costs nothing: `init_empty_weights` leaves every param on meta.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},)if fp8_layers and not keep_fp8:diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 4ca5f23ea5..134d7ad3e2 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -98,7 +98,6 @@ from invokeai.backend.quantization.fp8_scaled import (is_scale_metadata_key,iter_weight_scale_pairs,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reject_quantized_side_channel,split_fp8_scaled_layers,@@ -115,6 +114,7 @@ from invokeai.backend.quantization.int8_convrot import (install_int8_convrot_layers,reject_unmarked_int8_weights,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.sdnq.detection import is_sdnq_folderfrom invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loaderfrom invokeai.backend.util.logging import InvokeAILogger@@ -861,15 +861,15 @@ class FluxCheckpointModel(ModelLoader):# mapping the prediction would charge those 1 byte/element and arrive at 2. Where they are# not kept the prediction charges every float at the compute dtype, folded yet or not, so# the number is the same on either side of the fold -- what changes is when the room exists.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- torch.bfloat16,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},)if fp8_layers and not keep_fp8:@@ -1249,7 +1249,21 @@ class Flux2CheckpointModel(ModelLoader):# quantized, and with `keep_fp8` false nothing does, so the model-less number is the# same one. With `keep_fp8` true neither step widens anything, and the reservation# below covers the split on its own.- self._ram_cache.make_room(predict_cast_state_dict_size(converted_sd, torch.bfloat16, keep_fp8=False))+ # Through the shared reservation, for the scales `extract_fp8_scaled_layers` has just+ # recovered: they are resident across this `make_room` and are consumed by the fold+ # immediately below, and `predict_cast_state_dict_size` cannot see them because they+ # are no longer in the dict. On an MXFP8 build that is ~0.125 B per weight element of+ # decoded exponent grid. No model here, which is fine -- `keep_fp8` is false, so the+ # prediction does not consult one, and no nvfp4 payload exists on this path.+ reserve_for_load(+ self._ram_cache.make_room,+ converted_sd,+ torch.bfloat16,+ keep_fp8=False,+ model=None,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},+ )if fp8_layers and not keep_fp8:# Neither the matmul nor FP8 Storage asked for them, so keeping them quantized would@@ -1373,15 +1387,15 @@ class Flux2CheckpointModel(ModelLoader):# transient land on an unreserved cache. This path had no reservation at all, which on# a machine already holding the 15 GiB Qwen3-8B encoder meant nothing was ever evicted# to make room for a 16.9 GiB bf16 Klein 9B.- self._ram_cache.make_room(- predict_cast_state_dict_size(- converted_sd,- torch.bfloat16,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )+ reserve_for_load(+ self._ram_cache.make_room,+ converted_sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},)# Scaled layers the cast would dequantize anyway are folded here, scale applied, sodiff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex db69005978..1ba7663a27 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -47,7 +47,6 @@ from invokeai.backend.quantization.fp8_scaled import (extract_fp8_scaled_layers,full_precision_hints_respected,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reject_quantized_side_channel,should_keep_fp8_weights,@@ -61,6 +60,7 @@ from invokeai.backend.quantization.int8_convrot import (reject_int8_layers_a_plain_fold_cannot_decode,reject_unmarked_int8_weights,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys@@ -430,15 +430,15 @@ class Ideogram4CheckpointModel(ModelLoader):# Where the weights are not kept the prediction charges every float at `model_dtype`,# folded yet or not, so the number is the same on either side of the fold -- what changes# is when the room exists.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},)if fp8_layers and not keep_fp8:# Neither consumer asked. Fold the scales in: staying quantized would halve VRAM butdiff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex e48b3e9dc2..64a4571158 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -50,7 +50,6 @@ from invokeai.backend.quantization.fp8_scaled import (extract_fp8_scaled_layers,full_precision_hints_respected,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reattach_layer_sidechannel,should_keep_fp8_weights,@@ -66,6 +65,7 @@ from invokeai.backend.quantization.int8_convrot import (reject_unmarked_int8_weights,resolve_quantized_module_paths,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.nvfp4 import (WEIGHT_SCALE_2_SUFFIX,install_nvfp4_layers,@@ -540,16 +540,15 @@ class Krea2CheckpointModel(ModelLoader):# they are not kept the prediction charges every float at `model_dtype`, folded yet or# not, so the number is the same on either side of the fold -- what changes is when the# room exists.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )- + nvfp4_bytes+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads=nvfp4_payloads,)if fp8_layers and not keep_fp8:@@ -964,8 +963,14 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco# keeps the prediction in step with the split's own scale-layout filter; where the# weights are not kept it charges every float at `model_dtype`, folded yet or not, so the# number is the same on either side of the fold.- self._ram_cache.make_room(- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ fp8_layers=fp8_layers,+ nvfp4_payloads={},)if fp8_layers and not keep_fp8:# Neither consumer wants them packed: fold the scales into the weights. Both consumersdiff --git a/invokeai/backend/model_manager/load/model_loaders/ltx2.py b/invokeai/backend/model_manager/load/model_loaders/ltx2.pyindex 4765d7e256..93d2abfc67 100644--- a/invokeai/backend/model_manager/load/model_loaders/ltx2.py+++ b/invokeai/backend/model_manager/load/model_loaders/ltx2.py@@ -65,6 +65,7 @@ from invokeai.backend.quantization.int8_convrot import (reject_unmarked_int8_weights,resolve_quantized_module_paths,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.nvfp4 import (NVFP4_FORMAT,install_nvfp4_layers,@@ -373,9 +374,15 @@ class _LTX2ComponentLoading:"(int8_tensorwise checkpoint, dequantized per forward)")else:- self._ram_cache.make_room(- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False, model=model, skip_patterns=skip_patterns)- + nvfp4_bytes+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=False,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers={},+ nvfp4_payloads=nvfp4_payloads,)cast_state_dict(sd, model_dtype, keep_fp8=False, model=model, skip_patterns=skip_patterns)diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 8377092808..3cb9c3ad8b 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -71,7 +71,6 @@ from invokeai.backend.quantization.fp8_scaled import (is_scale_metadata_key,iter_weight_scale_pairs,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reject_undecoded_mx_scale,should_keep_fp8_weights,@@ -84,11 +83,11 @@ from invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.int8_convrot import (reject_int8_layers_a_plain_fold_cannot_decode,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.nvfp4 import (NVFP4Payload,install_nvfp4_layers,pop_nvfp4_layers,- predict_nvfp4_install_size,)from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger@@ -1288,16 +1287,15 @@ class MistralEncoderCheckpointLoader(ModelLoader):# One reservation, before the dequantizing branch or the split widens a single weight -- `make_room` makes# that much room rather than adding to an earlier one. The state dict is sized by the predicate the split and# the cast below decide with, the nvfp4 layers as they will be held.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_raw_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )- + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_raw_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads=nvfp4_payloads,)if not fp8_layers:diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 7e98f930ec..1f0e6250a1 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -37,7 +37,6 @@ from invokeai.backend.quantization.fp8_scaled import (extract_comfy_quant_hints,extract_fp8_scaled_layers,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,should_keep_fp8_weights,split_fp8_scaled_layers,@@ -47,7 +46,8 @@ from invokeai.backend.quantization.fp8_scaled import (from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.int8_convrot import reject_int8_layers_a_plain_fold_cannot_decode-from invokeai.backend.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layers, predict_nvfp4_install_size+from invokeai.backend.quantization.load_plan import reserve_for_load+from invokeai.backend.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layersfrom invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (load_bundled_qwen2_5_vl_config_dict,load_bundled_qwen2_5_vl_tokenizer,@@ -315,11 +315,15 @@ class QwenImageCheckpointModel(ModelLoader):# One reservation, before the fold or the split widens a single weight: `make_room` makes that much room# rather than adding to an earlier one.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns, scaled_layers=fp8_layers- )- + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads=nvfp4_payloads,)if fp8_layers and not keep_fp8:@@ -472,9 +476,15 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):# One reservation, before the fold widens a single weight: `make_room` makes that much room rather than adding# to an earlier one. Every fp8 layer is folded to the compute dtype.- self._ram_cache.make_room(- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)- + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=False,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers={},+ nvfp4_payloads=nvfp4_payloads,)# Dequantize ComfyUI-style fp8 weights, then strip the now-unused quantizationdiff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 679750cec0..7e4fb6f2d1 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -56,7 +56,6 @@ from invokeai.backend.quantization.fp8_scaled import (is_scale_metadata_key,iter_weight_scale_pairs,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,reject_quantized_side_channel,reject_undecoded_mx_scale,@@ -72,6 +71,7 @@ from invokeai.backend.quantization.int8_convrot import (install_int8_convrot_layers,reject_unmarked_int8_weights,)+from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.nvfp4 import (NVFP4Payload,install_nvfp4_layers,@@ -649,16 +649,15 @@ class ZImageCheckpointModel(ModelLoader):# With it, `scaled_layers` is what keeps the prediction honest: the split also widens layers# whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would# charge those 1 byte/element and arrive at 2.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,- )- + nvfp4_bytes+ reserve_for_load(+ self._ram_cache.make_room,+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ fp8_layers=fp8_layers,+ nvfp4_payloads=nvfp4_payloads,)if fp8_layers and not keep_fp8:@@ -1370,6 +1369,11 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):# reservation for what the state dict ends up holding -- every tensor but the scale metadata at the# compute dtype, plus the nvfp4 layers as they will be held -- since `make_room` makes that much room# rather than adding to an earlier one.+ # The excluded scale keys are still in `sd` and still resident, so this sum is short by+ # them -- bounded, not open-ended: `_fold_comfy_scaled_weights` refuses an MXFP8 grid by+ # name before folding, so the residue here is per-tensor and per-channel float32 scales,+ # kilobytes on this encoder. That is why this seam keeps its own sum rather than+ # `reserve_for_load`, which sizes a dict the side channel has been *popped* out of.new_sd_size = sum(tensor.nelement() * model_dtype.itemsize for key, tensor in sd.items() if not is_scale_metadata_key(key))diff --git a/invokeai/backend/quantization/load_plan.py b/invokeai/backend/quantization/load_plan.pyindex cd58c63c57..5dc9376b60 100644--- a/invokeai/backend/quantization/load_plan.py+++ b/invokeai/backend/quantization/load_plan.py@@ -63,29 +63,39 @@ def reserve_for_load(dtype: torch.dtype,*,keep_fp8: bool,+ model: torch.nn.Module | None,fp8_layers: Mapping[str, Fp8ScaledLayer],nvfp4_payloads: Mapping[str, NVFP4Payload],- model: torch.nn.Module | None = None,skip_patterns: Iterable[str] = (),) -> int:"""Ask for room for the state dict, the payloads it will install, and the scales it took out.- Both side-channel mappings are required rather than defaulted. A seam that recovered nothing- passes `{}` and says so; a default would let a seam that *did* recover something omit it by- silence and under-reserve by exactly the amount this function exists to count. That is weaker than- making the ordering unrepresentable -- nothing here can stop a caller reserving before it has- recovered -- and it is what a function taking the results can honestly give.+ Both side-channel mappings are required rather than defaulted, and so is `model`. A seam that+ recovered nothing passes `{}`, and one with no model yet passes `None`, and both say so; a default+ would let a seam that *did* have something omit it by silence and under-reserve. That matters for+ `model` too: with none, `_is_fp8_matmul_weight` answers for the safe subset, so under `keep_fp8`+ every 2-D weight predicts as staying quantized at 1 B/element and a quantized non-Linear then+ arrives at `dtype.itemsize`.++ This is weaker than making the ordering unrepresentable -- nothing here can stop a caller+ reserving before it has recovered -- and it is what a function taking the results can honestly+ give. `skip_patterns` keeps its default: omitting it is legible beside the `cast_state_dict` that+ omits it too, which is the only seam that does.Returns the bytes asked for, so a caller can log or assert on them."""patterns = tuple(skip_patterns)- if nvfp4_payloads and model is None:- # `predict_nvfp4_install_size` needs the model to decide which payloads stay packed. Absorbing- # that into a zero would drop a GiB-scale term without a word, which is this module's subject.- raise ValueError(- f"Cannot size {len(nvfp4_payloads)} nvfp4 payload(s) without the model they are installed "- "into; reserve after the model is built, or pass no payloads."- )+ nvfp4_bytes = 0+ if nvfp4_payloads:+ if model is None:+ # `predict_nvfp4_install_size` needs the model to decide which payloads stay packed.+ # Absorbing that into a zero would drop a GiB-scale term without a word, which is this+ # module's subject.+ raise ValueError(+ f"Cannot size {len(nvfp4_payloads)} nvfp4 payload(s) without the model they are "+ "installed into; reserve after the model is built, or pass no payloads."+ )+ nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, dtype, patterns)needed = (predict_cast_state_dict_size(@@ -96,7 +106,7 @@ def reserve_for_load(skip_patterns=patterns,scaled_layers=fp8_layers,)- + (predict_nvfp4_install_size(model, nvfp4_payloads, dtype, patterns) if nvfp4_payloads else 0)+ + nvfp4_bytes+ side_channel_bytes(fp8_layers))reserve(needed)diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.pyindex 8b41250685..32a50df156 100644--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py@@ -512,6 +512,12 @@ def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) ->The model-less prediction is exact here because it is only taken when nothing stays quantized,and that is the only case in which either step widens anything.++ It also has to cover the scales themselves. `extract_fp8_scaled_layers` recovers them eleven lines+ above this reservation and the fold consumes them immediately below, so they are resident across+ it and are no longer in the dict any prediction walks -- on an MXFP8 build that is ~0.125 B per+ weight element of decoded exponent grid. Asserted by value, because this is the one reservation in+ the series whose amount changed rather than only its position."""state_dict, _ = _scaled_fp8_checkpoint()run, config = _driver(monkeypatch, tmp_path, state_dict, observe=("dequantize_fp8_scaled",))@@ -520,3 +526,18 @@ def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) ->assert [step for step, _ in run.order] == ["dequantize_fp8_scaled"], run.orderassert all(reserved for _step, reserved in run.order), run.order++ # Counted by destination, not by source key: the conversion runs before the extraction, so a+ # fused `qkv`'s one scalar scale is recovered against each of the three projections it becomes and+ # is charged once per destination. That replication is why the count follows `destinations` here+ # exactly as it does in `_expected_reservation`, and it is a slight over-charge of the same tensor+ # -- conservative, which is the safe direction for a reservation.+ destinations = len(QUANTIZED) + 2 * 2+ recovered = destinations * torch.float32.itemsize+ widened = sum(+ tensor.nelement() * torch.bfloat16.itemsize+ for key, tensor in state_dict.items()+ if not (key.endswith(".weight_scale") or key.endswith(".input_scale"))+ )+ assert recovered > 0, "otherwise this cell could not notice the term being dropped"+ assert run.reserved[0] == widened + recovereddiff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.pyindex 4b25face3c..c22fc2363d 100644--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py@@ -174,15 +174,23 @@ def test_fp8_storage_alone_keeps_the_checkpoint_in_its_own_scaled_form(monkeypat# And the reservation is sized for what is actually held. This is the number the fix moves --# measured on the released checkpoint, 17.28 GiB down to 8.68 -- and it is what a loader that# decided the prediction's flag separately from the fold's would get wrong while every- # end-state assertion above still passed. The scale is popped out of the dict before this- # point, so only the codes and the dense remainder are charged.+ # end-state assertion above still passed.+ #+ # The scale is popped out of the dict before this point, so no prediction over the dict can see+ # it; the seam reserves through `reserve_for_load`, which is handed the recovered scales as well and+ # charges them. Four bytes here for a scalar, and 1.455 GiB on an MXFP8 build whose scales are+ # decoded exponent grids -- the reason the charge exists at all.kept_codes = before[f"{KEPT}.weight"].numel()dense = sum(tensor.numel() * torch.float32.itemsizefor key, tensor in before.items()if key != f"{KEPT}.weight" and not key.endswith(".weight_scale"))- assert run.reserved[-1] == kept_codes + dense+ recovered_scales = sum(+ tensor.numel() * tensor.element_size() for key, tensor in before.items() if key.endswith(".weight_scale")+ )+ assert recovered_scales > 0, "otherwise this cell would not notice the plan dropping the term"+ assert run.reserved[-1] == kept_codes + dense + recovered_scalesdef test_with_the_fp8_matmul_the_codes_stay_and_the_scales_are_attached(monkeypatch, tmp_path) -> None:diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.pyindex 436e4c64c9..83eccdd5ec 100644--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py@@ -195,12 +195,17 @@ def test_the_transformer_keeps_nvfp4_packed_and_scaled_fp8_only_where_something_assert entries_at_storage_cast == ([0] if mode == "fp8_storage" else [])# Counted by hand: the packed layers as stored; their biases, the fp8 layer's bias and the dense input projection at- # bf16; the fp8 weight at bf16 when folded and one byte per element when kept. The side-channel scales, recovered- # before the reservation, are not in the state dict it sizes.+ # bf16; the fp8 weight at bf16 when folded and one byte per element when kept. The side-channel scales are recovered+ # before the reservation and are no longer in the state dict it sizes -- the seam reserves through `reserve_for_load`,+ # which is handed them too and charges them. Four bytes here, for the one scalar `weight_scale`: the `input_scale` of+ # 1.0 is an uncalibrated placeholder that `_usable_input_scale` drops, so nothing is charged for it.packed = _packed_bytes(128, 64) + _packed_bytes(256, 64)fp8_weight = 128 * 64 * (COMPUTE_DTYPE.itemsize if mode == "fold" else 1)dense = (128 + 256) + 128 + (128 * 64 + 128)- loader._ram_cache.make_room.assert_called_once_with(packed + fp8_weight + dense * COMPUTE_DTYPE.itemsize)+ recovered_scale = torch.tensor(0.5).element_size()+ loader._ram_cache.make_room.assert_called_once_with(+ packed + fp8_weight + dense * COMPUTE_DTYPE.itemsize + recovered_scale+ )class _TinyQwenVL(torch.nn.Module):diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 15c65008ca..606d81e18c 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -1532,38 +1532,24 @@ class TestMalformedWeightScale:expand_weight_scale(torch.ones(32, 16), torch.full((7,), 2.0))-class TestReservationCoversTheSideChannelItHolds:- """The reservation is made *after* the side channel has been taken out of the state dict.-- `extract_fp8_scaled_layers` pops every scale key and hands back a mapping of tensors, and for an- MXFP8 layer it does more than move them: `decode_mx_block_scales` replaces the stored `uint8`- exponent grid with a float one, four times the size. That happens before the caller's- `make_room`, so those bytes are resident while the cache decides what to evict -- and they are in- no reservation, because the predictor walks the state dict they are no longer in.-- Measured on a 512x512 toy layer, per element of the weight:-- predicted (the widened bf16 weight) 2.000 B/element 524288 B- decoded grids, held for every layer at once 0.125 B/element 32768 B- per-layer fold transients (below) 12.000 B/element-- The grid is the *smallest* unreserved term, and the only one held for the whole quantized set at- once, which is why it is what this class pins: one entry per 32 weight elements, so around 1.5 GB- on Comfy-Org's 12 GB MXFP8 build.-- The per-layer term is larger *per element* and not in absolute peak. `dequantize_fp8_scaled` folds- one layer at a time, and for a block-wise grid `expand_weight_scale` `repeat_interleave`s it to the- weight's full width in float32 -- 4 B/element -- beside `weight.float()` and the float32 product,- so the peak is ~14 B/element of the *largest* layer against 2 predicted. Measured on the released- 12.6 GiB build: its largest quantized layers are 16384x6144, so ~1.21 GB for one of them, against- 1.455 GiB of grids summed over all 256. The grids are the bigger number as well as the persistent- one, which is why they are what this class pins. `int8_convrot.py:607` records the policy- that absorbs such a transient in the reservation's slack, on the grounds that "the widened set is- by construction the small one". That justification does not transfer here: a block-wise scale is- never matmul-usable (`is_matmul_usable_scale`), so for MXFP8 the widened set is every quantized- Linear in the file.-- Same class as the overshoots recorded at `z_image.py:697` and `krea2.py:588`.+class TestTheDecodeWidensTheGridOutsideThisPrediction:+ """Why this predictor cannot answer about an MXFP8 build, and what does.++ `extract_fp8_scaled_layers` pops every scale key and hands back a mapping, and for an MXFP8 layer+ it does more than move them: `decode_mx_block_scales` replaces the stored `uint8` exponent grid+ with a float32 one four times the size. That happens before the caller's `make_room`, so those+ bytes are resident while the cache decides what to evict -- and this function cannot see them,+ because it walks the state dict they have left.++ That is a property of its contract rather than a defect in it: it answers about the dict, exactly,+ and `TestPredictionIsSplitAware` pins the equality. Adding the mapping's bytes here would turn the+ answer into a peak and redden all three of those parametrizations. The question belongs to+ `reserve_for_load`, which is handed both halves; `tests/backend/quantization/test_load_plan.py`+ is where the grid is asserted to be inside the reservation.++ Kept here because the measurement is what motivates that function: on the released 12.6 GiB Krea-2+ build the grids total 1.455 GiB across 256 layers, more than the ~1.21 GB fold transient of its+ largest layer, and every seam used to omit them."""@staticmethod@@ -1574,10 +1560,9 @@ class TestReservationCoversTheSideChannelItHolds:model.add_module("lin", torch.nn.Linear(blocks * MX_BLOCK_SIZE, rows, bias=False))return sd, hints, model- def test_the_decode_widens_the_grid_before_anything_reserves_for_it(self) -> None:- """The half of the finding that is true today, so the numbers are recorded rather than- argued: the stored grid leaves the state dict and a four-times-larger one takes its place in- a mapping the predictor is handed but does not weigh."""+ def test_the_decode_widens_the_grid_and_this_prediction_does_not_see_it(self) -> None:+ """The stored grid leaves the state dict and a four-times-larger one takes its place in a+ mapping this function is handed but, by its contract, does not weigh."""sd, hints, model = self._mx_layer()stored_bytes = sd["lin.weight_scale"].nelement() * sd["lin.weight_scale"].element_size()@@ -1586,37 +1571,9 @@ class TestReservationCoversTheSideChannelItHolds:assert "lin.weight_scale" not in sdassert grid.dtype is torch.float32 and stored_bytes * 4 == grid.nelement() * grid.element_size()- # `keep_fp8=True`, which is what the seams that can receive an MX build pass. The layer is- # charged 2 B/element either way -- a block-wise scale fails `is_matmul_usable_scale` -- but- # this is the branch where `scaled_layers` and `model` are consulted at all.+ # `keep_fp8=True`, the branch where `scaled_layers` and `model` are consulted at all. The MX+ # layer is charged 2 B/element either way, because a block-wise scale is never matmul-usable.assert (predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)== sd["lin.weight"].nelement() * 2)-- @pytest.mark.xfail(- strict=True,- reason=(- "No fix for this belongs in this function as it stands. Adding the mapping's bytes "- "cannot be unconditional: whether a scale is still resident after the split depends on "- "whether its layer stayed fp8, so a flat term turns this function from 'bytes the state "- "dict will occupy' into 'peak bytes', and `TestPredictionIsSplitAware` pins the former "- "exactly -- measured: the flat term reddens all three `predicted == actual` "- "parametrizations and the under-count regression beside them. The alternative is a "- "second hand-assembled term at each of the nine call sites, beside the "- "`predict_nvfp4_install_size` each already adds by hand, which is the per-loader "- "assembly that keeps producing this class of gap. "- "Remove this marker when one object owns both the state dict and the scales recovered "- "from it and the reservation is computed from that object, so the size question cannot "- "be asked about half of the load."- ),- )- def test_the_decoded_mx_grid_is_inside_the_reservation(self) -> None:- """What the reservation should cover. Strict, so the fix cannot land without removing it."""- sd, hints, model = self._mx_layer()- layers = extract_fp8_scaled_layers(sd, layer_hints=hints)- grid = layers["lin"].weight_scale-- predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)-- assert predicted >= sd["lin.weight"].nelement() * 2 + grid.nelement() * grid.element_size()diff --git a/tests/backend/quantization/test_load_plan.py b/tests/backend/quantization/test_load_plan.pyindex bc55cdb5cc..867b3cd548 100644--- a/tests/backend/quantization/test_load_plan.py+++ b/tests/backend/quantization/test_load_plan.py@@ -64,16 +64,11 @@ class TestTheSideChannelIsCounted:"""Four bytes, counted for the same reason. A reservation that special-cased MXFP8 would beanswering about one scheme rather than about the mapping it was handed."""payload = quantize_scaled_fp8(torch.arange(32, dtype=torch.float32).reshape(4, 8))- sd = {"lin.weight": payload.codes, "lin.weight_scale": payload.scale}- layers = extract_fp8_scaled_layers(sd)- _asked_list, reserve = _asked()-- needed = reserve_for_load(- reserve, sd, torch.bfloat16, keep_fp8=False, model=_linear_model(8, 4), fp8_layers=layers, nvfp4_payloads={}- )+ layers = extract_fp8_scaled_layers({"lin.weight": payload.codes, "lin.weight_scale": payload.scale})+ # The magnitude only. What the total does with it is `TestKeepFp8IsCarried`'s subject, on+ # this same fixture, so asserting it here as well would be the same cell twice.assert side_channel_bytes(layers) == payload.scale.nelement() * payload.scale.element_size()- assert needed == 4 * 8 * torch.bfloat16.itemsize + side_channel_bytes(layers)def test_an_activation_scale_is_counted_beside_its_weight_scale(self) -> None:"""Encoder builds ship both halves, and both are resident from extraction onward."""@@ -101,7 +96,7 @@ class TestTheSideChannelIsCounted:assert layers["lin"].input_scale is Noneassert side_channel_bytes(layers) == payload.scale.nelement() * payload.scale.element_size()- layers["lin"].__dict__["weight_scale"] = 0.25 # a float, not a tensor+ layers["lin"].weight_scale = 0.25 # a float, not a tensorwith pytest.raises(AttributeError):side_channel_bytes(layers)@@ -128,17 +123,16 @@ class TestTheDictAndThePayloads:sd["other.weight"] = densemodel = _linear_model(64, 128)payloads = pop_nvfp4_layers(sd, {"lin": {"format": "nvfp4"}})- packed = sum(t.nelement() * t.element_size() for t in (payloads["lin"].weight, payloads["lin"].weight_scale))_asked_list, reserve = _asked()needed = reserve_for_load(reserve, sd, torch.bfloat16, keep_fp8=False, model=model, fp8_layers={}, nvfp4_payloads=payloads)- # The dense remainder is still in the dict and the packed layer is not, so the two terms are- # separable: a reservation that dropped either would miss this by a different amount.- assert needed > dense.nelement() * torch.bfloat16.itemsize- assert needed >= packed+ # Exact, and both terms non-zero: the dense remainder is still in the dict and the packed+ # layer is not, so dropping either changes the number. Inequalities would not have said that+ # -- `needed >= packed` alone is satisfied by the payload term on its own.+ assert needed == dense.nelement() * torch.bfloat16.itemsize + payloads["lin"].nbytes()def test_payloads_without_the_model_that_sizes_them_are_refused(self) -> None:"""`predict_nvfp4_install_size` needs the model to decide which payloads stay packed.@@ -153,7 +147,9 @@ class TestTheDictAndThePayloads:_asked_list, reserve = _asked()with pytest.raises(ValueError, match="without the model"):- reserve_for_load(reserve, sd, torch.bfloat16, keep_fp8=False, fp8_layers={}, nvfp4_payloads=payloads)+ reserve_for_load(+ reserve, sd, torch.bfloat16, keep_fp8=False, model=None, fp8_layers={}, nvfp4_payloads=payloads+ )class TestKeepFp8IsCarried: