Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(flux): load int8_convrot dev checkpoints

Alexander Eichhornfc3a9d83a1ef
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdx
index fa8dcb8aeb..4ddc9d50fc 100644
--- a/docs/src/content/docs/start-here/system-requirements.mdx
+++ b/docs/src/content/docs/start-here/system-requirements.mdx
@@ -26,7 +26,7 @@ The requirements below are rough guidelines for best performance. GPUs with less
|---|---:|---|---:|---:|---|
| SD1.5 | 512x512 | Nvidia 10xx+ | 4GB | 8GB | |
| SDXL | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | |
-| FLUX.1 | 1024x1024 | Nvidia 20xx+ | 10GB | 32GB | |
+| FLUX.1 | 1024x1024 | Nvidia 20xx+ | 10GB | 32GB | Download totals: NF4 ~12GB, int8 ~18GB, bf16 ~33GB. The int8 transformer is 11.5GB resident on any supported GPU, so it streams on a 10GB card |
| FLUX.2 Klein 4B | 1024x1024 | Nvidia 30xx+ | 12GB | 16GB | FP8 works with 8GB+; 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 / NVFP4 8GB; Q8/BF16 16GB+ |
diff --git a/invokeai/app/invocations/flux/flux_denoise.py b/invokeai/app/invocations/flux/flux_denoise.py
index c26bf271e6..d230992fe6 100644
--- a/invokeai/app/invocations/flux/flux_denoise.py
+++ b/invokeai/app/invocations/flux/flux_denoise.py
@@ -61,6 +61,10 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, FluxVariantTy
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.int8_convrot import (
+ peak_int8_dequant_transient_bytes,
+ requires_sidecar_patching,
+)
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import FLUXConditioningInfo
@@ -423,9 +427,23 @@ class FluxDenoiseInvocation(BaseInvocation):
device=x.device,
)
+ 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.
+ #
+ # 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
+ # (the transient is alive alongside the activations, as it is for FLUX.2 and Krea-2).
+ 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()
+ transformer_info.model_on_device(working_mem_bytes=int8_dequant_bytes)
)
assert isinstance(transformer, Flux)
config = transformer_config
@@ -435,7 +453,12 @@ class FluxDenoiseInvocation(BaseInvocation):
# If the model is quantized, then we need to apply the LoRA weights as sidecar layers. This results in
# slower inference than direct patching, but is agnostic to the quantization format.
if config.format in [ModelFormat.Checkpoint]:
- model_is_quantized = False
+ # An `int8_tensorwise` checkpoint carries `Checkpoint` like any other single file,
+ # but its `Int8ConvrotLinear` weights are int8 buffers that an in-place patch
+ # cannot write into -- and the fallbacks that would otherwise catch that iterate
+ # `module.parameters()`, which these modules have none of. So the loaded module
+ # tree is consulted, not just the format.
+ model_is_quantized = requires_sidecar_patching(transformer, config.format)
elif config.format in [
ModelFormat.BnbQuantizedLlmInt8b,
ModelFormat.BnbQuantizednf4b,
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index ca3f6ac0a5..108dfe9edf 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -735,6 +735,22 @@ class FluxCheckpointModel(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 -- `Int8ConvrotLinear` is neither
+ # one of `_FP8_SUPPORTED_PYTORCH_LAYERS` nor an owner of parameters. What it
+ # would still cast is the dense remainder: the embedders, the timestep, vector
+ # and guidance MLPs and the final layer, 423 MB of an 11.5 GiB model. Those are
+ # exactly the layers the repack chose to leave bf16, and `Flux` declares no skip
+ # patterns to protect them, so 3.6% is not worth e4m3 on the model's entry and
+ # exit. Same decision as the FLUX.2 arm below.
+ if getattr(getattr(config, "default_settings", None), "fp8_storage", None):
+ self._logger.info(
+ "FLUX: the model's fp8_storage setting was skipped - this is an "
+ "int8_tensorwise checkpoint, already one byte per quantized weight."
+ )
+ return model
model = self._apply_fp8_layerwise_casting(model, config, submodel_type)
return model
@@ -766,16 +782,50 @@ class FluxCheckpointModel(ModelLoader):
# layout this model implements, and `qkv` stays one fused Linear, so a per-tensor scale
# attaches to exactly the module it was computed for.
#
- # Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers; the
- # header wins on the rare checkpoint carrying both.
+ # Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers. For
+ # the fp8 merge below the header wins on the rare checkpoint carrying both; for the int8
+ # merge the per-layer marker does, because only it can carry `convrot` and the group size.
metadata = read_safetensors_metadata(model_path, self._logger)
# Header names still carry the checkpoint prefix that was stripped off `sd`; strip it from
# them too, or every per-layer flag matches nothing.
- layer_hints = {
- **extract_comfy_quant_hints(sd),
- **strip_layer_path_prefix(parse_quantization_metadata(metadata)),
+ header_hints = strip_layer_path_prefix(parse_quantization_metadata(metadata))
+
+ # 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, but never un-rotated, which
+ # loads cleanly and generates noise.
+ #
+ # No rename stands between the markers and the module tree here: unlike FLUX.2 the
+ # checkpoint is already in this model's BFL layout and `qkv` stays one fused Linear, so a
+ # marker names exactly the module it was written for.
+ # The header entries are filtered against `sd`, which the per-layer markers are by
+ # construction. Two things can otherwise put a name there that this load has no weight for:
+ # stale metadata from a repack tool, which would route a plain bf16 checkpoint into the int8
+ # branch and kill it at the swap; and a merged export, whose header still describes the
+ # bundled encoder after `convert_bundle_to_flux_transformer_checkpoint` has deleted it. The
+ # dtype test is what separates a real int8 layer from both.
+ int8_markers = {
+ **{
+ name: marker
+ for name, marker in header_hints.items()
+ if marker.get("format") == INT8_TENSORWISE_FORMAT
+ and getattr(sd.get(f"{name}.weight"), "dtype", None) is torch.int8
+ },
+ **extract_int8_convrot_markers(sd),
}
- fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+ # Outside the branch below on purpose (see the helper): an int8 weight that neither a marker
+ # nor the header claims would otherwise reach `load_state_dict` as raw codes. On this
+ # architecture that raises rather than loading quietly -- int8 is not a float dtype, so the
+ # cast skips it and assigning it to a float Parameter fails -- but the message names a
+ # gradient error rather than the checkpoint, which is the whole reason to check here.
+ # `model` narrows this to weights the transformer consumes, so a merged file's bundled
+ # encoder is left to the non-strict load that discards it.
+ reject_unmarked_int8_weights(sd, int8_markers, "FLUX", model)
+
+ fp8_layers: dict[str, Fp8ScaledLayer] = {}
+ if not int8_markers:
+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
# The `match` above admits only the transformer, so that is the submodel the cast will be
# asked about too -- keep and cast therefore decide on the same input.
@@ -788,6 +838,36 @@ class FluxCheckpointModel(ModelLoader):
fp8_layers = {}
skip_patterns = _model_declared_skip_patterns(model)
+
+ if int8_markers:
+ # W8A8 activation scales and any marker of another format: meaningless on this path,
+ # which dequantizes the weight and computes in bf16.
+ sd = drop_unconsumed_quantization_sidecars(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(sd, quantized, "FLUX", 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(sd, torch.bfloat16, quantized, model=model, skip_patterns=skip_patterns)
+ )
+ quantized = split_int8_convrot_layers(
+ sd, quantized, torch.bfloat16, model=model, skip_patterns=skip_patterns
+ )
+ cast_unquantized(sd, torch.bfloat16, quantized)
+ swap_in_int8_linears(model, sd, quantized)
+ load_state_dict_ignoring_extras(model, sd, source="FLUX transformer checkpoint", assign=True)
+
+ # No setting behind this one and nothing to fall back to: `Int8ConvrotLinear` holds the
+ # stored codes and dequantizes per forward, so an 11.5 GiB file stays 11.5 GiB resident
+ # on every device. What it does not get is int8 *compute*.
+ self._logger.info(
+ f"FLUX: kept {len(quantized)} layer(s) in int8 (int8_tensorwise checkpoint, dequantized per forward)"
+ )
+ return model
# Scaled layers that 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.
# Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 694ab4dc40..25b471dc68 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -85,6 +85,7 @@ from invokeai.backend.model_manager.starter_models.flux import (
flux_canny_control_lora,
flux_depth_control_lora,
flux_dev,
+ flux_dev_int8,
flux_dev_quantized,
flux_fill,
flux_kontext_quantized,
@@ -270,6 +271,7 @@ STARTER_MODELS: list[StarterModel] = [
flux_kontext_quantized,
flux_schnell_quantized,
flux_dev_quantized,
+ flux_dev_int8,
flux_schnell,
flux_dev,
flux_schnell_sdnq,
diff --git a/invokeai/backend/model_manager/starter_models/flux.py b/invokeai/backend/model_manager/starter_models/flux.py
index 164df60406..4506f0a93a 100644
--- a/invokeai/backend/model_manager/starter_models/flux.py
+++ b/invokeai/backend/model_manager/starter_models/flux.py
@@ -76,6 +76,23 @@ flux_schnell = StarterModel(
dependencies=[t5_base_encoder, flux_vae, clip_l_encoder],
)
+# A community repack -- neither BFL nor Comfy-Org publishes an int8 build of FLUX.1. Pinned to a
+# commit rather than `main`, which here is a correctness matter and not just reproducibility: the
+# decode follows the file's own `comfy_quant` marker, which says `convrot: true` at group size 256.
+# A reupload at the same path that changed or dropped that flag would be derotated wrongly, and the
+# result loads cleanly, logs its layer count and generates noise.
+flux_dev_int8 = StarterModel(
+ name="FLUX.1 dev (int8)",
+ base=BaseModelType.Flux,
+ source="https://huggingface.co/AX1Y2JP/FLUX.1-dev-INT8-ConvRot/resolve/01a17db182d52088b222d615ce54729fa090b378/flux1-dev-int8-convrot.safetensors",
+ description="FLUX dev transformer in ComfyUI int8_tensorwise, from a community repack (no "
+ "first-party int8 build of FLUX.1 exists). Half the memory of the bfloat16 transformer at 8 bits "
+ "per weight, on every supported GPU - FLUX.1 dev (quantized) is smaller still, at 4. Total size "
+ "with dependencies: ~18GB",
+ type=ModelType.Main,
+ dependencies=[t5_8b_quantized_encoder, flux_vae, clip_l_encoder],
+)
+
flux_dev = StarterModel(
name="FLUX.1 dev",
base=BaseModelType.Flux,
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index 6e75a4e756..9ae2ec837f 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -349,7 +349,9 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensor
)
-def reject_unmarked_int8_weights(sd: dict[str, Any], markers: Mapping[str, Any], architecture: str) -> None:
+def reject_unmarked_int8_weights(
+ sd: dict[str, Any], markers: Mapping[str, Any], architecture: str, model: torch.nn.Module | None = None
+) -> None:
"""Refuse a checkpoint holding an int8 weight that no ``int8_tensorwise`` marker claims.
Call this *outside* the "did we find markers" branch. An int8 weight whose marker is missing --
@@ -367,12 +369,21 @@ def reject_unmarked_int8_weights(sd: dict[str, Any], markers: Mapping[str, Any],
marker on the *weight* at ``foo.qkv`` exempted a packed sidecar the decode never places, and a
key shorter than the suffix collapses to the empty string. An int8 tensor under any name but a
marked ``.weight`` is a payload this decode cannot place, and saying so is the whole point.
+
+ Pass ``model`` where the caller has already built it, and the check narrows to weights this
+ model actually consumes -- the same filter :func:`reject_foreign_quantization_scales` applies,
+ for the same reason. A merged single file may bundle a quantized *submodel* beside the
+ transformer; a non-strict load discards those keys rather than casting them, so they cannot
+ become noise and are not this loader's business. Without ``model`` every int8 key in ``sd`` is
+ in scope, which is right for a caller that has not built the module tree yet.
"""
+ consumed = None if model is None else {name for name, _ in model.named_modules()}
orphans = sorted(
k
for k, v in sd.items()
if v.dtype is torch.int8
and not (isinstance(k, str) and k.endswith(".weight") and k[: -len(".weight")] in markers)
+ and (consumed is None or (isinstance(k, str) and k.rsplit(".", 1)[0] in consumed))
)
if orphans:
raise ValueError(
diff --git a/tests/app/invocations/test_flux1_denoise_working_memory.py b/tests/app/invocations/test_flux1_denoise_working_memory.py
new file mode 100644
index 0000000000..8805fcf34a
--- /dev/null
+++ b/tests/app/invocations/test_flux1_denoise_working_memory.py
@@ -0,0 +1,176 @@
+"""FLUX.1 denoise wiring: the dequant transient and the sidecar decision.
+
+`peak_dequant_transient_bytes` and `requires_sidecar_patching` are unit-tested next to the module
+they belong to. What is pinned here is the wire -- deleting the `working_mem_bytes=` argument from
+the node, or deciding the sidecar flag from the format alone, leaves every other test green.
+
+Z-Image's equivalent lives in `test_z_image_denoise_working_memory.py`, Krea-2's in
+`test_krea2_denoise.py` and FLUX.2's in `test_flux2_working_memory.py`.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+
+from invokeai.app.invocations.fields import FluxConditioningField
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
+
+
+class _StopBeforeLoad(Exception):
+ """Raised out of the mocked `model_on_device()` so the node stops at the reservation."""
+
+
+def _int8_model(out_features: int, in_features: int) -> torch.nn.Module:
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(
+ torch.zeros(out_features, in_features, dtype=torch.int8),
+ torch.ones(out_features, 1),
+ convrot=False,
+ )
+ return model
+
+
+class TestFlux1:
+ """FLUX.1's node passed no `working_mem_bytes` at all before int8 reached this loader.
+
+ Its largest quantized layer is `single_blocks.N.linear1` at 21504x3072, i.e. a 252 MiB bf16
+ transient on the released repack -- against a card that is already holding 11.5 GiB of weights
+ plus T5-XXL.
+ """
+
+ def _reserved_by(self, transformer: torch.nn.Module, on_device=None) -> int:
+ """`on_device` lets a caller get past the load instead of stopping at it."""
+ from invokeai.app.invocations.flux.flux_denoise import FluxDenoiseInvocation
+
+ transformer_info = MagicMock()
+ transformer_info.model = transformer
+ transformer_info.model_on_device = MagicMock(side_effect=on_device or _StopBeforeLoad)
+
+ context = MagicMock()
+ context.models.load.return_value = transformer_info
+ from invokeai.backend.model_manager.taxonomy import FluxVariantType
+
+ context.models.get_config.return_value = SimpleNamespace(
+ base=BaseModelType.Flux,
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=FluxVariantType.Dev,
+ )
+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
+ ConditioningFieldData,
+ FLUXConditioningInfo,
+ )
+
+ context.conditioning.load.return_value = ConditioningFieldData(
+ conditionings=[FLUXConditioningInfo(clip_embeds=torch.zeros(1, 768), t5_embeds=torch.zeros(1, 8, 4096))]
+ )
+
+ invocation = FluxDenoiseInvocation.model_construct(
+ latents=None,
+ noise=None,
+ denoise_mask=None,
+ denoising_start=0.0,
+ denoising_end=1.0,
+ add_noise=True,
+ transformer=MagicMock(transformer=MagicMock(), loras=[]),
+ positive_text_conditioning=FluxConditioningField(conditioning_name="pos", mask=None),
+ negative_text_conditioning=None,
+ control_lora=None,
+ controlnet_vae=None,
+ control=None,
+ ip_adapter=None,
+ kontext_conditioning=None,
+ redux_conditioning=None,
+ cfg_scale=1.0,
+ cfg_scale_start_step=0,
+ cfg_scale_end_step=-1,
+ guidance=4.0,
+ width=256,
+ height=256,
+ num_steps=2,
+ seed=0,
+ )
+
+ with (
+ patch(
+ "invokeai.app.invocations.flux.flux_denoise.TorchDevice.choose_torch_device",
+ return_value=torch.device("cpu"),
+ ),
+ pytest.raises(_StopBeforeLoad),
+ ):
+ invocation._run_diffusion(context)
+
+ transformer_info.model_on_device.assert_called_once()
+ return transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"]
+
+ def test_the_transient_reaches_the_model_cache(self) -> None:
+ reserved = self._reserved_by(_int8_model(1024, CONVROT_GROUP_SIZE))
+
+ assert reserved == 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
+
+ def test_an_unquantized_transformer_asks_for_nothing_extra(self) -> None:
+ dense = torch.nn.Module()
+ dense.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
+
+ assert self._reserved_by(dense) == 0
+
+ @staticmethod
+ def _flux(quantized: bool) -> torch.nn.Module:
+ """A real (tiny) `Flux`, because the node asserts the type before it patches."""
+ from invokeai.backend.flux.model import Flux, FluxParams
+
+ params = FluxParams(
+ in_channels=64,
+ vec_in_dim=768,
+ context_in_dim=4096,
+ hidden_size=CONVROT_GROUP_SIZE,
+ mlp_ratio=4.0,
+ num_heads=2,
+ depth=1,
+ depth_single_blocks=1,
+ axes_dim=[16, 56, 56],
+ theta=10_000,
+ qkv_bias=True,
+ guidance_embed=True,
+ )
+ model = Flux(params)
+ if quantized:
+ model.single_blocks[0].linear1 = Int8ConvrotLinear(
+ torch.zeros(1024, CONVROT_GROUP_SIZE, dtype=torch.int8),
+ torch.ones(1024, 1),
+ convrot=False,
+ )
+ return model
+
+ def _sidecar_flag_at_the_node(self, transformer: torch.nn.Module) -> bool:
+ """What the node actually hands `LayerPatcher`.
+
+ `Checkpoint` is the format an int8 build carries, so the old format-only decision answered
+ "not quantized" and `LayerPatcher` picked direct patching -- which asks an
+ `Int8ConvrotLinear` for a `weight` *parameter* it does not have. Every LoRA on an int8
+ FLUX.1 would die there, with an error naming nothing.
+ """
+ from contextlib import contextmanager
+
+ from invokeai.backend.patches.layer_patcher import LayerPatcher
+
+ captured: dict = {}
+
+ @contextmanager
+ def on_device(**_kwargs):
+ yield (None, transformer)
+
+ def apply_patches(**kwargs):
+ captured["force_sidecar_patching"] = kwargs["force_sidecar_patching"]
+ raise _StopBeforeLoad
+
+ with patch.object(LayerPatcher, "apply_smart_model_patches", staticmethod(apply_patches)):
+ self._reserved_by(transformer, on_device=on_device)
+ return captured["force_sidecar_patching"]
+
+ def test_the_node_asks_the_model_and_not_only_the_format(self) -> None:
+ assert self._sidecar_flag_at_the_node(self._flux(quantized=True)) is True
+ assert self._sidecar_flag_at_the_node(self._flux(quantized=False)) is False
diff --git a/tests/backend/model_manager/load/state_dicts/flux1_dev_int8_convrot_keys.py b/tests/backend/model_manager/load/state_dicts/flux1_dev_int8_convrot_keys.py
new file mode 100644
index 0000000000..9beea70ea3
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux1_dev_int8_convrot_keys.py
@@ -0,0 +1,98 @@
+"""Representative key layout of the `int8_tensorwise` FLUX.1 [dev] repack.
+
+Captured from `AX1Y2JP/FLUX.1-dev-INT8-ConvRot` (`flux1-dev-int8-convrot.safetensors`),
+a community repack -- neither BFL nor Comfy-Org publishes an int8 build of FLUX.1.
+
+This is the scheme in its usual form, unlike the FLUX.2 Klein fixture beside it: the marker is
+`{"format": "int8_tensorwise", "per_row": true, "convrot": true, "convrot_groupsize": 256}`,
+so the weights were rotated along their input dimension before quantization and the scales are
+per-output-channel `[out, 1]` rather than scalars.
+
+What it quantizes is its own choice and worth reading: both attention `qkv` tensors but
+*neither* `attn.proj`, both MLPs, and every modulation `lin`. `img_in`, `txt_in`, `time_in`,
+`vector_in`, `guidance_in` and `final_layer` stay BF16.
+
+No key conversion stands between these names and the module tree -- `FluxCheckpointModel`
+builds the BFL `Flux` class directly and `qkv` stays one fused Linear -- which is what makes
+this the simple case next to FLUX.2.
+
+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.bias": ([3072], "BF16"),
+ "double_blocks.0.img_attn.proj.weight": ([3072, 3072], "BF16"),
+ "double_blocks.0.img_attn.qkv.bias": ([9216], "BF16"),
+ "double_blocks.0.img_attn.qkv.comfy_quant": ([89], "U8"),
+ "double_blocks.0.img_attn.qkv.weight": ([9216, 3072], "I8"),
+ "double_blocks.0.img_attn.qkv.weight_scale": ([9216, 1], "F32"),
+ "double_blocks.0.img_mlp.0.bias": ([12288], "BF16"),
+ "double_blocks.0.img_mlp.0.comfy_quant": ([89], "U8"),
+ "double_blocks.0.img_mlp.0.weight": ([12288, 3072], "I8"),
+ "double_blocks.0.img_mlp.0.weight_scale": ([12288, 1], "F32"),
+ "double_blocks.0.img_mlp.2.bias": ([3072], "BF16"),
+ "double_blocks.0.img_mlp.2.comfy_quant": ([89], "U8"),
+ "double_blocks.0.img_mlp.2.weight": ([3072, 12288], "I8"),
+ "double_blocks.0.img_mlp.2.weight_scale": ([3072, 1], "F32"),
+ "double_blocks.0.img_mod.lin.bias": ([18432], "BF16"),
+ "double_blocks.0.img_mod.lin.comfy_quant": ([89], "U8"),
+ "double_blocks.0.img_mod.lin.weight": ([18432, 3072], "I8"),
+ "double_blocks.0.img_mod.lin.weight_scale": ([18432, 1], "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.bias": ([3072], "BF16"),
+ "double_blocks.0.txt_attn.proj.weight": ([3072, 3072], "BF16"),
+ "double_blocks.0.txt_attn.qkv.bias": ([9216], "BF16"),
+ "double_blocks.0.txt_attn.qkv.comfy_quant": ([89], "U8"),
+ "double_blocks.0.txt_attn.qkv.weight": ([9216, 3072], "I8"),
+ "double_blocks.0.txt_attn.qkv.weight_scale": ([9216, 1], "F32"),
+ "double_blocks.0.txt_mlp.0.bias": ([12288], "BF16"),
+ "double_blocks.0.txt_mlp.0.comfy_quant": ([89], "U8"),
+ "double_blocks.0.txt_mlp.0.weight": ([12288, 3072], "I8"),
+ "double_blocks.0.txt_mlp.0.weight_scale": ([12288, 1], "F32"),
+ "double_blocks.0.txt_mlp.2.bias": ([3072], "BF16"),
+ "double_blocks.0.txt_mlp.2.comfy_quant": ([89], "U8"),
+ "double_blocks.0.txt_mlp.2.weight": ([3072, 12288], "I8"),
+ "double_blocks.0.txt_mlp.2.weight_scale": ([3072, 1], "F32"),
+ "double_blocks.0.txt_mod.lin.bias": ([18432], "BF16"),
+ "double_blocks.0.txt_mod.lin.comfy_quant": ([89], "U8"),
+ "double_blocks.0.txt_mod.lin.weight": ([18432, 3072], "I8"),
+ "double_blocks.0.txt_mod.lin.weight_scale": ([18432, 1], "F32"),
+ "final_layer.adaLN_modulation.1.bias": ([6144], "BF16"),
+ "final_layer.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.linear.bias": ([64], "BF16"),
+ "final_layer.linear.weight": ([64, 3072], "BF16"),
+ "guidance_in.in_layer.bias": ([3072], "BF16"),
+ "guidance_in.in_layer.weight": ([3072, 256], "BF16"),
+ "guidance_in.out_layer.bias": ([3072], "BF16"),
+ "guidance_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "img_in.bias": ([3072], "BF16"),
+ "img_in.weight": ([3072, 64], "BF16"),
+ "single_blocks.0.linear1.bias": ([21504], "BF16"),
+ "single_blocks.0.linear1.comfy_quant": ([89], "U8"),
+ "single_blocks.0.linear1.weight": ([21504, 3072], "I8"),
+ "single_blocks.0.linear1.weight_scale": ([21504, 1], "F32"),
+ "single_blocks.0.linear2.bias": ([3072], "BF16"),
+ "single_blocks.0.linear2.comfy_quant": ([89], "U8"),
+ "single_blocks.0.linear2.weight": ([3072, 15360], "I8"),
+ "single_blocks.0.linear2.weight_scale": ([3072, 1], "F32"),
+ "single_blocks.0.modulation.lin.bias": ([9216], "BF16"),
+ "single_blocks.0.modulation.lin.comfy_quant": ([89], "U8"),
+ "single_blocks.0.modulation.lin.weight": ([9216, 3072], "I8"),
+ "single_blocks.0.modulation.lin.weight_scale": ([9216, 1], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "time_in.in_layer.bias": ([3072], "BF16"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.bias": ([3072], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.bias": ([3072], "BF16"),
+ "txt_in.weight": ([3072, 4096], "BF16"),
+ "vector_in.in_layer.bias": ([3072], "BF16"),
+ "vector_in.in_layer.weight": ([3072, 768], "BF16"),
+ "vector_in.out_layer.bias": ([3072], "BF16"),
+ "vector_in.out_layer.weight": ([3072, 3072], "BF16"),
+}
diff --git a/tests/backend/model_manager/load/test_flux1_int8_convrot_keys.py b/tests/backend/model_manager/load/test_flux1_int8_convrot_keys.py
new file mode 100644
index 0000000000..fa3a91b1b0
--- /dev/null
+++ b/tests/backend/model_manager/load/test_flux1_int8_convrot_keys.py
@@ -0,0 +1,96 @@
+"""What the released `int8_tensorwise` FLUX.1 repack actually contains.
+
+The loader suite beside this one runs on a synthetic tiny geometry, which cannot say whether the
+*real* file still looks the way the loader assumes. This one reads the captured key layout and
+pins the three properties the decode depends on. Each is a thing a re-upload could change without
+any loader code moving:
+
+- the marker body, which is where `convrot` and the group size live;
+- the group alignment, which is what makes a rotated weight decodable at all;
+- the scale layout, which decides whether the scale multiplies rows or columns.
+"""
+
+import json
+
+import torch
+
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ INT8_TENSORWISE_FORMAT,
+ as_column_scale,
+ check_int8_scale_layout,
+)
+from tests.backend.model_manager.load.state_dicts.flux1_dev_int8_convrot_keys import (
+ state_dict_keys as flux1_keys,
+)
+
+MARKER = {"format": INT8_TENSORWISE_FORMAT, "per_row": True, "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
+
+QUANTIZED = sorted(key[: -len(".weight")] for key, (_, dtype) in flux1_keys.items() if dtype == "I8")
+
+
+def test_the_fixture_is_the_marker_this_suite_assumes() -> None:
+ """The recorded blob length is 89 bytes, which is exactly the marker spelled out above.
+
+ A re-capture from a repack that dropped `convrot`, or changed the group size, moves that length
+ -- and the loader tests would otherwise keep exercising the rotated case against a file that no
+ longer rotates, which is the one mistake that loads cleanly and generates noise.
+ """
+ lengths = {tuple(shape) for key, (shape, _) in flux1_keys.items() if key.endswith(".comfy_quant")}
+
+ assert lengths == {(len(json.dumps(MARKER).encode("utf-8")),)}
+
+
+def test_every_quantized_layer_is_marked_and_scaled() -> None:
+ # No orphan codes and no orphan scales: the two halves `reject_unmarked_int8_weights` and
+ # `reject_foreign_quantization_scales` exist to keep matched.
+ assert QUANTIZED, "fixture carries no int8 weights"
+ for path in QUANTIZED:
+ assert flux1_keys.get(f"{path}.comfy_quant"), path
+ assert flux1_keys.get(f"{path}.weight_scale"), path
+ scaled = {key[: -len(".weight_scale")] for key in flux1_keys if key.endswith(".weight_scale")}
+ assert scaled == set(QUANTIZED)
+
+
+def test_every_quantized_weight_is_a_whole_number_of_rotation_groups_wide() -> None:
+ """`convrot` rotates in groups of 256 along the input dim.
+
+ A layer that is not a multiple of that cannot be derotated at all -- `build_regular_hadamard`
+ refuses it -- so this is the property that decides whether the released file is loadable. It
+ also explains why the repack leaves `img_in` (64 wide) alone.
+ """
+ for path in QUANTIZED:
+ in_features = flux1_keys[f"{path}.weight"][0][1]
+ assert in_features % CONVROT_GROUP_SIZE == 0, f"{path} is {in_features} wide"
+
+
+def test_the_scales_are_per_output_channel() -> None:
+ """`[out, 1]`, not `[out]` and not a block grid.
+
+ Broadcasting aligns trailing dimensions, so an `[out]` scale would multiply along the *input*
+ axis instead -- for a square weight that is silent, and this repack has plenty of square ones.
+ """
+ for path in QUANTIZED:
+ weight_shape, _ = flux1_keys[f"{path}.weight"]
+ scale_shape, scale_dtype = flux1_keys[f"{path}.weight_scale"]
+ assert scale_dtype == "F32", path
+ assert scale_shape == [weight_shape[0], 1], path
+
+ # Through the helpers the loader uses, so a layout change is caught as the loader sees it.
+ weight = torch.zeros(weight_shape, dtype=torch.int8)
+ scale = torch.zeros(scale_shape, dtype=torch.float32)
+ check_int8_scale_layout(path, weight, scale)
+ assert as_column_scale(weight, scale).shape == (weight_shape[0], 1)
+
+
+def test_the_repack_leaves_the_embedders_and_the_output_projection_dense() -> None:
+ # Not a requirement of the loader -- `Flux` declares no skip patterns and nothing in its forward
+ # reads `weight.dtype` -- but it is what the fixture documents, and a re-capture that quantized
+ # them would make the loader suite's "dense remainder" assertions meaningless.
+ dense = {
+ key[: -len(".weight")] for key, (shape, dtype) in flux1_keys.items() if dtype == "BF16" and len(shape) == 2
+ }
+
+ for path in ("img_in", "txt_in", "time_in.in_layer", "vector_in.in_layer", "final_layer.linear"):
+ assert path in dense, path
+ assert "double_blocks.0.img_attn.proj" in dense, "this repack leaves attn.proj dense"
diff --git a/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
new file mode 100644
index 0000000000..857844b5fb
--- /dev/null
+++ b/tests/backend/model_manager/load/test_flux1_int8_convrot_loader.py
@@ -0,0 +1,367 @@
+"""Loader-level tests for the `int8_tensorwise` FLUX.1 path.
+
+These drive `FluxCheckpointModel._load_from_singlefile` and assert the end state of the module:
+which layers keep their codes, what weight they reconstruct, and what the cache was asked to free.
+
+FLUX.1 is the simple shape of this scheme next to FLUX.2: no key conversion stands between a
+marker and its module, and `qkv` stays one fused Linear. What it does have, and Klein 9B does not,
+is the scheme's full form -- `convrot` at group size 256 with per-output-channel scales -- so a
+loader that ignored the rotation would produce a weight that loads cleanly and generates noise.
+"""
+
+import json
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.backend.flux.model import FluxParams
+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_FLUX_Config
+from invokeai.backend.model_manager.load.model_loaders.flux import FluxCheckpointModel
+from invokeai.backend.model_manager.taxonomy import FluxVariantType
+from invokeai.backend.quantization.int8_convrot import (
+ CONVROT_GROUP_SIZE,
+ Int8ConvrotLinear,
+ build_regular_hadamard,
+)
+
+# As the file carries it: rotated along the input dim, per-output-channel scales.
+MARKER = {"format": "int8_tensorwise", "per_row": True, "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
+
+# The released geometry scaled down: convrot works in groups of 256 along the input dim, so the
+# hidden size cannot go below one group. One double and one single block is enough -- the file
+# quantizes the same six layer kinds in every block.
+TINY = FluxParams(
+ in_channels=64,
+ vec_in_dim=768,
+ context_in_dim=4096,
+ hidden_size=CONVROT_GROUP_SIZE,
+ mlp_ratio=4.0,
+ num_heads=2,
+ depth=1,
+ depth_single_blocks=1,
+ axes_dim=[16, 56, 56],
+ theta=10_000,
+ qkv_bias=True,
+ guidance_embed=True,
+)
+
+# What this repack quantizes: both `qkv`, both MLPs, every modulation `lin` -- and, notably, not
+# `attn.proj`. `adaln`/embedders/final layer stay dense.
+QUANTIZED = (
+ "double_blocks.0.img_attn.qkv",
+ "double_blocks.0.img_mlp.0",
+ "double_blocks.0.img_mlp.2",
+ "double_blocks.0.img_mod.lin",
+ "double_blocks.0.txt_attn.qkv",
+ "single_blocks.0.linear1",
+ "single_blocks.0.linear2",
+ "single_blocks.0.modulation.lin",
+)
+
+
+def _marker_blob(marker: dict) -> torch.Tensor:
+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()
+
+
+def _quantize_convrot(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""
+ out_features, in_features = weight.shape
+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)
+ rotated = (weight.view(out_features, in_features // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ hadamard.T).view(
+ out_features, in_features
+ )
+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0
+ return torch.clamp(torch.round(rotated / 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(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 the compute width, comes up short by its size.
+STORED_FP32 = "img_in.weight"
+
+# W8A8 metadata for a mode this path does not implement. The load tolerates extras, but the cast
+# and the reservation would both pay for it.
+ACTIVATION_SCALE = "double_blocks.0.img_attn.qkv.input_scale"
+
+
+def _checkpoint(marker: dict | None = MARKER) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
+ """A full state dict for the tiny geometry with `QUANTIZED` stored int8_tensorwise+convrot."""
+ torch.manual_seed(0)
+ with torch.device("cpu"):
+ from invokeai.backend.flux.model import Flux
+
+ reference = Flux(TINY)
+ state_dict = {key: value.clone().to(torch.bfloat16) for key, value in reference.state_dict().items()}
+ state_dict[STORED_FP32] = state_dict[STORED_FP32].float()
+ state_dict[ACTIVATION_SCALE] = torch.ones((), dtype=torch.float32)
+
+ originals: dict[str, torch.Tensor] = {}
+ for path in QUANTIZED:
+ key = f"{path}.weight"
+ weight = state_dict[key].float()
+ originals[path] = weight
+ state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_convrot(weight)
+ if marker is not None:
+ state_dict[f"{path}.comfy_quant"] = _marker_blob(marker)
+ return state_dict, originals
+
+
+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 / "flux1-dev-int8-convrot.safetensors"
+ checkpoint.touch()
+ config = Main_Checkpoint_FLUX_Config.model_construct(
+ path=str(checkpoint), name="flux1-dev-int8", variant=FluxVariantType.Dev
+ )
+
+ loader = object.__new__(FluxCheckpointModel)
+ loader._ram_cache = SimpleNamespace(make_room=lambda reserved: recorded.__setitem__("reserved", reserved))
+ 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)
+ monkeypatch.setattr(module, "get_flux_transformers_params", lambda _variant: TINY)
+ 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_and_un_rotates(monkeypatch, tmp_path) -> None:
+ """The end state, not the decision.
+
+ `Int8ConvrotLinear` holds the stored codes, which is the point -- the file's size is the
+ resident size. The weight it reconstructs must also be the *un-rotated* one: a checkpoint sent
+ down the fp8 path instead would be scaled but never derotated, which loads cleanly and
+ generates noise.
+ """
+ state_dict, originals = _checkpoint()
+
+ model = _load(monkeypatch, tmp_path, state_dict)
+
+ for path in QUANTIZED:
+ layer = model.get_submodule(path)
+ assert isinstance(layer, Int8ConvrotLinear), path
+ assert layer.weight.dtype is torch.int8, path
+ assert layer.convrot is True, path
+ # int8 keeps ~2 decimal digits, so this is "the rotation was undone", not a bit compare:
+ # a weight left rotated is a different tensor entirely, not a rounder one.
+ reconstructed = layer._dequantized_weight(torch.device("cpu"), torch.float32)
+ original = originals[path]
+ assert torch.allclose(reconstructed, original, rtol=0.05, atol=0.05 * original.abs().max()), path
+
+
+def test_the_biases_of_the_quantized_layers_survive(monkeypatch, tmp_path) -> None:
+ """`qkv` and the modulation projections carry biases, and the swap has to keep them.
+
+ `Int8ConvrotLinear` takes its bias from the checkpoint, so a swap that dropped it would leave
+ every block's attention and modulation without its offset -- and still load.
+ """
+ state_dict, _ = _checkpoint()
+ expected = {path: state_dict[f"{path}.bias"].clone() for path in QUANTIZED if f"{path}.bias" in state_dict}
+ assert expected, "fixture carries no biases on the quantized layers"
+
+ model = _load(monkeypatch, tmp_path, state_dict)
+
+ for path, bias in expected.items():
+ assert torch.equal(model.get_submodule(path).bias.to(bias.dtype), bias), path
+
+
+def test_the_reservation_charges_each_payload_its_stored_width(monkeypatch, tmp_path) -> None:
+ """The cache frees what it is asked for, so this number is the load's whole memory contract.
+
+ Charging an int8 payload bf16's two bytes evicts roughly twice what an 11.5 GiB file needs.
+ """
+ state_dict, _ = _checkpoint()
+ before_load = {key: value.clone() for key, value in state_dict.items()}
+ trace: dict = {}
+
+ _load(monkeypatch, tmp_path, state_dict, trace)
+
+ # One byte per code; its per-output-channel scale stays at the fp32 it is pinned at; the marker
+ # and the activation scale are dropped before the load and charged nothing; everything else
+ # arrives at the compute width -- including the layer the checkpoint stored as fp32, charged
+ # what it becomes rather than what it was.
+ pinned = {f"{path}.{suffix}" for path in QUANTIZED for suffix in ("weight", "weight_scale")}
+ expected = 0
+ for key, tensor in before_load.items():
+ if key.endswith(".comfy_quant") or key == ACTIVATION_SCALE:
+ continue
+ expected += tensor.nelement() * (tensor.element_size() if key in pinned else torch.bfloat16.itemsize)
+
+ assert trace["reserved"] == expected
+
+
+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."""
+ state_dict, _ = _checkpoint(marker=None)
+
+ with pytest.raises(ValueError, match="int8"):
+ _load(monkeypatch, tmp_path, state_dict)
+
+
+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 only one in the wild.
+
+ A repack that declares its scheme in `_quantization_metadata` alone would otherwise be refused
+ for a marker it never had to write.
+ """
+ state_dict, originals = _checkpoint(marker=None)
+ header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}
+
+ model = _load(monkeypatch, tmp_path, state_dict, header=header)
+
+ for path in QUANTIZED:
+ layer = model.get_submodule(path)
+ assert isinstance(layer, Int8ConvrotLinear), path
+ # The marker *body* has to survive that route too, not just the layer name: a header that
+ # arrived without `convrot` would build every layer unrotated, and an unrotated decode of a
+ # rotated weight loads cleanly and generates noise.
+ assert layer.convrot is True, path
+ reconstructed = layer._dequantized_weight(torch.device("cpu"), torch.float32)
+ original = originals[path]
+ assert torch.allclose(reconstructed, original, rtol=0.05, atol=0.05 * original.abs().max()), 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
+ # decides how the weight is decoded. Deliberately the opposite of the fp8 hint merge beside it.
+ state_dict, originals = _checkpoint(marker={**MARKER, "convrot": False})
+ for path in QUANTIZED:
+ weight = originals[path]
+ scale = weight.abs().amax(dim=1, keepdim=True) / 127.0
+ state_dict[f"{path}.weight"] = torch.clamp(torch.round(weight / scale), -128, 127).to(torch.int8)
+ state_dict[f"{path}.weight_scale"] = scale.to(torch.float32)
+ header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}
+
+ model = _load(monkeypatch, tmp_path, state_dict, header=header)
+
+ assert model.get_submodule(QUANTIZED[0]).convrot is False
+
+
+def test_a_header_that_names_a_layer_this_file_does_not_quantize_is_ignored(monkeypatch, tmp_path) -> None:
+ """Stale metadata must not route a plain checkpoint into the int8 branch.
+
+ A repack tool that left `_quantization_metadata` behind on a bf16 export would otherwise take
+ the whole file down the int8 path and die at the swap, complaining about a missing
+ `weight_scale` for a layer that was never quantized -- pointing at a header the user cannot see.
+ """
+ state_dict, originals = _checkpoint(marker=None)
+ for path in QUANTIZED:
+ del state_dict[f"{path}.weight_scale"]
+ state_dict[f"{path}.weight"] = originals[path].to(torch.bfloat16)
+ header = {"_quantization_metadata": json.dumps({"layers": dict.fromkeys(QUANTIZED, MARKER)})}
+
+ model = _load(monkeypatch, tmp_path, state_dict, header=header)
+
+ assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())
+
+
+def test_an_int8_weight_the_transformer_does_not_consume_is_tolerated(monkeypatch, tmp_path) -> None:
+ """A merged export bundles an encoder beside the transformer.
+
+ Those keys are discarded by the non-strict load rather than cast, so they cannot become noise --
+ the same reasoning `reject_foreign_quantization_scales` already applies to a foreign scale.
+ Refusing the whole file for them would reject a checkpoint that loads correctly today.
+ """
+ state_dict, _ = _checkpoint()
+ state_dict["text_encoders.t5xxl.block.0.attn.q.weight"] = torch.zeros(8, 8, dtype=torch.int8)
+
+ model = _load(monkeypatch, tmp_path, state_dict)
+
+ assert isinstance(model.get_submodule(QUANTIZED[0]), Int8ConvrotLinear)
+
+
+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, so an fp8 layer that came along
+ would be cast to bf16 without its scale -- off by `1/weight_scale`, with nothing logged."""
+ state_dict, _ = _checkpoint()
+ weight = state_dict["double_blocks.0.img_attn.proj.weight"].float()
+ scale = weight.abs().max() / 448.0
+ state_dict["double_blocks.0.img_attn.proj.weight"] = (weight / scale).to(torch.float8_e4m3fn)
+ state_dict["double_blocks.0.img_attn.proj.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_plain_checkpoint_still_takes_the_fp8_path(monkeypatch, tmp_path) -> None:
+ # The other half: a file with no int8 in it must reach the scaled-fp8 pipeline unchanged.
+ 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)
+
+ model = _load(monkeypatch, tmp_path, state_dict)
+
+ assert not any(isinstance(module, Int8ConvrotLinear) for module in model.modules())
+ for path in QUANTIZED:
+ assert model.get_submodule(path).weight.dtype is torch.bfloat16, path
+
+
+def test_the_dense_remainder_is_cast_to_the_compute_dtype(monkeypatch, tmp_path) -> None:
+ """`assign=True` hands the checkpoint's storage dtype straight to the module.
+
+ The fixture stores one layer as fp32, which is what makes this able to fail: without the cast an
+ fp32 `img_in` lands inside a bf16 model.
+ """
+ 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)
+
+ assert model.img_in.weight.dtype is torch.bfloat16
+
+
+def test_the_fp8_storage_pass_is_not_offered_an_int8_model(monkeypatch, tmp_path) -> None:
+ """FP8 Storage is a per-model setting offered for every FLUX main model.
+
+ On an int8 build the cast cannot reach the quantized weights at all, and what it *can* reach is
+ the dense remainder the repack deliberately left bf16 -- the embedders and the final layer, 3.6%
+ of the file. So it is skipped rather than allowed to spend e4m3 on the model's entry and exit.
+ """
+ from invokeai.backend.model_manager.taxonomy import SubModelType
+
+ state_dict, _ = _checkpoint()
+ 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 == []
+ 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 setting quietly
+ # stops working for ordinary FLUX.1 checkpoints.
+ from invokeai.backend.model_manager.taxonomy import SubModelType
+
+ 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())