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
feat(flux2): load int8_convrot Klein checkpoints
Alexander Eichhorn4df3c070edb7
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdxindex 2488357c93..a86e11bbf8 100644--- a/docs/src/content/docs/start-here/system-requirements.mdx+++ b/docs/src/content/docs/start-here/system-requirements.mdx@@ -28,7 +28,7 @@ The requirements below are rough guidelines for best performance. GPUs with less| 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+ || 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+ |diff --git a/invokeai/app/invocations/flux2/flux2_denoise.py b/invokeai/app/invocations/flux2/flux2_denoise.pyindex 33725938a4..c1058e3697 100644--- a/invokeai/app/invocations/flux2/flux2_denoise.py+++ b/invokeai/app/invocations/flux2/flux2_denoise.py@@ -40,13 +40,17 @@ from invokeai.backend.flux2.sampling_utils import ()from invokeai.backend.flux2.text_conditioning import Flux2TextConditioningfrom invokeai.backend.model_manager.configs.flux2_variant import flux2_hidden_size-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.flux_bfl_peft_lora_conversion_utils import (convert_bfl_lora_patch_to_diffusers,)from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.int8_convrot import (+ peak_int8_dequant_transient_bytes,+ requires_sidecar_patching,+)from 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 FLUXConditioningInfo@@ -512,26 +516,26 @@ 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.+ # 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)+# 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- # Determine if the model is quantized- if config.format in [ModelFormat.Diffusers]:- model_is_quantized = False- elif config.format in [- ModelFormat.BnbQuantizedLlmInt8b,- ModelFormat.BnbQuantizednf4b,- ModelFormat.GGUFQuantized,- ModelFormat.SDNQQuantized,- ]:- model_is_quantized = True- else:- model_is_quantized = False+ # Whether LoRA has to be applied as a sidecar rather than patched into the weights.+ # Asked of the *model*, not only the format: an `int8_tensorwise` checkpoint carries+ # `ModelFormat.Checkpoint` like any other single file, but its `Int8ConvrotLinear`+ # weights are int8 buffers that an in-place patch cannot touch.+ model_is_quantized = requires_sidecar_patching(transformer, config.format)# Apply LoRA models to the transformerexit_stack.enter_context(diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 65360d2dca..b5acffd457 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -86,6 +86,7 @@ from invokeai.backend.model_manager.util.model_util import (convert_bundle_to_flux_transformer_checkpoint,)from invokeai.backend.quantization.fp8_scaled import (+ Fp8ScaledLayer,attach_fp8_scales,can_stay_quantized,cast_state_dict,@@ -105,6 +106,18 @@ from invokeai.backend.quantization.fp8_scaled import ()from invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES+from invokeai.backend.quantization.int8_convrot import (+ INT8_TENSORWISE_FORMAT,+ Int8ConvrotLinear,+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ predict_int8_cast_size,+ reject_foreign_quantization_scales,+ reject_unmarked_int8_weights,+ split_int8_convrot_layers,+ swap_in_int8_linears,+)from 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@@ -1039,6 +1052,24 @@ class Flux2CheckpointModel(ModelLoader):match submodel_type:case SubModelType.Transformer:model = self._load_from_singlefile(config)+ if isinstance(model, torch.nn.Module) and any(+ isinstance(module, Int8ConvrotLinear) for module in model.modules()+ ):+ # The storage pass cannot reach an int8 weight: it casts only+ # `_FP8_SUPPORTED_PYTORCH_LAYERS`, and `Int8ConvrotLinear` is neither one of+ # them nor an owner of parameters. What it *could* still cast is the dense+ # remainder -- the modulation projections feeding AdaLN shift/scale/gate, the+ # embedders and the final layer, ~285M parameters. Those are precisely what the+ # repack chose to leave bf16, and the model's own skip patterns+ # (`pos_embed`, `norm`) do not protect them, so the pass is skipped rather than+ # allowed to undo that choice for ~140 MB. Krea-2's Qwen3-VL encoder loader+ # makes the same call for the same reason.+ if getattr(getattr(config, "default_settings", None), "fp8_storage", None):+ self._logger.info(+ "FLUX.2: the model's fp8_storage setting was skipped - this is an "+ "int8_tensorwise checkpoint, already one byte per quantized weight."+ )+ return modelmodel = self._apply_fp8_layerwise_casting(model, config, submodel_type)return model@@ -1078,38 +1109,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])+ }- 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.- dequantize_fp8_scaled(converted_sd, fp8_layers, torch.bfloat16)- fp8_layers = {}+ # 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:+ # 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.+ 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 keysdouble_block_indices = [@@ -1152,6 +1219,12 @@ class Flux2CheckpointModel(ModelLoader):# Klein models don't have guidance embeddings - check if they're in the checkpointhas_guidance = "time_guidance_embed.guidance_embedder.linear_1.weight" in converted_sd+ # Outside the branch on purpose (see the helper): an int8 weight that neither a marker nor+ # the header claims would otherwise be cast to bf16 as raw codes and load silently. In the+ # fp8 branch `int8_markers` is empty, so this also catches an int8 payload that arrived+ # down that path.+ reject_unmarked_int8_weights(converted_sd, int8_markers, "FLUX.2")+# Create model with detected configurationwith SilenceWarnings():with accelerate.init_empty_weights():@@ -1190,23 +1263,73 @@ class Flux2CheckpointModel(ModelLoader):# model's own precision-sensitive list is honored — see the Z-Image loader for why that is# a correctness requirement and not just a quality nicety.skip_patterns = _model_declared_skip_patterns(model)- # Scaled layers the cast would dequantize anyway are folded here, scale applied, so- # `cast_state_dict` never strips a scale that can no longer be put back.- fp8_layers = split_fp8_scaled_layers(- converted_sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns- )- kept = cast_state_dict(- converted_sd,- torch.bfloat16,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- )+ if int8_markers:+ # W8A8 activation scales and any marker of another format: meaningless on this path,+ # which dequantizes the weight and computes in bf16. Dropped rather than tolerated+ # because they would otherwise be cast and counted against the reservation for nothing.+ converted_sd = drop_unconsumed_quantization_sidecars(converted_sd)++ quantized = int8_markers+ # A scale left over from another scheme means its weight is about to be cast without+ # one. After the model exists, so the check can tell a real module from a stray key.+ reject_foreign_quantization_scales(converted_sd, quantized, "FLUX.2", model)++ # Reserve before the split, which dequantizes what it cannot keep, and charge the int8+ # payloads their actual one byte rather than bf16's two.+ self._ram_cache.make_room(+ predict_int8_cast_size(+ converted_sd, torch.bfloat16, quantized, model=model, skip_patterns=skip_patterns+ )+ )+ quantized = split_int8_convrot_layers(+ converted_sd, quantized, torch.bfloat16, model=model, skip_patterns=skip_patterns+ )+ cast_unquantized(converted_sd, torch.bfloat16, quantized)+ swap_in_int8_linears(model, converted_sd, quantized)+ else:+ # The same reservation FLUX.1 makes above, and for the same reason: the split+ # dequantizes its unusable subset through fp32, so reserving afterwards lets that+ # 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,+ )+ )++ # Scaled layers the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale that can no longer be put back.+ fp8_layers = split_fp8_scaled_layers(+ converted_sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns+ )++ kept = cast_state_dict(+ converted_sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )# Load the state dict - guidance weights were already initialized above if missingload_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)")diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.pyindex a6f17efe61..73f4b1053c 100644--- a/invokeai/backend/model_manager/starter_models/__init__.py+++ b/invokeai/backend/model_manager/starter_models/__init__.py@@ -114,6 +114,7 @@ from invokeai.backend.model_manager.starter_models.flux2 import (flux2_klein_9b_fp8,flux2_klein_9b_gguf_q4,flux2_klein_9b_gguf_q8,+ flux2_klein_9b_int8,flux2_klein_9b_sdnq,flux2_vae,pid_decoder_flux2_2k,@@ -339,6 +340,7 @@ STARTER_MODELS: list[StarterModel] = [flux2_klein_4b_fp8,flux2_klein_9b,flux2_klein_9b_fp8,+ flux2_klein_9b_int8,flux2_klein_4b_sdnq,flux2_klein_9b_sdnq,flux2_klein_4b_gguf_q4,diff --git a/invokeai/backend/model_manager/starter_models/flux2.py b/invokeai/backend/model_manager/starter_models/flux2.pyindex 607a5abd97..ca1a874265 100644--- a/invokeai/backend/model_manager/starter_models/flux2.py+++ b/invokeai/backend/model_manager/starter_models/flux2.py@@ -92,6 +92,28 @@ flux2_klein_9b_fp8 = StarterModel(dependencies=[flux2_vae, flux2_klein_qwen3_8b_encoder],)+# A community repack rather than a BFL or Comfy-Org release -- neither publishes an int8 build of+# FLUX.2. It is listed because it is the only FLUX.2 build whose download size is also its resident+# size on every device: `Int8ConvrotLinear` keeps the stored codes and dequantizes per forward,+# where the fp8 weights above expand to bf16 on load unless `fp8_compute` is available.+#+# Pinned to a commit rather than `main`, which for this entry is a correctness matter and not just+# reproducibility: the decode is driven by the file's own `comfy_quant` marker, which today says+# `int8_tensorwise` with no `convrot` flag. A reupload at the same path that added `"convrot": true`+# -- or that was genuinely rotated -- would be derotated with a Hadamard that was never applied, and+# the result loads cleanly, logs "kept 144 layer(s) in int8" and generates noise.+flux2_klein_9b_int8 = StarterModel(+ name="FLUX.2 Klein 9B (int8)",+ base=BaseModelType.Flux2,+ source="https://huggingface.co/Winnougan/Klein9b-Distilled-Base-INT8-Convrot/resolve/0373bf363446b8aa1e77245658dc2163875d7f08/flux-2-klein-9b-int8-convrot.safetensors",+ description="FLUX.2 Klein 9B in ComfyUI int8_tensorwise, from a community repack (no first-party "+ "int8 build of FLUX.2 exists). Unlike the FP8 build it stays at its download size in memory on "+ "every supported GPU - 9.5GB rather than ~18GB - because the weights are dequantized per forward "+ "instead of on load. Quality matches FP8 closely. Installs with VAE and Qwen3 8B encoder. ~9.5GB",+ type=ModelType.Main,+ dependencies=[flux2_vae, flux2_klein_qwen3_8b_encoder],+)+flux2_klein_4b_sdnq = StarterModel(name="FLUX.2 Klein 4B (SDNQ dynamic 4-bit)",base=BaseModelType.Flux2,diff --git a/tests/app/invocations/test_flux2_working_memory.py b/tests/app/invocations/test_flux2_working_memory.pyindex e5899df397..01a32f07d1 100644--- a/tests/app/invocations/test_flux2_working_memory.py+++ b/tests/app/invocations/test_flux2_working_memory.py@@ -26,6 +26,7 @@ from invokeai.app.invocations.flux2.flux2_denoise import ()from invokeai.app.invocations.vae.flux2_vae_decode import Flux2VaeDecodeInvocationfrom invokeai.app.invocations.vae.flux2_vae_encode import Flux2VaeEncodeInvocation+from invokeai.backend.patches.layer_patcher import LayerPatcherfrom invokeai.backend.util.attention import (SDPA_MATH_BYTES_PER_SCORE_ELEMENT,_diffusers_attention_dispatch,@@ -554,8 +555,21 @@ class TestFlux2DenoiseRequestsWorkingMemory:"""The denoise node must hand its estimate to the cache, and that estimate must grow with theattached reference images -- the combination that #9500 was missing."""- def _run(self, num_ref_tokens: int, batch: int = 1, init_batch: int | None = None, variant="klein_9b"):- """Drive `_run_diffusion` up to the transformer load and return the requested working memory."""+ def _run(+ self,+ num_ref_tokens: int,+ batch: int = 1,+ init_batch: int | None = None,+ variant="klein_9b",+ transformer: torch.nn.Module | None = None,+ on_device=None,+ ):+ """Drive `_run_diffusion` up to the transformer load and return the requested working memory.++ `transformer` replaces the mocked model the node reads before locking. It has to be a real+ module for anything that walks the module tree: a `MagicMock` iterates empty, so an int8+ build looks exactly like a dense one.+ """from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelTypefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,@@ -563,7 +577,9 @@ class TestFlux2DenoiseRequestsWorkingMemory:)transformer_info = MagicMock()- transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)+ transformer_info.model_on_device = MagicMock(side_effect=on_device or _StopBeforeLoad)+ if transformer is not None:+ transformer_info.model = transformercontext = MagicMock()context.models.load.return_value = transformer_info@@ -621,6 +637,9 @@ class TestFlux2DenoiseRequestsWorkingMemory:transformer_info.model_on_device.assert_called_once()return transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"]+ # `on_device` lets a caller get past the load instead of stopping at it, for the wires that sit+ # further down the node.+def test_estimate_reaches_the_model_cache(self):"""Without this the cache reserves only the default `device_working_mem_gb`."""assert self._run(num_ref_tokens=0) == _estimate(image_seq_len=64 * 64, text_seq_len=512)@@ -1223,3 +1242,104 @@ class TestDiffusersAttentionDispatchIsConsulted: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++ 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 Falsediff --git a/tests/app/invocations/test_int8_denoise_working_memory.py b/tests/app/invocations/test_int8_denoise_working_memory.pyindex c6e05d3c2f..078297ced5 100644--- a/tests/app/invocations/test_int8_denoise_working_memory.py+++ b/tests/app/invocations/test_int8_denoise_working_memory.py@@ -8,7 +8,8 @@ default working memory and the first forward competes with what it just placed.`peak_int8_dequant_transient_bytes` is unit-tested next to the module it belongs to. What ispinned here is the wire: deleting the `working_mem_bytes=` argument from the node leaves everyother test green. Z-Image only -- MiniMax H3 adds the same term; reaching its `model_on_device()` call needs a packed sequence.-Krea-2's wiring is pinned separately, in `tests/app/invocations/test_krea2_denoise.py`.+Krea-2's wiring is pinned in `tests/app/invocations/test_krea2_denoise.py` and FLUX.2's in+`tests/app/invocations/test_flux2_working_memory.py`."""from types import SimpleNamespacediff --git a/tests/backend/model_manager/load/state_dicts/flux2_klein_9b_int8_convrot_keys.py b/tests/backend/model_manager/load/state_dicts/flux2_klein_9b_int8_convrot_keys.pynew file mode 100644index 0000000000..c9e20dddea--- /dev/null+++ b/tests/backend/model_manager/load/state_dicts/flux2_klein_9b_int8_convrot_keys.py@@ -0,0 +1,75 @@+"""Representative key layout of the `int8_tensorwise` FLUX.2 Klein 9B repack.++Captured from `Winnougan/Klein9b-Distilled-Base-INT8-Convrot` (`flux-2-klein-9b-int8-convrot.safetensors`),+which is the community repack v7 installs -- Comfy-Org publishes no int8 build of FLUX.2.++Two things make this the interesting int8 fixture rather than a copy of the fp8 one:++- `double_blocks.0.img_attn.qkv.weight` is a fused **int8** tensor whose `weight_scale` is a+ scalar and whose `comfy_quant` marker is a byte blob. Both describe the whole fused tensor,+ so each of the three diffusers projections has to inherit them *unchanged* -- and the marker+ has to arrive at all, or `extract_int8_convrot_markers` claims nothing and the int8 codes are+ cast to bf16 as raw integers.+- The marker carries no `convrot` flag (`{"format": "int8_tensorwise"}` and nothing else), so+ this build is the unrotated half of the scheme. A loader that assumed rotation would+ derotate a weight that was never rotated, which loads cleanly and generates noise.++`img_in`, `txt_in`, `time_in`, `final_layer` and the three modulation `lin`s stay BF16 in this+repack -- the repacker's choice, not the loader's. `Flux2Transformer2DModel` declares only+`('pos_embed', 'norm')` as precision-sensitive, of which just `final_layer.adaLN_modulation.1`+(renamed to `norm_out.linear`) is a quantizable match, so a repack that also quantized the+embedders would keep them int8. That is safe here because nothing in this architecture reads+`weight.dtype` to decide what to cast its activations to -- the hazard those patterns exist for on+Z-Image and Ideogram 4.++Subsetting rule as for the sibling fixtures: block 0 of each stack plus every non-block key.+Values are `(shape, dtype)`.+"""++state_dict_keys: dict[str, tuple[list[int], str]] = {+ "double_blocks.0.img_attn.norm.key_norm.scale": ([128], "BF16"),+ "double_blocks.0.img_attn.norm.query_norm.scale": ([128], "BF16"),+ "double_blocks.0.img_attn.proj.comfy_quant": ([29], "U8"),+ "double_blocks.0.img_attn.proj.weight": ([4096, 4096], "I8"),+ "double_blocks.0.img_attn.proj.weight_scale": ([], "F32"),+ "double_blocks.0.img_attn.qkv.comfy_quant": ([29], "U8"),+ "double_blocks.0.img_attn.qkv.weight": ([12288, 4096], "I8"),+ "double_blocks.0.img_attn.qkv.weight_scale": ([], "F32"),+ "double_blocks.0.img_mlp.0.comfy_quant": ([29], "U8"),+ "double_blocks.0.img_mlp.0.weight": ([24576, 4096], "I8"),+ "double_blocks.0.img_mlp.0.weight_scale": ([], "F32"),+ "double_blocks.0.img_mlp.2.comfy_quant": ([29], "U8"),+ "double_blocks.0.img_mlp.2.weight": ([4096, 12288], "I8"),+ "double_blocks.0.img_mlp.2.weight_scale": ([], "F32"),+ "double_blocks.0.txt_attn.norm.key_norm.scale": ([128], "BF16"),+ "double_blocks.0.txt_attn.norm.query_norm.scale": ([128], "BF16"),+ "double_blocks.0.txt_attn.proj.comfy_quant": ([29], "U8"),+ "double_blocks.0.txt_attn.proj.weight": ([4096, 4096], "I8"),+ "double_blocks.0.txt_attn.proj.weight_scale": ([], "F32"),+ "double_blocks.0.txt_attn.qkv.comfy_quant": ([29], "U8"),+ "double_blocks.0.txt_attn.qkv.weight": ([12288, 4096], "I8"),+ "double_blocks.0.txt_attn.qkv.weight_scale": ([], "F32"),+ "double_blocks.0.txt_mlp.0.comfy_quant": ([29], "U8"),+ "double_blocks.0.txt_mlp.0.weight": ([24576, 4096], "I8"),+ "double_blocks.0.txt_mlp.0.weight_scale": ([], "F32"),+ "double_blocks.0.txt_mlp.2.comfy_quant": ([29], "U8"),+ "double_blocks.0.txt_mlp.2.weight": ([4096, 12288], "I8"),+ "double_blocks.0.txt_mlp.2.weight_scale": ([], "F32"),+ "double_stream_modulation_img.lin.weight": ([24576, 4096], "BF16"),+ "double_stream_modulation_txt.lin.weight": ([24576, 4096], "BF16"),+ "final_layer.adaLN_modulation.1.weight": ([8192, 4096], "BF16"),+ "final_layer.linear.weight": ([128, 4096], "BF16"),+ "img_in.weight": ([4096, 128], "BF16"),+ "single_blocks.0.linear1.comfy_quant": ([29], "U8"),+ "single_blocks.0.linear1.weight": ([36864, 4096], "I8"),+ "single_blocks.0.linear1.weight_scale": ([], "F32"),+ "single_blocks.0.linear2.comfy_quant": ([29], "U8"),+ "single_blocks.0.linear2.weight": ([4096, 16384], "I8"),+ "single_blocks.0.linear2.weight_scale": ([], "F32"),+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),+ "single_stream_modulation.lin.weight": ([12288, 4096], "BF16"),+ "time_in.in_layer.weight": ([4096, 256], "BF16"),+ "time_in.out_layer.weight": ([4096, 4096], "BF16"),+ "txt_in.weight": ([4096, 12288], "BF16"),+}diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_keys.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_keys.pynew file mode 100644index 0000000000..6f5306663d--- /dev/null+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_keys.py@@ -0,0 +1,116 @@+"""An `int8_tensorwise` FLUX.2 checkpoint must survive the BFL -> diffusers rename with its markers.++The scaled-fp8 sibling of this file covers the scales. What is new here is the `comfy_quant` marker,+and it is load-bearing in a way a scale is not: a scale that goes missing leaves a weight quantized+but unscaled, while a *marker* that goes missing means `extract_int8_convrot_markers` claims nothing+at all and the int8 codes are cast to bf16 as raw integers -- a model of small signed integers.++Both of FLUX.2's fused layers are exercised, and they pull in opposite directions. The per-tensor+scale and the marker each describe a whole fused tensor, so `double_blocks.*.img_attn.qkv` -- which+diffusers splits three ways -- has to *copy* both to every projection, while+`single_blocks.*.linear1` stays fused as `to_qkv_mlp_proj` and has to carry both to exactly one.+"""++import json++import torch++from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import (+ convert_flux2_bfl_to_diffusers,+)+from invokeai.backend.quantization.int8_convrot import (+ extract_int8_convrot_markers,+ reject_unmarked_int8_weights,+)+from tests.backend.model_manager.load.state_dicts.flux2_klein_9b_int8_convrot_keys import (+ state_dict_keys as klein_keys,+)++_DTYPES = {"I8": torch.int8, "U8": torch.uint8, "F32": torch.float32, "BF16": torch.bfloat16}++# What the repack writes, read from the file: no `convrot`, so no rotation to undo.+MARKER = {"format": "int8_tensorwise"}+++def _build_state_dict() -> dict[str, torch.Tensor]:+ """The captured layout at exact extents but almost no storage.++ The extents matter -- the fused tensors are split by row -- but the values do not, so each+ tensor is one element expanded to its full shape. The markers are the exception: they carry+ the JSON the loader parses, so they are built for real (and are 29 bytes each).+ """+ sd: dict[str, torch.Tensor] = {}+ for key, (shape, dtype) in klein_keys.items():+ if key.endswith(".comfy_quant"):+ sd[key] = torch.frombuffer(bytearray(json.dumps(MARKER).encode("utf-8")), dtype=torch.uint8).clone()+ continue+ sd[key] = torch.full((), 2.5 if key.endswith(".weight_scale") else 0.0, dtype=_DTYPES[dtype]).expand(shape)+ return sd+++def test_the_marker_this_suite_builds_matches_the_captured_blob_length() -> None:+ """A consistency guard between `MARKER` and the fixture, not a check on production code.++ The captured blobs are 29 bytes, which is exactly `{"format": "int8_tensorwise"}` -- no+ `convrot` flag. If someone re-captures the fixture from a repack that added one, the recorded+ length moves and this fails, which is the prompt to update `MARKER` rather than keep testing+ the unrotated case against a rotated file.+ """+ lengths = {tuple(shape) for key, (shape, _) in klein_keys.items() if key.endswith(".comfy_quant")}++ assert lengths == {(len(json.dumps(MARKER).encode("utf-8")),)}+++def test_every_int8_weight_is_still_claimed_after_the_rename() -> None:+ """The end state the loader depends on: no orphaned codes anywhere in the converted dict."""+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())+ markers = extract_int8_convrot_markers(converted)++ assert markers, "no marker survived the conversion"+ # Raises if any int8 weight is left without one. Checked through the guard the loader uses+ # rather than by recounting, because that guard is what has to stay satisfied.+ reject_unmarked_int8_weights(converted, markers, "FLUX.2")+ assert [k for k in converted if k.startswith(("double_blocks.", "single_blocks."))] == []+++def test_a_fused_layer_hands_its_marker_and_scale_to_every_projection() -> None:+ """A per-tensor scale and a marker blob describe the whole fused tensor.++ Splitting either would be wrong and leaving either on the fused path is worse: the projections+ the fusion becomes then carry int8 codes that nothing claims.+ """+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())+ markers = extract_int8_convrot_markers(converted)++ for fused, parts in (+ ("double_blocks.0.img_attn.qkv", ("to_q", "to_k", "to_v")),+ ("double_blocks.0.txt_attn.qkv", ("add_q_proj", "add_k_proj", "add_v_proj")),+ ):+ source_scale = _build_state_dict()[f"{fused}.weight_scale"]+ destinations = [path for path in markers if path.rsplit(".", 1)[-1] in parts]+ assert len(destinations) == len(parts), f"{fused} -> {destinations}"+ for path in destinations:+ assert markers[path] == MARKER+ assert torch.equal(converted[f"{path}.weight_scale"], source_scale)+ assert converted[f"{path}.weight"].dtype is torch.int8+++def test_the_single_block_fusion_is_renamed_rather_than_split() -> None:+ """`single_blocks.linear1` fuses attention *and* MLP, and diffusers keeps it fused.++ So it is the opposite case from the qkv, and worth pinning for that reason: its marker must be+ carried to exactly one destination. It is also the largest quantized layer in the file+ (36864 x 4096), i.e. the one that sets the per-forward dequantization transient the denoise+ node reserves for.+ """+ converted = convert_flux2_bfl_to_diffusers(_build_state_dict())+ markers = extract_int8_convrot_markers(converted)++ fused = "single_transformer_blocks.0.attn.to_qkv_mlp_proj"+ from_single_block = sorted(path for path in markers if path.startswith("single_transformer_blocks.0."))++ # Exactly one destination from `linear1` and one from `linear2` -- no split, no duplicate.+ assert from_single_block == ["single_transformer_blocks.0.attn.to_out", fused]+ assert markers[fused] == MARKER+ assert converted[f"{fused}.weight"].shape == torch.Size(klein_keys["single_blocks.0.linear1.weight"][0])+ assert converted[f"{fused}.weight"].dtype is torch.int8diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.pynew file mode 100644index 0000000000..78417d89b8--- /dev/null+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py@@ -0,0 +1,419 @@+"""Loader-level tests for the `int8_tensorwise` FLUX.2 path.++These drive `Flux2CheckpointModel._load_from_singlefile` and assert the end state of the module:+which layers keep their codes, what the reconstructed weight is, and what the cache was asked to+free. The geometry is the released Klein 9B layout scaled down by 16 -- same module tree and the+same two fusions, 4 tensors per block instead of 4096-wide ones.++The branch this covers is one decision: an int8 layer ships a `.weight_scale` exactly like a scaled+fp8 layer, so a loader that probes for scales first takes the whole checkpoint down the fp8 path.+There the codes are scaled but never dequantized to a dtype torch computes in.+"""++import json+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux2_Config+from invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModel+from invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import remap_flux2_layer_paths+from invokeai.backend.model_manager.taxonomy import Flux2VariantType, SubModelType+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear++MARKER = {"format": "int8_tensorwise"}++H = 256 # hidden size: two 128-wide attention heads, the smallest the architecture allows+JOINT = 768 # context_embedder input; only its presence and rank matter here+IN_CHANNELS = 128 # FLUX.2's 32 latent channels x 4 packing -- what identification keys on++# `<bfl path>: (out, in)`, at the released ratios. The two fused layers are what make FLUX.2 the+# hard case: one int8 tensor and one scalar scale become three (or two) diffusers projections.+QUANTIZED: dict[str, tuple[int, int]] = {+ "double_blocks.0.img_attn.qkv": (3 * H, H),+ "double_blocks.0.img_attn.proj": (H, H),+ "double_blocks.0.img_mlp.0": (6 * H, H),+ "double_blocks.0.img_mlp.2": (H, 3 * H),+ "double_blocks.0.txt_attn.qkv": (3 * H, H),+ "double_blocks.0.txt_attn.proj": (H, H),+ "double_blocks.0.txt_mlp.0": (6 * H, H),+ "double_blocks.0.txt_mlp.2": (H, 3 * H),+ "single_blocks.0.linear1": (9 * H, H),+ "single_blocks.0.linear2": (H, 4 * H),+}++DENSE: dict[str, tuple[int, ...]] = {+ "img_in.weight": (H, IN_CHANNELS),+ "txt_in.weight": (H, JOINT),+ "time_in.in_layer.weight": (H, 256),+ "time_in.out_layer.weight": (H, H),+ "double_stream_modulation_img.lin.weight": (6 * H, H),+ "double_stream_modulation_txt.lin.weight": (6 * H, H),+ "single_stream_modulation.lin.weight": (3 * H, H),+ "final_layer.adaLN_modulation.1.weight": (2 * H, H),+ "final_layer.linear.weight": (IN_CHANNELS, H),+ "double_blocks.0.img_attn.norm.key_norm.scale": (128,),+ "double_blocks.0.img_attn.norm.query_norm.scale": (128,),+ "double_blocks.0.txt_attn.norm.key_norm.scale": (128,),+ "double_blocks.0.txt_attn.norm.query_norm.scale": (128,),+ "single_blocks.0.norm.key_norm.scale": (128,),+ "single_blocks.0.norm.query_norm.scale": (128,),+}+++def _marker_blob(marker: dict) -> torch.Tensor:+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()+++def _quantize_tensorwise(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """As the repack stores it: one scalar scale for the whole tensor, no rotation."""+ scale = weight.abs().max() / 127.0+ return torch.clamp(torch.round(weight / scale), -128, 127).to(torch.int8), scale.to(torch.float32)+++# Stored fp32 rather than bf16, because a repack that mixes precisions in its dense remainder is+# what makes `cast_unquantized` observable at all: `load_state_dict_ignoring_extras(assign=True)`+# assigns storage dtypes straight through, so without the cast this layer lands as fp32 inside a+# bf16 model -- and the reservation, which charged it two bytes, comes up short by its size.+STORED_FP32 = "img_in.weight"++# W8A8 metadata for a mode this path does not implement. The load is not strict, but the cast and+# the reservation would both pay for it.+ACTIVATION_SCALE = "double_blocks.0.img_attn.proj.input_scale"+++def _checkpoint(marker: dict | None = MARKER) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ """A BFL-format state dict with every block linear stored int8, plus the float originals."""+ torch.manual_seed(0)+ sd: dict[str, torch.Tensor] = {+ key: torch.randn(*shape, dtype=torch.float32 if key == STORED_FP32 else torch.bfloat16)+ for key, shape in DENSE.items()+ }+ sd[ACTIVATION_SCALE] = torch.ones((), dtype=torch.float32)++ originals: dict[str, torch.Tensor] = {}+ for path, (out_features, in_features) in QUANTIZED.items():+ weight = torch.randn(out_features, in_features, dtype=torch.float32)+ originals[path] = weight+ sd[f"{path}.weight"], sd[f"{path}.weight_scale"] = _quantize_tensorwise(weight)+ if marker is not None:+ sd[f"{path}.comfy_quant"] = _marker_blob(marker)+ return sd, originals+++def _expected_reservation() -> int:+ """What the load occupies, with the four widths spelled out rather than recomputed.++ A payload that stays int8 is one byte, whatever the compute dtype. Its scalar scale is *copied*+ to each projection the fused layer becomes and stays fp32 there, so that count follows the+ destinations and not the checkpoint's ten layers. Everything else arrives at the compute width,+ including the layer the checkpoint stored as fp32 -- charged what it becomes, not what it was.+ The marker and the activation scale are dropped before the load and charged nothing.++ Charging a kept int8 payload two bytes asks the cache to evict roughly twice what an 8.8 GiB+ file needs; charging none lets the split's transient land on an unreserved cache.+ """+ int8_bytes = sum(out * inp for out, inp in QUANTIZED.values())+ destinations = sum(len(paths) for paths in remap_flux2_layer_paths(QUANTIZED).values())+ scale_bytes = destinations * torch.float32.itemsize+ dense_bytes = sum(torch.Size(shape).numel() for shape in DENSE.values()) * torch.bfloat16.itemsize+ # Klein has no guidance embedder, so the loader fills one with zeros shaped like the timestep+ # embedder's two linears. It is part of what the load occupies and is reserved for.+ guidance_bytes = (H * 256 + H * H) * torch.bfloat16.itemsize+ return int8_bytes + scale_bytes + dense_bytes + guidance_bytes+++def _driver(monkeypatch, tmp_path, state_dict: dict, trace: dict | None = None, header: dict | None = None):+ """Drive the loader with the cache recorded rather than stubbed out."""+ import invokeai.backend.model_manager.load.model_loaders.flux as module++ recorded = trace if trace is not None else {}+ recorded.setdefault("reserved", None)++ checkpoint = tmp_path / "flux-2-klein-9b-int8-convrot.safetensors"+ checkpoint.touch()+ config = Main_Checkpoint_Flux2_Config.model_construct(+ path=str(checkpoint), name="klein-9b-int8", variant=Flux2VariantType.Klein9B+ )++ def make_room(reserved: int) -> None:+ recorded["reserved"] = reserved++ loader = object.__new__(Flux2CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=make_room)+ loader._logger = MagicMock()+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.bfloat16++ monkeypatch.setattr(module, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: header)+ return loader, config+++def _load(monkeypatch, tmp_path, state_dict, trace: dict | None = None, header: dict | None = None):+ loader, config = _driver(monkeypatch, tmp_path, state_dict, trace, header)+ return loader._load_from_singlefile(config)+++def test_an_int8_checkpoint_stays_int8_resident(monkeypatch, tmp_path) -> None:+ """The point of the build: the file's size is the resident size.++ `Int8ConvrotLinear` holds the stored codes and dequantizes per forward, so the weights must+ still be int8 after the load -- on a path whose every other branch casts to bf16.+ """+ state_dict, _ = _checkpoint()++ model = _load(monkeypatch, tmp_path, state_dict)++ swapped = [name for name, module in model.named_modules() if isinstance(module, Int8ConvrotLinear)]+ assert swapped, "no layer kept its int8 storage"+ assert all(model.get_submodule(name).weight.dtype is torch.int8 for name in swapped)+ # This repack declares no rotation, and inventing one would derotate a weight that was never+ # rotated -- which loads cleanly and generates noise.+ assert all(model.get_submodule(name).convrot is False for name in swapped)+++def test_both_fusions_are_swapped_and_reconstruct_their_source(monkeypatch, tmp_path) -> None:+ """The fused layers are where a marker or a scale goes missing silently.++ Each projection is compared against its slice of the *original float* tensor, so a scale left+ on the fused path -- the failure that has no error attached to it -- fails here.+ """+ state_dict, originals = _checkpoint()++ model = _load(monkeypatch, tmp_path, state_dict)++ for fused, parts in (+ ("double_blocks.0.img_attn.qkv", ("transformer_blocks.0.attn.to_q", "transformer_blocks.0.attn.to_k")),+ ("double_blocks.0.txt_attn.qkv", ("transformer_blocks.0.attn.add_q_proj",)),+ ):+ source = originals[fused]+ for index, path in enumerate(parts):+ layer = model.get_submodule(path)+ assert isinstance(layer, Int8ConvrotLinear), path+ reconstructed = layer._dequantized_weight(torch.device("cpu"), torch.float32)+ expected = source[index * H : (index + 1) * H]+ assert torch.allclose(reconstructed, expected, rtol=0.05, atol=0.05 * source.abs().max())+++def test_the_dense_remainder_is_cast_to_the_compute_dtype(monkeypatch, tmp_path) -> None:+ """The layers the repack left alone still have to arrive in the compute dtype.++ `assign=True` hands the checkpoint's storage dtype straight to the module, so a repack whose+ dense remainder is fp32 -- the module docstring names real ones that mix precisions -- would+ otherwise put an fp32 `x_embedder` inside a bf16 model. The fixture stores exactly one layer+ that way, which is what makes this assertion able to fail.+ """+ state_dict, _ = _checkpoint()+ assert state_dict[STORED_FP32].dtype is torch.float32, "fixture no longer exercises the cast"++ model = _load(monkeypatch, tmp_path, state_dict)++ for path in ("x_embedder", "context_embedder", "proj_out"):+ layer = model.get_submodule(path)+ assert not isinstance(layer, Int8ConvrotLinear), path+ assert layer.weight.dtype is torch.bfloat16, path+++def test_an_unusable_activation_scale_is_dropped(monkeypatch, tmp_path) -> None:+ """W8A8 sidecars are metadata for a mode this path does not implement.++ Left in place they are cast to the compute dtype and charged against the reservation for+ nothing, and on a strict loader they would fail the load outright.+ """+ with_scale, without_scale = _checkpoint()[0], _checkpoint()[0]+ del without_scale[ACTIVATION_SCALE]+ traces: list[dict] = [{}, {}]++ model = _load(monkeypatch, tmp_path, with_scale, traces[0])+ _load(monkeypatch, tmp_path, without_scale, traces[1])++ assert isinstance(model.get_submodule("transformer_blocks.0.attn.to_out.0"), Int8ConvrotLinear)+ # Compared against the same file without the sidecar rather than against a computed total: what+ # has to hold is that carrying one costs nothing, and a dropped `drop_unconsumed_...` shows up+ # as the two branches disagreeing.+ assert traces[0]["reserved"] == traces[1]["reserved"] == _expected_reservation()+++def test_the_reservation_charges_the_int8_payloads_one_byte(monkeypatch, tmp_path) -> None:+ """This path asked the cache for nothing at all before int8 arrived.++ The number matters in both directions: charging bf16's two bytes asks the cache to evict about+ twice what an 8.8 GiB file needs, and charging none lets the split's transient land on an+ unreserved cache.+ """+ state_dict, _ = _checkpoint()+ trace: dict = {}++ _load(monkeypatch, tmp_path, state_dict, trace)++ assert trace["reserved"] == _expected_reservation()+++def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> None:+ """An unclaimed int8 weight would be cast to bf16 as raw codes: a model of small integers.++ It is refused rather than loaded, because nothing downstream can tell the difference.+ """+ state_dict, _ = _checkpoint(marker=None)++ with pytest.raises(ValueError, match="int8"):+ _load(monkeypatch, tmp_path, state_dict)+++def test_the_fp8_storage_pass_is_not_offered_an_int8_model(monkeypatch, tmp_path) -> None:+ """FP8 Storage is documented as a no-op on an already-quantized checkpoint, and here it has to+ be made one: the cast walks `model.parameters()` and only converts the handful of layers this+ path left dense -- `Int8ConvrotLinear` holds buffers and is not a layer type it casts at all.+ So it would spend the walk for no saving on the 144 layers that matter, and it is skipped.+ """+ state_dict, _ = _checkpoint()+ trace: dict = {}+ calls: list[str] = []++ loader, config = _driver(monkeypatch, tmp_path, state_dict, trace)+ loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model++ model = loader._load_model(config, SubModelType.Transformer)++ assert calls == []+ assert any(isinstance(module, Int8ConvrotLinear) for module in model.modules())+++def test_a_dense_checkpoint_still_reaches_the_fp8_storage_pass(monkeypatch, tmp_path) -> None:+ # The other half: skipping for int8 must not skip for everything else, or the FP8 Storage+ # setting quietly stops working for ordinary FLUX.2 checkpoints.+ state_dict, originals = _checkpoint()+ for path in QUANTIZED:+ del state_dict[f"{path}.comfy_quant"]+ del state_dict[f"{path}.weight_scale"]+ state_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)+ calls: list[str] = []++ loader, config = _driver(monkeypatch, tmp_path, state_dict)+ loader._apply_fp8_layerwise_casting = lambda model, *_args: calls.append("cast") or model++ model = loader._load_model(config, SubModelType.Transformer)++ assert calls == ["cast"]+ assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())+++def test_a_file_mixing_int8_with_scaled_fp8_is_refused(monkeypatch, tmp_path) -> None:+ """Inside the int8 branch the fp8 pipeline is skipped entirely.++ An fp8 layer that came along would be cast to the compute dtype without its scale -- off by+ `1/weight_scale` -- while the non-strict load drops the orphaned scale and says nothing. The+ detection is file-wide, so a merged export is exactly the shape that reaches this.+ """+ state_dict, _ = _checkpoint()+ weight = state_dict["final_layer.linear.weight"].float()+ scale = weight.abs().max() / 448.0+ state_dict["final_layer.linear.weight"] = (weight / scale).to(torch.float8_e4m3fn)+ state_dict["final_layer.linear.weight_scale"] = scale.to(torch.float32)++ with pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):+ _load(monkeypatch, tmp_path, state_dict)+++def test_a_repack_that_quantizes_a_skip_patterned_layer_is_dequantized(monkeypatch, tmp_path) -> None:+ """`Flux2Transformer2DModel` declares `('pos_embed', 'norm')`, and the final adaLN projection+ lands on `norm_out.linear` after the rename -- the one quantizable path those patterns match.++ A repack that claims it must still come back dense, and the reservation must charge it the+ width it is about to become rather than the one byte its marker implies.+ """+ state_dict, originals = _checkpoint()+ path = "final_layer.adaLN_modulation.1"+ weight = state_dict[f"{path}.weight"].float()+ originals[path] = weight+ state_dict[f"{path}.weight"], state_dict[f"{path}.weight_scale"] = _quantize_tensorwise(weight)+ state_dict[f"{path}.comfy_quant"] = _marker_blob(MARKER)++ model = _load(monkeypatch, tmp_path, state_dict)++ skipped = model.get_submodule("norm_out.linear")+ assert not isinstance(skipped, Int8ConvrotLinear)+ assert skipped.weight.dtype is torch.bfloat16+ # The block linears it was mixed with still keep their codes.+ assert isinstance(model.get_submodule("transformer_blocks.0.attn.to_q"), Int8ConvrotLinear)+++def test_a_checkpoint_that_declares_int8_only_in_its_header_still_loads(monkeypatch, tmp_path) -> None:+ """Per-layer markers are one of the two forms ComfyUI writes, and not the one it writes here.++ Comfy-Org's own fp8 build of Klein 9B carries no `.comfy_quant` tensors at all and names every+ layer in the safetensors header instead. A repack from that tooling would otherwise be refused+ for a marker it never had to write -- and refused by the guard whose message says the file+ would generate noise, which is the wrong story to tell about a perfectly valid checkpoint.++ The header names layers in the BFL scheme, so it needs the same one-to-many rename as the+ scales: a fused `qkv` becomes three diffusers modules.+ """+ state_dict, _ = _checkpoint(marker=None)+ header = {+ "_quantization_metadata": json.dumps(+ {"format_version": "1.0", "layers": {path: {"format": "int8_tensorwise"} for path in QUANTIZED}}+ )+ }++ model = _load(monkeypatch, tmp_path, state_dict, header=header)++ for path in (+ "transformer_blocks.0.attn.to_q",+ "transformer_blocks.0.attn.to_v",+ "single_transformer_blocks.0.attn.to_qkv_mlp_proj",+ ):+ assert isinstance(model.get_submodule(path), Int8ConvrotLinear), path+++def test_a_per_layer_marker_wins_over_the_header(monkeypatch, tmp_path) -> None:+ # Only the per-layer marker can carry `convrot` and the group size, so where both are present+ # it is the one that decides how the weight is decoded.+ state_dict, _ = _checkpoint(marker={**MARKER, "convrot": False})+ header = {+ "_quantization_metadata": json.dumps(+ {"layers": {path: {"format": "int8_tensorwise", "convrot": True} for path in QUANTIZED}}+ )+ }++ model = _load(monkeypatch, tmp_path, state_dict, header=header)++ assert model.get_submodule("transformer_blocks.0.attn.to_q").convrot is False+++def _scaled_fp8_checkpoint() -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ """The other build this loader takes: ComfyUI scaled fp8, one scale per tensor."""+ state_dict, originals = _checkpoint(marker=None)+ for path in QUANTIZED:+ weight = originals[path]+ scale = weight.abs().max() / 448.0+ state_dict[f"{path}.weight"] = (weight / scale).to(torch.float8_e4m3fn)+ state_dict[f"{path}.weight_scale"] = scale.to(torch.float32)+ return state_dict, originals+++def test_a_scaled_fp8_checkpoint_still_folds_its_scales(monkeypatch, tmp_path) -> None:+ """The fp8 pipeline moved wholesale into the `else` branch, and nothing drove it end to end.++ Without the fp8 matmul the scales are folded into the weights, so what has to come out is a+ plain bf16 Linear whose values are the original ones -- a dropped scale is off by+ `1/weight_scale`, i.e. orders of magnitude, not a rounding difference.+ """+ state_dict, originals = _scaled_fp8_checkpoint()++ model = _load(monkeypatch, tmp_path, state_dict)++ assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())+ for path, source in (+ ("transformer_blocks.0.attn.to_q", originals["double_blocks.0.img_attn.qkv"][:H]),+ ("transformer_blocks.0.ff.linear_out", originals["double_blocks.0.img_mlp.2"]),+ ):+ layer = model.get_submodule(path)+ assert layer.weight.dtype is torch.bfloat16, path+ assert not hasattr(layer, "weight_scale"), path+ # fp8 keeps ~2 decimal digits, so this is a "the scale was applied" check, not a bit compare.+ assert torch.allclose(layer.weight.float(), source, rtol=0.1, atol=0.1 * source.abs().max())