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(model-cache): reserve the GGUF dequantization transient in every node
Alexander Eichhorn59c851290a34
diff --git a/invokeai/app/invocations/flux/flux_denoise.py b/invokeai/app/invocations/flux/flux_denoise.pyindex 120effcf1d..19f0924c94 100644--- a/invokeai/app/invocations/flux/flux_denoise.py+++ b/invokeai/app/invocations/flux/flux_denoise.py@@ -429,21 +429,22 @@ class FluxDenoiseInvocation(BaseInvocation):transformer_info = context.models.load(self.transformer.transformer)- # An `int8_tensorwise` build materializes each linear's dequantized, derotated weight- # inside `forward`, and that transient is not part of the model's resident size. Read- # from the unlocked model, before the VRAM lock the reservation applies to; zero for- # every other build.+ # An `int8_tensorwise` or GGUF build materializes each linear's dequantized weight inside+ # `forward`, and that transient is not part of the model's resident size. Read from the+ # unlocked model, before the VRAM lock the reservation applies to; zero for every other+ # build.## Passed alone because this node has no activation estimate. The cache floors the# request at `device_working_mem_gb`, so at the 3 GiB default this changes nothing --- # FLUX.1's largest quantized layer needs 252 MiB. It binds only where that floor was- # lowered, and it is what keeps the term honest if this node ever grows a real estimate+ # FLUX.1's largest quantized layer needs 252 MiB as int8 and under 1 GiB as GGUF. It binds+ # only where that floor was lowered, and it is what keeps the term honest if this node ever+ # grows a real estimate# (the transient is alive alongside the activations, as it is for FLUX.2 and Krea-2).- int8_dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)+ dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)# Load the transformer model.(cached_weights, transformer) = exit_stack.enter_context(- transformer_info.model_on_device(working_mem_bytes=int8_dequant_bytes)+ transformer_info.model_on_device(working_mem_bytes=dequant_bytes))assert isinstance(transformer, Flux)config = transformer_configdiff --git a/invokeai/app/invocations/flux2/flux2_denoise.py b/invokeai/app/invocations/flux2/flux2_denoise.pyindex b8470746e1..a874c8101f 100644--- a/invokeai/app/invocations/flux2/flux2_denoise.py+++ b/invokeai/app/invocations/flux2/flux2_denoise.py@@ -569,16 +569,16 @@ class Flux2DenoiseInvocation(BaseInvocation):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.+ # An `int8_tensorwise` or GGUF 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_dequant_transient_bytes(transformer_info.model, inference_dtype)+ dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)# Load the transformer model(cached_weights, transformer) = exit_stack.enter_context(- transformer_info.model_on_device(working_mem_bytes=estimated_working_memory + int8_dequant_bytes)+ transformer_info.model_on_device(working_mem_bytes=estimated_working_memory + dequant_bytes))config = transformer_config@@ -730,8 +730,9 @@ class Flux2DenoiseInvocation(BaseInvocation):references adds 12288 more for ~6.5GB, and a 1328px tile with three 1328px references reaches~10.9GB -- against a default ``device_working_mem_gb`` of 3.- A fixed base covers resolution-independent overhead (transient fp8/GGUF -> bf16 weight casts- during the forward, and allocator slack across many steps). LoRA sidecar patches add an extra+ A fixed base covers resolution-independent overhead (transient fp8 -> bf16 weight casts during+ the forward, and allocator slack across many steps); the dequantization copy of an int8 or GGUF+ build is added by the caller. LoRA sidecar patches add an extraactivation branch per patched layer, so we add a per-LoRA margin.Batch multiplies the token count and nothing else. A batch of B is B independent sequences,diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex e079d0b6f7..fda4f044bb 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -23,7 +23,6 @@ from invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPairfrom invokeai.backend.model_manager.load.load_base import LoadedModelfrom invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes-from invokeai.backend.quantization.gguf.ggml_tensor import peak_ggml_linear_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Ideogram4ConditioningInfofrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.fp8 import get_model_compute_dtype@@ -248,14 +247,11 @@ class Ideogram4DenoiseInvocation(BaseInvocation):materialize the dequantized weight inside `forward`, so that peak is not part of the model'sresident size and has to fit inside the caller's reservation. Zero for a bf16 or fp8 build --which is why it is measured from the model rather than from the resolution: the two branches- are separate models and may be different builds. A model holds one scheme or the other.+ are separate models and may be different builds."""if not isinstance(model, torch.nn.Module):return 0- return max(- peak_dequant_transient_bytes(model, get_model_compute_dtype(model)),- peak_ggml_linear_dequant_transient_bytes(model),- )+ return peak_dequant_transient_bytes(model, get_model_compute_dtype(model))def _load_branches(self, context: InvocationContext, stack: ExitStack, working_mem_bytes: intdiff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.pyindex d9aca4e851..53874e4e11 100644--- a/invokeai/app/invocations/krea2/krea2_denoise.py+++ b/invokeai/app/invocations/krea2/krea2_denoise.py@@ -578,8 +578,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):device=device,dtype=inference_dtype,)- # An int8_tensorwise build stores its linears quantized and materializes the dequantized,- # derotated weight per forward call. That transient is alive alongside the activations above,+ # An int8_tensorwise or GGUF build stores its linears quantized and materializes the dequantized+ # weight per forward call. That transient is alive alongside the activations above,# so it is added rather than compared -- and it is invisible to an activation estimate, which# is how a model that loaded comfortably OOMs in its first step. Zero for any other format.estimated_working_memory += peak_dequant_transient_bytes(transformer_info.model, inference_dtype)diff --git a/invokeai/app/invocations/qwen_image/qwen_image_denoise.py b/invokeai/app/invocations/qwen_image/qwen_image_denoise.pyindex 3cd1d89717..a0b4623422 100644--- a/invokeai/app/invocations/qwen_image/qwen_image_denoise.py+++ b/invokeai/app/invocations/qwen_image/qwen_image_denoise.py@@ -458,9 +458,10 @@ class QwenImageDenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):noisy_seq_len = latents.shape[1]transformer_config = context.models.get_config(self.transformer.transformer)- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not cover. The- # cache holds back the larger of this and its default working memory, not their sum: this node has no- # activation estimate to add it to. Read from the unlocked model, before the lock; zero for every other build.+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does not+ # cover. The cache holds back the larger of this and its default working memory, not their sum: this node has+ # no activation estimate to add it to. Read from the unlocked model, before the lock; zero for every other+ # build.dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)with ExitStack() as exit_stack:diff --git a/invokeai/app/invocations/text_encoder/anima_text_encoder.py b/invokeai/app/invocations/text_encoder/anima_text_encoder.pyindex 3647a766c7..45df2e6fa7 100644--- a/invokeai/app/invocations/text_encoder/anima_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/anima_text_encoder.py@@ -140,7 +140,7 @@ class AnimaTextEncoderInvocation(BaseInvocation):text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does not# cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_anima_inference_dtype(text_encoder_info.compute_device)diff --git a/invokeai/app/invocations/text_encoder/ernie_image_text_encoder.py b/invokeai/app/invocations/text_encoder/ernie_image_text_encoder.pyindex 476294b063..d848dd8796 100644--- a/invokeai/app/invocations/text_encoder/ernie_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/ernie_image_text_encoder.py@@ -13,10 +13,12 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import Mistral3EncoderFieldfrom invokeai.app.invocations.primitives import ErnieImageConditioningOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,ErnieImageConditioningInfo,)+from invokeai.backend.util.devices import TorchDevice@invocation(@@ -61,8 +63,15 @@ class ErnieImageTextEncoderInvocation(BaseInvocation):text_encoder_info = context.models.load(self.text_encoder.text_encoder)tokenizer_info = context.models.load(self.text_encoder.tokenizer)+ # A GGUF build dequantizes each Linear per forward, a transient its resident size does not cover;+ # zero for other builds.+ dequant_bytes = peak_dequant_transient_bytes(+ text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)+ )with ExitStack() as exit_stack:- (_, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())+ (_, text_encoder) = exit_stack.enter_context(+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)+ )(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())if not isinstance(text_encoder, PreTrainedModel):diff --git a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.pyindex da8cd02189..c7e32565cc 100644--- a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py@@ -131,7 +131,7 @@ class Flux2DevTextEncoderInvocation(BaseInvocation):def _encode_prompt(self, context: InvocationContext, exit_stack: ExitStack) -> torch.Tensor:text_encoder_info = context.models.load(self.mistral_encoder.text_encoder)text_encoder_format = context.models.get_config(self.mistral_encoder.text_encoder).format- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does not# cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)diff --git a/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py b/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.pyindex 1e7f15266e..543eeb6012 100644--- a/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py@@ -104,7 +104,7 @@ class Flux2KleinTextEncoderInvocation(BaseInvocation):# This prevents it from being evicted while we look up the tokenizertext_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does not# cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)diff --git a/invokeai/app/invocations/text_encoder/flux_text_encoder.py b/invokeai/app/invocations/text_encoder/flux_text_encoder.pyindex 3572106bf3..fab327fe71 100644--- a/invokeai/app/invocations/text_encoder/flux_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/flux_text_encoder.py@@ -21,7 +21,9 @@ from invokeai.backend.model_manager.taxonomy import ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_CLIP_PREFIX, FLUX_LORA_T5_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, FLUXConditioningInfo+from invokeai.backend.util.devices import TorchDevice@invocation(@@ -81,8 +83,13 @@ class FluxTextEncoderInvocation(BaseInvocation):t5_encoder_config = t5_encoder_info.configassert t5_encoder_config is not None+ # A GGUF build dequantizes each Linear per forward, a transient its resident size does not cover;+ # zero for other builds.+ dequant_bytes = peak_dequant_transient_bytes(+ t5_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(t5_encoder_info.compute_device)+ )with (- t5_encoder_info.model_on_device() as (cached_weights, t5_text_encoder),+ t5_encoder_info.model_on_device(working_mem_bytes=dequant_bytes) as (cached_weights, t5_text_encoder),context.models.load(self.t5_encoder.tokenizer) as t5_tokenizer,ExitStack() as exit_stack,):diff --git a/invokeai/app/invocations/text_encoder/ideogram4_text_encoder.py b/invokeai/app/invocations/text_encoder/ideogram4_text_encoder.pyindex 9ca08640f1..0bc68cc647 100644--- a/invokeai/app/invocations/text_encoder/ideogram4_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/ideogram4_text_encoder.py@@ -8,10 +8,12 @@ from invokeai.app.invocations.model import Qwen3EncoderFieldfrom invokeai.app.invocations.primitives import Ideogram4ConditioningOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.ideogram4.text_encoding import encode_qwen3vl_prompt+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,Ideogram4ConditioningInfo,)+from invokeai.backend.util.devices import TorchDevice@invocation(@@ -45,8 +47,15 @@ class Ideogram4TextEncoderInvocation(BaseInvocation):text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)+ # A GGUF build dequantizes each Linear per forward, a transient its resident size does not cover;+ # zero for other builds.+ dequant_bytes = peak_dequant_transient_bytes(+ text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)+ )with ExitStack() as exit_stack:- (_, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())+ (_, text_encoder) = exit_stack.enter_context(+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)+ )(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())context.util.signal_progress("Running Qwen3-VL text encoder")diff --git a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py b/invokeai/app/invocations/text_encoder/krea2_text_encoder.pyindex 481dbfc01b..e6b807faf4 100644--- a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/krea2_text_encoder.py@@ -81,7 +81,7 @@ class Krea2TextEncoderInvocation(BaseInvocation):tokenizer_info = context.models.load(self.qwen3_vl_encoder.tokenizer)text_encoder_info = context.models.load(self.qwen3_vl_encoder.text_encoder)text_encoder_format = context.models.get_config(self.qwen3_vl_encoder.text_encoder).format- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does# not cover. Read from the unlocked model, before the lock the reservation applies to; zero for# other builds.dequant_bytes = peak_dequant_transient_bytes(diff --git a/invokeai/app/invocations/text_encoder/sd3_text_encoder.py b/invokeai/app/invocations/text_encoder/sd3_text_encoder.pyindex 5be404d07e..5cd7aaee65 100644--- a/invokeai/app/invocations/text_encoder/sd3_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/sd3_text_encoder.py@@ -19,7 +19,9 @@ from invokeai.backend.model_manager.taxonomy import ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_CLIP_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, SD3ConditioningInfo+from invokeai.backend.util.devices import TorchDevice# The SD3 T5 Max Sequence Length set based on the default in diffusers.SD3_T5_MAX_SEQ_LEN = 256@@ -97,8 +99,13 @@ class Sd3TextEncoderInvocation(BaseInvocation):prompt = [self.prompt]t5_text_encoder_info = context.models.load(self.t5_encoder.text_encoder)+ # A GGUF build dequantizes each Linear per forward, a transient its resident size does not cover;+ # zero for other builds.+ dequant_bytes = peak_dequant_transient_bytes(+ t5_text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(t5_text_encoder_info.compute_device)+ )with (- t5_text_encoder_info as t5_text_encoder,+ t5_text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes) as (_, t5_text_encoder),context.models.load(self.t5_encoder.tokenizer) as t5_tokenizer,):context.util.signal_progress("Running T5 encoder")diff --git a/invokeai/app/invocations/text_encoder/z_image_text_encoder.py b/invokeai/app/invocations/text_encoder/z_image_text_encoder.pyindex 9c5541627c..110c90db34 100644--- a/invokeai/app/invocations/text_encoder/z_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/z_image_text_encoder.py@@ -77,7 +77,7 @@ class ZImageTextEncoderInvocation(BaseInvocation):text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format- # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not+ # An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does not# cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)diff --git a/invokeai/app/invocations/wan/wan_denoise.py b/invokeai/app/invocations/wan/wan_denoise.pyindex 85e7e0c2fe..fbf78e687e 100644--- a/invokeai/app/invocations/wan/wan_denoise.py+++ b/invokeai/app/invocations/wan/wan_denoise.py@@ -48,6 +48,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat,from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.wan_lora_constants import WAN_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import WanConditioningInfo@@ -255,7 +256,11 @@ class _ExpertSwapper:info = self._context.models.load(model_id)supports_partial_loading = getattr(info, "supports_partial_loading", None)if self._working_mem_bytes is None or supports_partial_loading is False:- device_ctx = info.model_on_device()+ # No estimate to add it to, so a GGUF expert's per-forward dequantization transient is passed+ # alone; the cache floors it at `device_working_mem_gb`, so zero asks for the default.+ device_ctx = info.model_on_device(+ working_mem_bytes=peak_dequant_transient_bytes(info.model, self._inference_dtype)+ )else:device_ctx = info.model_on_device(working_mem_bytes=self._working_mem_bytes)cached_weights, model = device_ctx.__enter__()diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.pyindex 5894899b87..66623c3058 100644--- a/invokeai/app/invocations/z_image/z_image_denoise.py+++ b/invokeai/app/invocations/z_image/z_image_denoise.py@@ -322,7 +322,8 @@ class ZImageDenoiseInvocation(BaseInvocation):and 3.85 GiB at 2048px (16896) -- 0.22 to 0.23 MB per token, unchanged between 2 and 4 blocks, because ano-grad forward frees each block's intermediates. 0.25 MB per token bounds every point on its own, withroom for the ~5% more ROCm needed on FLUX.2. The fixed base covers what does not scale with the sequence- -- GGUF and fp8 weights cast per forward, and allocator slack across steps. Conditional and unconditional+ -- fp8 weights cast per forward, and allocator slack across steps; the caller adds the dequantization copy+ of an int8, nvfp4 or GGUF build. Conditional and unconditionalpasses run one after the other, so only the longer caption counts.Where SDPA has no fused kernel for these shapes it materializes the score matrices, and those dominate:@@ -565,7 +566,7 @@ class ZImageDenoiseInvocation(BaseInvocation):device=device,dtype=inference_dtype,)- # An int8_tensorwise or nvfp4 build materializes each quantized linear's weight per forward, alive+ # An int8_tensorwise, nvfp4 or GGUF build materializes each quantized linear's weight per forward, alive# alongside the activations above and invisible to them. Read from the unlocked model; zero for# every other build.working_mem_bytes += peak_dequant_transient_bytes(transformer_info.model, inference_dtype)diff --git a/invokeai/backend/quantization/dequantizing_linear.py b/invokeai/backend/quantization/dequantizing_linear.pyindex 9ae2bf3ee9..7df692a7bb 100644--- a/invokeai/backend/quantization/dequantizing_linear.py+++ b/invokeai/backend/quantization/dequantizing_linear.py@@ -1,10 +1,11 @@"""Linears that keep their weight quantized in buffers and materialize it on every forward.-Two schemes store their Linears this way, ``int8_convrot`` and ``nvfp4``, and the code around them-needs the same two answers about either: whether a LoRA has to ride along as a sidecar, and how much-memory one forward needs on top of the model's resident size. Both are asked of the loaded module tree,-so they live here beside the base class the modules share rather than inside either scheme -- a new-scheme answers them by subclassing instead of every caller learning its name.+Two schemes store their Linears this way, ``int8_convrot`` and ``nvfp4``; GGUF keeps a plain Linear but+packs its weight in a ``GGMLTensor`` and dequantizes it per forward just the same. The code around them+needs the same two answers about any of these: whether a LoRA has to ride along as a sidecar, and how+much memory one forward needs on top of the model's resident size. Both are asked of the loaded module+tree and live here, so callers ask once for every scheme: a module-level scheme answers by subclassing,+GGUF -- whose quantization lives on the weight, not the module -- is delegated to."""import abc@@ -14,6 +15,7 @@ import torchimport torch.nn.functional as Ffrom invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.quantization.gguf.ggml_tensor import peak_ggml_linear_dequant_transient_bytesclass DequantizingLinear(torch.nn.Module, abc.ABC):@@ -67,15 +69,17 @@ def requires_sidecar_patching(model: Any, model_format: ModelFormat) -> bool:def peak_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:"""Peak bytes one forward transiently needs to dequantize this model's quantized linears.- A :class:`DequantizingLinear` materializes its weight per forward, so that allocation is not covered- by the model's resident size and has to fit inside the calling node's working-memory reservation. The- layers run one after another and free their weight before the next one allocates, so the peak is the- largest single layer's transient. Zero when the model holds no such layer.+ A :class:`DequantizingLinear` materializes its weight per forward, and so does a Linear whose weight+ is a GGUF ``GGMLTensor`` (see :func:`peak_ggml_linear_dequant_transient_bytes`), so that allocation is+ not covered by the model's resident size and has to fit inside the calling node's working-memory+ reservation. The layers run one after another and free their weight before the next one allocates, so+ the peak is the largest single layer's transient. Zero when the model holds no such layer.+ ``compute_dtype`` applies to the module-level schemes; a GGUF weight carries its own.Not covered: the matmul's own cuBLAS workspace, which a dense Linear of the same shape allocates tooand which a node's activation estimate already includes."""- return max(+ dequantizing = max((module.dequant_transient_bytes(compute_dtype)for module in model.modules()@@ -83,3 +87,4 @@ def peak_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dt),default=0,)+ return max(dequantizing, peak_ggml_linear_dequant_transient_bytes(model))diff --git a/invokeai/backend/quantization/gguf/ggml_tensor.py b/invokeai/backend/quantization/gguf/ggml_tensor.pyindex 04351bbaa7..7bb5532194 100644--- a/invokeai/backend/quantization/gguf/ggml_tensor.py+++ b/invokeai/backend/quantization/gguf/ggml_tensor.py@@ -1,3 +1,4 @@+import mathfrom typing import overloadimport gguf@@ -204,10 +205,27 @@ class GGMLTensor(torch.Tensor):# What one dequantization allocates beyond its result, per weight element: the block kernels in# `utils.py` widen codes and scales through integer and float16 intermediates before the final cast.-# Measured on CUDA (torch 2.13) for a 4608x53248 weight: about 2 bytes for Q8_0 and Q4_0, 3 for Q4_K-# and Q6_K, 5 for Q5_K, 6 for BF16 and 8 for Q5_1. The host-side counterpart, for decoding a whole tensor-# at load, is `_PEAK_COPIES` in `model_manager/load/quantized_embedding.py`.-_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT = 8+# Measured on CUDA (torch 2.13) for a 4608x53248 weight and rounded up; F32/F16 are a plain cast. Types+# not listed (the IQ family decodes through the numpy fallback) get the worst measured value. The+# host-side counterpart, for decoding a whole tensor at load, is `_PEAK_COPIES` in+# `model_manager/load/quantized_embedding.py`.+_GGMLQ = gguf.GGMLQuantizationType+_DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT: dict[gguf.GGMLQuantizationType, float] = {+ _GGMLQ.F32: 0.05,+ _GGMLQ.F16: 0.0,+ _GGMLQ.Q8_0: 2.0,+ _GGMLQ.Q4_0: 2.0,+ _GGMLQ.Q4_1: 3.0,+ _GGMLQ.Q6_K: 3.25,+ _GGMLQ.Q4_K: 3.25,+ _GGMLQ.Q2_K: 3.25,+ _GGMLQ.Q3_K: 3.5,+ _GGMLQ.Q5_K: 5.25,+ _GGMLQ.BF16: 6.0,+ _GGMLQ.Q5_0: 8.0,+ _GGMLQ.Q5_1: 8.0,+}+_DEQUANT_INTERMEDIATE_BYTES_WORST = 8.0def peak_ggml_linear_dequant_transient_bytes(model: torch.nn.Module) -> int:@@ -217,13 +235,19 @@ def peak_ggml_linear_dequant_transient_bytes(model: torch.nn.Module) -> int:which is not part of the model's resident size and so has to fit inside the calling node'sworking-memory reservation. The layers run one after another and free their copy before thenext one allocates, so the peak is the largest single layer's: its dequantized copy, the kernels'- intermediates, and the packed bytes, which partial loading copies to the device for the call.- Zero when no Linear weight is packed.+ intermediates for its quantization type, and the packed bytes, which partial loading copies to+ the device for the call. Zero when no Linear weight is packed."""peak = 0for module in model.modules():- weight = getattr(module, "weight", None)- if isinstance(module, torch.nn.Linear) and isinstance(weight, GGMLTensor):- per_element = weight.compute_dtype.itemsize + _DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT- peak = max(peak, weight.tensor_shape.numel() * per_element + weight.quantized_data.nbytes)+ if not isinstance(module, torch.nn.Linear):+ continue+ weight = module.weight+ if not isinstance(weight, GGMLTensor):+ continue+ intermediates = _DEQUANT_INTERMEDIATE_BYTES_PER_ELEMENT.get(+ weight._ggml_quantization_type, _DEQUANT_INTERMEDIATE_BYTES_WORST+ )+ per_element = weight.compute_dtype.itemsize + intermediates+ peak = max(peak, math.ceil(weight.tensor_shape.numel() * per_element) + weight.quantized_data.nbytes)return peakdiff --git a/tests/app/invocations/test_sd3_text_encoder.py b/tests/app/invocations/test_sd3_text_encoder.pyindex ff68e0332f..8cbcf10275 100644--- a/tests/app/invocations/test_sd3_text_encoder.py+++ b/tests/app/invocations/test_sd3_text_encoder.py@@ -80,8 +80,12 @@ class FakeLoadedModel:def compute_device(self) -> torch.device:return self._compute_device+ @property+ def model(self):+ return self._model+@contextmanager- def model_on_device(self):+ def model_on_device(self, working_mem_bytes=None):yield (None, self._model)def __enter__(self):diff --git a/tests/app/invocations/test_text_encoders_with_packed_layers.py b/tests/app/invocations/test_text_encoders_with_packed_layers.pyindex 116ce4407b..9da3802710 100644--- a/tests/app/invocations/test_text_encoders_with_packed_layers.py+++ b/tests/app/invocations/test_text_encoders_with_packed_layers.py@@ -1,5 +1,5 @@"""The text-encoder nodes have to treat a quantized encoder the way the denoise nodes treat a quantized transformer:-reserve working memory for the per-forward dequantization of packed nvfp4 Linears, and apply LoRA as a sidecar+reserve working memory for the per-forward dequantization of packed nvfp4 and GGUF Linears, and apply LoRA as a sidecarwherever a direct patch cannot write the weights -- packed nvfp4 Linears, and GGUF or SDNQ encoders, which the denoisenodes already patch this way. The three Qwen3 nodes load through the Qwen3 loader and the FLUX.2 [dev] node throughthe Mistral loader, and both keep Comfy's fp4_mixed files packed, so each node receives a packed encoder as soon as@@ -10,15 +10,22 @@ from contextlib import ExitStack, contextmanagerfrom types import SimpleNamespacefrom unittest.mock import MagicMock+import gguf+import numpy as npimport pytestimport torchfrom invokeai.app.invocations.text_encoder.anima_text_encoder import AnimaTextEncoderInvocation+from invokeai.app.invocations.text_encoder.ernie_image_text_encoder import ErnieImageTextEncoderInvocationfrom invokeai.app.invocations.text_encoder.flux2_dev_text_encoder import Flux2DevTextEncoderInvocationfrom invokeai.app.invocations.text_encoder.flux2_klein_text_encoder import Flux2KleinTextEncoderInvocation+from invokeai.app.invocations.text_encoder.flux_text_encoder import FluxTextEncoderInvocation+from invokeai.app.invocations.text_encoder.ideogram4_text_encoder import Ideogram4TextEncoderInvocation+from invokeai.app.invocations.text_encoder.sd3_text_encoder import Sd3TextEncoderInvocationfrom invokeai.app.invocations.text_encoder.z_image_text_encoder import ZImageTextEncoderInvocationfrom invokeai.backend.model_manager.taxonomy import ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear@@ -26,26 +33,41 @@ class _StopAtPatching(Exception):"""Raised from the patched `apply_smart_model_patches`, so the node stops right where it has decided."""+class _StopOnDevice(Exception):+ """Raised once the encoder is put on the device: the reservation is decided by then."""++class _LoadedModel:- def __init__(self, model: object) -> None:+ def __init__(self, model: object, model_format: ModelFormat = ModelFormat.Checkpoint) -> None:self.model = model+ self.config = SimpleNamespace(format=model_format)self.compute_device = torch.device("cpu")self.working_mem_bytes: int | None = None+ self.stop_on_device = False@contextmanagerdef model_on_device(self, working_mem_bytes: int | None = None):self.working_mem_bytes = working_mem_bytes+ if self.stop_on_device:+ raise _StopOnDeviceyield (None, self.model)def repair_required_tensors_on_device(self) -> int:return 0-def _encoder(packed: bool) -> torch.nn.Module:+def _encoder(kind: str) -> torch.nn.Module:encoder = torch.nn.Module()- if packed:+ if kind == "nvfp4":weight = torch.zeros(128, 32, dtype=torch.uint8)encoder.proj = NVFP4Linear(weight, torch.ones(128, 4).to(torch.float8_e4m3fn), torch.tensor(1.0))+ elif kind == "gguf":+ encoder.proj = torch.nn.Linear(64, 128, bias=False)+ raw = gguf.quantize(np.zeros((128, 64), np.float32), gguf.GGMLQuantizationType.Q8_0)+ encoder.proj.weight = torch.nn.Parameter(+ GGMLTensor(torch.from_numpy(raw), gguf.GGMLQuantizationType.Q8_0, torch.Size((128, 64)), torch.bfloat16),+ requires_grad=False,+ )else:encoder.proj = torch.nn.Linear(64, 128)return encoder@@ -73,11 +95,11 @@ NODES = {@pytest.mark.parametrize(- ("packed", "model_format", "sidecar", "working_memory"),+ ("kind", "model_format", "sidecar", "working_memory"),[- (True, ModelFormat.Checkpoint, True, True),- (False, ModelFormat.Checkpoint, False, False),- (False, ModelFormat.GGUFQuantized, True, False),+ ("nvfp4", ModelFormat.Checkpoint, True, True),+ ("dense", ModelFormat.Checkpoint, False, False),+ ("gguf", ModelFormat.GGUFQuantized, True, True),],ids=["nvfp4_checkpoint", "dense_checkpoint", "gguf"],)@@ -85,13 +107,13 @@ NODES = {def test_the_node_reserves_the_dequant_transient_and_patches_quantized_encoders_as_sidecars(monkeypatch: pytest.MonkeyPatch,node_name: str,- packed: bool,+ kind: str,model_format: ModelFormat,sidecar: bool,working_memory: bool,) -> None:invocation_class, encoder_field, encode = NODES[node_name]- encoder = _LoadedModel(_encoder(packed))+ encoder = _LoadedModel(_encoder(kind))context = MagicMock()context.models.load.side_effect = [encoder, _LoadedModel(object())]context.models.get_config.return_value = SimpleNamespace(format=model_format)@@ -117,17 +139,17 @@ def test_the_node_reserves_the_dequant_transient_and_patches_quantized_encoders_@pytest.mark.parametrize(- ("packed", "model_format", "sidecar", "working_memory"),+ ("kind", "model_format", "sidecar", "working_memory"),[- (True, ModelFormat.Checkpoint, True, True),- (False, ModelFormat.Checkpoint, False, False),- (False, ModelFormat.GGUFQuantized, True, False),+ ("nvfp4", ModelFormat.Checkpoint, True, True),+ ("dense", ModelFormat.Checkpoint, False, False),+ ("gguf", ModelFormat.GGUFQuantized, True, True),],ids=["nvfp4_checkpoint", "dense_checkpoint", "gguf"],)def test_the_krea2_node_reserves_the_dequant_transient_and_patches_quantized_encoders_as_sidecars(monkeypatch: pytest.MonkeyPatch,- packed: bool,+ kind: str,model_format: ModelFormat,sidecar: bool,working_memory: bool,@@ -154,7 +176,7 @@ def test_the_krea2_node_reserves_the_dequant_transient_and_patches_quantized_encdef __exit__(self, *_exc):return False- encoder = _LoadedModel(_encoder(packed))+ encoder = _LoadedModel(_encoder(kind))context = MagicMock()# The node loads the tokenizer first, then the encoder.context.models.load.side_effect = [_LoadedTokenizer(), encoder]@@ -177,3 +199,51 @@ def test_the_krea2_node_reserves_the_dequant_transient_and_patches_quantized_encassert patching["force_sidecar_patching"] is sidecarassert bool(encoder.working_mem_bytes) is working_memory+++# Nodes that reached a GGUF encoder without asking for its transient at all: (node class, how its+# encoder field is filled, how its encode step is called).+GGUF_ONLY_NODES = {+ "flux_t5": (+ FluxTextEncoderInvocation,+ {"t5_encoder": SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[])},+ lambda node, context: node._t5_encode(context),+ ),+ "sd3_t5": (+ Sd3TextEncoderInvocation,+ {"t5_encoder": SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace())},+ lambda node, context: node._t5_encode(context, 16),+ ),+ "ideogram4": (+ Ideogram4TextEncoderInvocation,+ {"qwen3_encoder": SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace())},+ lambda node, context: node.invoke(context),+ ),+ "ernie_image": (+ ErnieImageTextEncoderInvocation,+ {"text_encoder": SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace())},+ lambda node, context: node._encode_prompt(context, "a prompt"),+ ),+}++[email protected]("kind", ["gguf", "dense"])[email protected]("node_name", list(GGUF_ONLY_NODES))+def test_a_gguf_encoder_reserves_its_dequant_transient(node_name: str, kind: str) -> None:+ """The reservation is decided when the encoder is put on the device, before any encoding."""+ invocation_class, fields, encode = GGUF_ONLY_NODES[node_name]+ model_format = ModelFormat.GGUFQuantized if kind == "gguf" else ModelFormat.Checkpoint+ encoder = _LoadedModel(_encoder(kind), model_format)+ encoder.stop_on_device = True+ context = MagicMock()+ context.models.load.side_effect = [encoder, _LoadedModel(object())]+ node = invocation_class.model_construct(prompt="a prompt", t5_max_seq_len=512, **fields)++ with pytest.raises(_StopOnDevice):+ encode(node, context)++ if kind == "gguf":+ # At least the bfloat16 copy of the one packed 128x64 weight.+ assert encoder.working_mem_bytes is not None and encoder.working_mem_bytes > 128 * 64 * 2+ else:+ assert not encoder.working_mem_bytesdiff --git a/tests/app/invocations/test_wan_denoise.py b/tests/app/invocations/test_wan_denoise.pyindex 9dbaef7f79..f3846663ca 100644--- a/tests/app/invocations/test_wan_denoise.py+++ b/tests/app/invocations/test_wan_denoise.py@@ -16,6 +16,8 @@ from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom unittest.mock import MagicMock+import gguf+import numpy as npimport pytestimport torchimport torch.nn as nn@@ -30,6 +32,7 @@ from invokeai.app.invocations.wan.wan_denoise import (from invokeai.app.invocations.wan.wan_ref_image_encoder import WanRefImageEncoderInvocationfrom invokeai.app.invocations.wan.wan_video_denoise import WanVideoDenoiseInvocationfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, WanVariantType+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,WanConditioningInfo,@@ -92,7 +95,7 @@ def _model_on_device_ctx(model: nn.Module):def _make_loaded_model(model: nn.Module) -> MagicMock:"""Mock ``LoadedModel`` exposing only the methods the denoise loop touches."""loaded = MagicMock()- loaded.model_on_device = lambda: _model_on_device_ctx(model)+ loaded.model_on_device = lambda working_mem_bytes=None: _model_on_device_ctx(model)return loaded@@ -311,6 +314,50 @@ class TestWanDenoiseShapes:loaded.model_on_device.assert_called_once_with(working_mem_bytes=working_mem_bytes)loaded.unload_from_vram.assert_called_once_with(3 * 2**30, keep_required_weights_in_vram=True)+ @pytest.mark.parametrize("packed", [True, False], ids=["gguf", "dense"])+ def test_expert_swapper_reserves_a_gguf_experts_dequant_transient(self, packed: bool) -> None:+ """Without the aggressive budget there is no estimate, so a GGUF expert's per-forward+ dequantization copy is the whole request; a dense expert asks for nothing beyond the default."""+ transformer = _ZeroTransformer()+ linear = torch.nn.Linear(256, 512, bias=False)+ if packed:+ raw = gguf.quantize(np.zeros((512, 256), np.float32), gguf.GGMLQuantizationType.Q8_0)+ linear.weight = torch.nn.Parameter(+ GGMLTensor(torch.from_numpy(raw), gguf.GGMLQuantizationType.Q8_0, linear.weight.shape, torch.bfloat16),+ requires_grad=False,+ )+ loaded = MagicMock()+ loaded.model = torch.nn.Sequential(linear)+ loaded.supports_partial_loading = True+ loaded.resident_weight_bytes = 0+ loaded.weight_bytes = 0+ device_context = MagicMock()+ device_context.__enter__.return_value = (None, transformer)+ loaded.model_on_device.return_value = device_context+ context = MagicMock()+ context.models.load.return_value = loaded+ swapper = _ExpertSwapper(+ context=context,+ high_model=MagicMock(),+ low_model=None,+ inference_dtype=torch.bfloat16,+ working_mem_bytes=None,+ max_resident_model_bytes=2 * 2**30,+ )++ try:+ swapper.get(_ExpertSwapper.HIGH)+ finally:+ swapper.close()++ ((), kwargs) = loaded.model_on_device.call_args+ if packed:+ # At least the bfloat16 copy of the weight it dequantizes on every forward.+ assert kwargs["working_mem_bytes"] > 512 * 256 * torch.bfloat16.itemsize+ else:+ # Zero, which the cache reads as its default working memory.+ assert kwargs["working_mem_bytes"] == 0+def test_expert_swapper_does_not_trim_when_residency_is_already_targeted(self) -> None:transformer = _ZeroTransformer()loaded = MagicMock()@@ -363,7 +410,9 @@ class TestWanDenoiseShapes:finally:swapper.close()- loaded.model_on_device.assert_called_once_with()+ # Not the aggressive budget: without partial loading the expert asks only for its own (here zero)+ # dequantization transient, which the cache reads as its default working memory.+ loaded.model_on_device.assert_called_once_with(working_mem_bytes=0)loaded.unload_from_vram.assert_not_called()context.logger.warning.assert_called_once()diff --git a/tests/app/invocations/test_wan_expert_swapper.py b/tests/app/invocations/test_wan_expert_swapper.pyindex 140fbff79b..2ad62ffa94 100644--- a/tests/app/invocations/test_wan_expert_swapper.py+++ b/tests/app/invocations/test_wan_expert_swapper.py@@ -80,7 +80,11 @@ class _FakeInfo:self.weight_bytes = 0self.resident_weight_bytes = 0- def model_on_device(self):+ @property+ def model(self) -> nn.Module:+ return self._model++ def model_on_device(self, working_mem_bytes=None):return _FakeModelOnDevice(self._label, self._model, self._log)def unload_from_vram(self, _vram_bytes_to_free, keep_required_weights_in_vram=False):@@ -628,7 +632,7 @@ def test_slots_cleared_when_device_exit_raises():raise RuntimeError("device teardown blew up")class _ExitRaisingInfo(_FakeInfo):- def model_on_device(self):+ def model_on_device(self, working_mem_bytes=None):return _ExitRaisingDeviceCtx(self._label, self._model, self._log)ctx = _FakeContext({"high": _ExitRaisingInfo("HIGH", high_nn, log)}, log)diff --git a/tests/backend/quantization/gguf/test_ggml_tensor.py b/tests/backend/quantization/gguf/test_ggml_tensor.pyindex 01c3aae646..32b1d537fb 100644--- a/tests/backend/quantization/gguf/test_ggml_tensor.py+++ b/tests/backend/quantization/gguf/test_ggml_tensor.py@@ -152,3 +152,41 @@ def test_ggml_tensor_numpy_fallback_dequantize_uses_logical_shape():)assert t.get_dequantized_tensor().shape == logical_shape+++def _gguf_linear(in_features: int, out_features: int) -> torch.nn.Linear:+ linear = torch.nn.Linear(in_features, out_features, bias=False)+ linear.weight = torch.nn.Parameter(+ quantize_tensor(torch.zeros(out_features, in_features), gguf.GGMLQuantizationType.Q8_0), requires_grad=False+ )+ return linear+++def test_the_shared_dequant_transient_counts_gguf_linears():+ """Every denoise and encoder node sizes its reservation with `peak_dequant_transient_bytes`, so a GGUF+ Linear -- dequantized into a full copy on every forward -- has to count there, as an int8 one does.+ It is the largest layer that counts, whichever scheme it uses, since the layers run one at a time."""+ from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes+ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear++ gguf_model = torch.nn.Sequential(_gguf_linear(64, 128), _gguf_linear(64, 32))+ largest = gguf_model[0].weight+ gguf_peak = peak_dequant_transient_bytes(gguf_model, torch.float32)++ # At least the copy of the larger layer, in the weight's own compute dtype, plus its packed bytes;+ # never the sum of both layers.+ assert gguf_peak > largest.tensor_shape.numel() * largest.compute_dtype.itemsize + largest.quantized_data.nbytes+ assert gguf_peak == peak_dequant_transient_bytes(torch.nn.Sequential(gguf_model[0]), torch.float32)++ # Whichever scheme holds the largest layer decides, in either order.+ larger_int8 = Int8ConvrotLinear(+ weight=torch.zeros(4096, 4096, dtype=torch.int8), weight_scale=torch.ones(4096, 1), convrot=False+ )+ mixed = torch.nn.Sequential(gguf_model[0], larger_int8)+ assert peak_dequant_transient_bytes(mixed, torch.float32) == larger_int8.dequant_transient_bytes(torch.float32)+ smaller_int8 = Int8ConvrotLinear(+ weight=torch.zeros(8, 64, dtype=torch.int8), weight_scale=torch.ones(8, 1), convrot=False+ )+ assert smaller_int8.dequant_transient_bytes(torch.float32) < gguf_peak+ assert peak_dequant_transient_bytes(torch.nn.Sequential(smaller_int8, gguf_model[0]), torch.float32) == gguf_peak+ assert peak_dequant_transient_bytes(torch.nn.Sequential(torch.nn.Linear(64, 64)), torch.float32) == 0