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(ideogram-4): load int8_convrot single files
Alexander Eichhorn3593648d9962
diff --git a/docs/src/content/docs/concepts/models.mdx b/docs/src/content/docs/concepts/models.mdxindex 0565be0543..e698f6fff1 100644--- a/docs/src/content/docs/concepts/models.mdx+++ b/docs/src/content/docs/concepts/models.mdx@@ -66,17 +66,32 @@ Paste either repo ID into the Model Manager's HuggingFace / URL field to install#### Single files-Comfy-Org's [`Comfy-Org/Ideogram-4`](https://huggingface.co/Comfy-Org/Ideogram-4) repackage is ungated (the same non-commercial license still applies) and ships the parts separately. Ideogram 4 runs **two** transformers — a conditional branch and an unconditional one, both active at every step — so a single-file install is four models, and the **Ideogram 4 (single file)** starter installs all four together:+Comfy-Org's [`Comfy-Org/Ideogram-4`](https://huggingface.co/Comfy-Org/Ideogram-4) repackage is ungated (the same non-commercial license still applies) and ships the parts separately. Ideogram 4 runs **two** transformers — a conditional branch and an unconditional one, both active at every step — so a single-file install is four models, and each starter installs all four together:-- `diffusion_models/ideogram4_fp8_scaled.safetensors` — the conditional branch, selected as the model-- `diffusion_models/ideogram4_unconditional_fp8_scaled.safetensors` — the unconditional branch+- `diffusion_models/ideogram4_<build>.safetensors` — the conditional branch, selected as the model+- `diffusion_models/ideogram4_unconditional_<build>.safetensors` — the unconditional branch- `text_encoders/qwen3vl_8b_fp8_scaled.safetensors` — the Qwen3-VL **8B** encoder (not the 4B one Krea-2 uses)- `vae/flux2-vae.safetensors` — the 32-channel VAE, shared with FLUX.2, which is why it installs under the FLUX.2 base-Pick the unconditional branch, the encoder and the VAE in the **Components** section next to the model. The `int8_convrot` and `nvfp4` repackages in that repo are **not** supported yet and are refused at install.+Pick the unconditional branch, the encoder and the VAE in the **Components** section next to the model — and pick the unconditional branch of the *same* build as the model. The `nvfp4` repackage in that repo is **not** supported yet and is refused at install.-:::note[Memory]-Both branches stay resident, so the fp8 pair needs roughly twice one file's size. Without `fp8_compute` the scaled fp8 weights are expanded to bf16 on load — about 35 GB for the pair — so on 24 GB cards the bundled nf4 build remains the smaller option.+Which branch a file holds is read from the file itself, and from the filename for a build that does not record it, so keep these names as published.++Two builds of the transformers are supported, and they behave differently in memory:++| | download, per branch | resident, per branch |+|---|---|---|+| **Ideogram 4 (single file, int8)** — `int8_convrot` | 8.9 GB | **8.9 GB**, on every device |+| **Ideogram 4 (single file, fp8)** — `fp8_scaled` | 8.6 GB | 8.7 GB with `fp8_compute`, ~17 GB without |++Both branches are resident at once, so double those figures for the pair.++:::note[Which to pick]+**On an NVIDIA Ada card (RTX 40-series) or newer, with `fp8_compute` enabled**, take the fp8 build: the two are a wash on memory, and fp8 is the faster one because its weights stay quantized *and* run on the fp8 tensor cores. Measured at 1024px on a 4090, 12 steps: **35.6 s** for the fp8 pair against **45.7 s** for the int8 pair.++**Everywhere else, use int8.** Without `fp8_compute` the fp8 weights are expanded to bf16 on load — about 35 GB for the pair, which does not fit a 24 GB card — while int8 keeps its stored codes and dequantizes them per forward, on any device and with no setting to turn on. Those ~10 s are what the dequantization costs, and they buy the difference between the model fitting and not fitting.++On a 24 GB NVIDIA card without the fp8 matmul (RTX 30-series), the int8 pair plus the 8B encoder still adds up to more than the card holds, so the bundled [nf4 build](#installing-ideogram-4) remains the smaller option there.:::### Prompting Ideogram 4diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex 5f10658033..79bbcd8328 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -21,8 +21,10 @@ from invokeai.backend.ideogram4.sampler_configs import PRESETSfrom invokeai.backend.ideogram4.sampling_utils import PIXELS_PER_IMAGE_TOKEN, unpatchify_and_denormalizefrom invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPairfrom invokeai.backend.model_manager.taxonomy import BaseModelType+from invokeai.backend.quantization.int8_convrot import peak_int8_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Ideogram4ConditioningInfofrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.fp8 import get_model_compute_dtype# Named sampler presets bundle step count, guidance schedule (with polish tail), and the# logit-normal schedule mean/std. V4_QUALITY_48 is the reference default.@@ -211,14 +213,30 @@ class Ideogram4DenoiseInvocation(BaseInvocation):pair (~17.5 GB) the headroom runs out somewhere above 1300px: past that the cache cannotsatisfy the reservation, the second branch loses residency and streams. That is not theestimate being wrong -- the memory genuinely is not there -- and reserving less would only- exchange a slow generation for an out-of-memory error. The fix for large images is smaller- weights (the int8 and nvfp4 builds), not a smaller number here.+ exchange a slow generation for an out-of-memory error, and the remedy is fewer resident+ bytes rather than a smaller number here. The int8 build does not supply them: it is the same+ ~8.9 GiB per branch as fp8 with `fp8_compute`. What it buys is that this holds on *every*+ device, where the fp8 pair doubles to ~35 GiB without the fp8 matmul."""image_tokens = (self.height // PIXELS_PER_IMAGE_TOKEN) * (self.width // PIXELS_PER_IMAGE_TOKEN)per_token_bytes = 3 * 1024**2 // 4 # 0.75 MiBbase_bytes = 3 * 1024**3 // 2 # 1.5 GiBreturn (image_tokens + num_text_tokens) * per_token_bytes + base_bytes+ @staticmethod+ def _dequant_transient(model: object) -> int:+ """What an int8 build transiently needs to dequantize its largest layer, per forward.++ `Int8ConvrotLinear` keeps the stored codes and materializes the dequantized, derotated+ weight inside `forward`, so that peak is not part of the model's resident size and has to+ fit inside the caller's reservation. Zero for a bf16 or fp8 build -- which is why it is+ measured from the model rather than from the resolution: the two branches are separate+ models and may be different builds.+ """+ if not isinstance(model, torch.nn.Module):+ return 0+ return peak_int8_dequant_transient_bytes(model, get_model_compute_dtype(model))+def _load_branches(self, context: InvocationContext, stack: ExitStack, working_mem_bytes: int) -> tuple[Ideogram4Transformer, Ideogram4Transformer]:@@ -228,34 +246,55 @@ class Ideogram4DenoiseInvocation(BaseInvocation):files are two models and are locked simultaneously, because every step runs both andreleasing one between steps would make the cache stream it back for the next.- Both are given the same `working_mem_bytes`: each `model_on_device` decides how much of its- own model fits, and a reservation passed to only the first would be spent by the second.- """- primary = stack.enter_context(- context.models.load(self.transformer.transformer).model_on_device(working_mem_bytes=working_mem_bytes)- )[1]+ Both locks get the *same* reservation even though the dequantization transient is per branch+ and the two branches can be different builds. The cache computes free VRAM as+ `capacity - working_mem - in_use` at each lock, and the second lock cannot claw space back+ from the first, which is already locked: a first branch that reserved less has taken+ headroom the second one still needs, and with the second branch already resident from an+ earlier run there is nothing left to evict.- if self.unconditional_transformer is None:- if not isinstance(primary, Ideogram4TransformerPair):- raise ValueError(- "This Ideogram 4 transformer holds only one branch, so 'Transformer (Unconditional)' "- "must be connected as well. The Ideogram 4 model loader emits it when the model is a "- "single-file checkpoint."- )- return primary.conditional, primary.unconditional+ Taking the maximum up front costs reading `LoadedModel.model` -- documented as returning the+ model unlocked, and it is already constructed by then -- and loading the second branch into+ RAM before the first is locked. Under the default `keep_ram_copy_of_weights` that is not a+ new peak, since both branches hold their RAM copies through the loop anyway; with RAM copies+ off it is one cold load's worth, which the cache absorbs the same way it absorbs any+ overshoot. Neither branch can be evicted meanwhile: `LoadedModel` takes a first-use hold the+ moment it is constructed, and `make_room` skips a record that has one.+ """+ conditional_info = context.models.load(self.transformer.transformer)+ both_in_one = isinstance(conditional_info.model, Ideogram4TransformerPair)- if isinstance(primary, Ideogram4TransformerPair):+ # Checked before the second model is loaded, so a mis-wired graph costs an error rather than+ # a ~9 GiB read. Real checks, not asserts: a hand-built graph can wire anything here, and+ # under `python -O` an assert would vanish and leave the mismatch to surface inside the loop.+ if both_in_one and self.unconditional_transformer is not None:raise ValueError("'Transformer' already carries both Ideogram 4 branches, so 'Transformer (Unconditional)' ""must not be connected. Disconnect it, or select a single-file checkpoint as the model.")- unconditional = stack.enter_context(- context.models.load(self.unconditional_transformer.transformer).model_on_device(- working_mem_bytes=working_mem_bytes+ if not both_in_one and self.unconditional_transformer is None:+ raise ValueError(+ "This Ideogram 4 transformer holds only one branch, so 'Transformer (Unconditional)' "+ "must be connected as well. The Ideogram 4 model loader emits it when the model is a "+ "single-file checkpoint.")- )[1]- # A real check, not an assert: a hand-built graph can wire any transformer here, and under- # `python -O` an assert would vanish and leave the mismatch to surface inside the loop.++ second = self.unconditional_transformer+ unconditional_info = None if second is None else context.models.load(second.transformer)+ reservation = working_mem_bytes + max(+ self._dequant_transient(conditional_info.model),+ 0 if unconditional_info is None else self._dequant_transient(unconditional_info.model),+ )++ primary = stack.enter_context(conditional_info.model_on_device(working_mem_bytes=reservation))[1]+ if unconditional_info is None:+ # Narrowing, not validation: `both_in_one` was decided from this same object above, and+ # locking it does not change what it is. The user-facing refusals are the two checks+ # further up, which is why they are `raise` and this is not.+ assert isinstance(primary, Ideogram4TransformerPair)+ return primary.conditional, primary.unconditional++ unconditional = stack.enter_context(unconditional_info.model_on_device(working_mem_bytes=reservation))[1]for role, branch in (("Transformer", primary), ("Transformer (Unconditional)", unconditional)):if not isinstance(branch, Ideogram4Transformer):raise ValueError(diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex fe32d5e2a5..53d1c52bfd 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -57,6 +57,7 @@ from invokeai.backend.model_manager.taxonomy import (ZImageVariantType,)from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT, read_comfy_quant_markersfrom invokeai.backend.quantization.sdnq.detection import is_sdnq_folderfrom invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor@@ -1448,7 +1449,10 @@ def _has_ideogram4_keys(state_dict: dict[str | int, Any]) -> bool:def _ideogram4_branch_from_filename(filename: str) -> Ideogram4Branch:- """Fallback for files whose metadata was stripped by a re-upload or a repack tool.+ """The branch for a file that declares none.++ Not only a fallback for a stripped re-upload: the released `int8_convrot` pair carries no+ `model_type` at all, so this is the sole path for that build.Only the unconditional file is named for its branch, so anything else is read as the conditionalbranch — the same default direction as the released naming. Both spellings are accepted: the@@ -1466,17 +1470,19 @@ class Main_Checkpoint_Ideogram4_Config(Checkpoint_Config_Base, Main_Config_Base,FLUX.2 VAE are separate models, selected on the loader node; the diffusers pipeline folder(``Main_Diffusers_Ideogram4_Config``) is the variant that bundles everything.- Quantization: plain bf16/fp16 and ComfyUI "scaled fp8" load. The ``int8_convrot`` and ``nvfp4``- repacks of the same files are recognised and rejected with `InvalidMatchError`, which keeps them- out of the database entirely -- `NotAMatchError` would let them fall through to `Unknown_Config`- and register a 9 GiB file that nothing can ever load.+ Quantization: plain bf16/fp16, ComfyUI "scaled fp8" and ComfyUI ``int8_tensorwise``(+convrot)+ all load. The ``nvfp4`` repack of the same files is recognised and rejected with+ `InvalidMatchError`, which keeps it out of the database entirely -- `NotAMatchError` would let+ it fall through to `Unknown_Config` and register a 5 GiB file that nothing can ever load."""base: Literal[BaseModelType.Ideogram4] = Field(default=BaseModelType.Ideogram4)format: Literal[ModelFormat.Checkpoint] = Field(default=ModelFormat.Checkpoint)branch: Ideogram4Branch = Field(description="Which of Ideogram 4's two transformer branches this file holds. Read from the "- "file's `model_type` metadata, with the filename as the fallback for stripped re-uploads."+ "file's `model_type` metadata where it has any, and from the filename otherwise — the "+ "released int8 build records no metadata at all, so keep those files under their published "+ "names. Rename and re-install to correct it.")@classmethod@@ -1492,7 +1498,7 @@ class Main_Checkpoint_Ideogram4_Config(Checkpoint_Config_Base, Main_Config_Base,if _has_ggml_tensors(state_dict):raise NotAMatchError("GGUF-quantized Ideogram 4 checkpoints are not supported yet")- cls._raise_for_unsupported_quantization(state_dict)+ cls._raise_for_unsupported_quantization(mod, state_dict)branch = override_fields.pop("branch", None) or cls._branch_or_raise(mod)@@ -1521,29 +1527,58 @@ class Main_Checkpoint_Ideogram4_Config(Checkpoint_Config_Base, Main_Config_Base,return branch@classmethod- def _raise_for_unsupported_quantization(cls, state_dict: dict[str | int, Any]) -> None:- """Refuse the quantization schemes this loader cannot yet build.+ def _raise_for_unsupported_quantization(cls, mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:+ """Refuse the quantization schemes this loader cannot build.`InvalidMatchError`, not `NotAMatchError`: the file *is* an Ideogram 4 transformer, so theright outcome is a refusal the installer shows, not a fall-through to `Unknown_Config` thatregisters it as a model nothing can load.- Neither scheme is visible in one fixed tensor: the int8_convrot repack leaves the input- projection bf16 and quantizes the block linears, and nvfp4 packs two codes per byte, so a- uint8 weight is indistinguishable from the `comfy_quant` markers every repack carries --- including the supported fp8 one. The per-tensor `weight_scale_2` is what only nvfp4 writes,- and int8 is a dtype nothing else here uses.+ Two of them. nvfp4 packs two codes per byte, so its uint8 weights are indistinguishable from+ the `comfy_quant` markers every repack carries -- including the two supported ones; the+ per-tensor `weight_scale_2` is what only nvfp4 writes.++ And int8 weights *without* a readable `int8_tensorwise` marker: the loader refuses those+ (`reject_unmarked_int8_weights`), because a rotated weight loaded as if it were not one+ generates noise. Refusing them here too is what keeps that refusal at install time -- a+ torchao or `int8_dynamic` repack of this architecture would otherwise register as a 9 GiB+ model, pull in its three starter dependencies, and fail at the first render.++ The markers come from the file's header rather than from `state_dict`: identification loads+ tensors on the meta device, so it has every dtype and shape but no bytes to parse. That read+ is a header parse plus one seek per marker, and it only happens for a file that has int8+ weights to explain in the first place."""if any(isinstance(key, str) and key.endswith(".weight_scale_2") for key in state_dict):raise InvalidMatchError("this is an nvfp4-quantized Ideogram 4 transformer, which is not supported yet. "- "Install the fp8_scaled build instead (ideogram4_fp8_scaled.safetensors)."+ "Install the fp8_scaled or int8_convrot build instead.")- if any(getattr(value, "dtype", None) is torch.int8 for value in state_dict.values()):+ int8_weights = sorted(+ key+ for key, value in state_dict.items()+ if isinstance(key, str) and key.endswith(".weight") and getattr(value, "dtype", None) is torch.int8+ )+ if not int8_weights:+ return++ try:+ markers = read_comfy_quant_markers(mod.path)+ except Exception:+ # Not readable safetensors, so there are no markers to find and nothing explains the+ # int8 weights. The refusal below is the right answer for that file too.+ markers = {}+ unmarked = [+ key+ for key in int8_weights+ if markers.get(key[: -len(".weight")], {}).get("format") != INT8_TENSORWISE_FORMAT+ ]+ if unmarked:raise InvalidMatchError(- "this is an int8-quantized Ideogram 4 transformer, which is not supported yet. "- "Install the fp8_scaled build instead (ideogram4_fp8_scaled.safetensors)."+ f"{len(unmarked)} int8 weight(s) in this Ideogram 4 transformer carry no readable "+ f"'{INT8_TENSORWISE_FORMAT}' marker (e.g. '{unmarked[0]}'), so the quantization scheme "+ "cannot be identified. Only Comfy-Org's int8_convrot build is supported.")diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex 2eebfaafdd..0011fa5d53 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -35,6 +35,7 @@ from invokeai.backend.model_manager.taxonomy import (SubModelType,)from invokeai.backend.quantization.fp8_scaled import (+ Fp8ScaledLayer,attach_fp8_scales,cast_state_dict,dequantize_fp8_scaled,@@ -48,6 +49,16 @@ from invokeai.backend.quantization.fp8_scaled import (split_fp8_scaled_layers,warn_on_unattached_scales,)+from invokeai.backend.quantization.int8_convrot import (+ 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.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys@@ -258,11 +269,18 @@ class Ideogram4CheckpointModel(ModelLoader):as its own model and the loader node pairs them, which is why this returns a bare transformerwhere the diffusers loader returns an ``Ideogram4TransformerPair``.- Handles plain bf16/fp16 and ComfyUI "scaled fp8" (fp8 weight + per-tensor ``.weight_scale``,- plus ``.comfy_quant`` markers). The fp8 weights are kept quantized when the device can run the- fp8 matmul and folded into the compute dtype otherwise -- the same trade every other- single-file loader here makes, and the reason a 8.6 GiB file needs ~17 GiB resident without- ``fp8_compute``.+ Three storage schemes, distinguished by what sits next to the weights:++ - plain bf16/fp16 -- loaded verbatim;+ - ComfyUI "scaled fp8" (fp8 weight + per-tensor ``.weight_scale``, plus ``.comfy_quant``+ markers), kept quantized when the device can run the fp8 matmul and folded into the compute+ dtype otherwise -- the same trade every other single-file loader here makes, and the reason an+ 8.6 GiB file needs ~17 GiB resident without ``fp8_compute``;+ - ComfyUI ``int8_tensorwise`` + ``convrot`` (int8 weight + per-output-channel ``.weight_scale``),+ kept in ``Int8ConvrotLinear`` and dequantized per forward, so the file's size is the resident+ size with no setting to enable and no dependence on the device.++ nvfp4 is refused at identification, not here."""def _load_model(@@ -288,43 +306,83 @@ class Ideogram4CheckpointModel(ModelLoader):sd: dict[str, torch.Tensor] = load_file(model_path)- # Per-layer `.comfy_quant` markers are popped out of `sd` here; the header carries the same- # flags on some repacks and wins where both are present. Read before anything consumes the- # weights: `extract_fp8_scaled_layers` drops what is left of the side channel.- layer_hints = {- **extract_comfy_quant_hints(sd),- **parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger)),- }-- fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)- keep_fp8 = should_keep_fp8_weights(target_device)- if fp8_layers and not keep_fp8:- # Fold the scales in. Staying quantized without the fp8 matmul would halve VRAM but- # dequantize on every forward, so both are tied to the same setting.- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)- fp8_layers = {}+ # 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.+ int8_markers = extract_int8_convrot_markers(sd)+ # Outside the branch on purpose (see the helper): an int8 weight whose marker is missing or+ # unparseable would otherwise be cast to the compute dtype as raw codes and load silently.+ reject_unmarked_int8_weights(sd, int8_markers, "Ideogram 4")++ fp8_layers: dict[str, Fp8ScaledLayer] = {}+ keep_fp8 = False+ if not int8_markers:+ # Per-layer `.comfy_quant` markers are popped out of `sd` here; the header carries the+ # same flags on some repacks and wins where both are present. Read before anything+ # consumes the weights: `extract_fp8_scaled_layers` drops what is left of the side+ # channel.+ layer_hints = {+ **extract_comfy_quant_hints(sd),+ **parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger)),+ }++ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)+ keep_fp8 = should_keep_fp8_weights(target_device)+ if fp8_layers and not keep_fp8:+ # Fold the scales in. Staying quantized without the fp8 matmul would halve VRAM but+ # dequantize on every forward, so both are tied to the same setting.+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)+ fp8_layers = {}with accelerate.init_empty_weights():model: torch.nn.Module = Ideogram4Transformer(Ideogram4Config())- # `input_proj` and `t_embedding` must not stay fp8 -- the model derives its activation dtype- # from their weights (see `Ideogram4Transformer._skip_layerwise_casting_patterns`).+ # `input_proj` and `t_embedding` must not stay quantized in either scheme -- the model+ # derives its activation dtype from their weights, and neither float8 nor int8 is a dtype+ # torch computes in (see `Ideogram4Transformer._skip_layerwise_casting_patterns`). The+ # released int8 build leaves both dense anyway; this holds for a repack that does not.skip_patterns = _model_declared_skip_patterns(model)- # Reserve before the split: it dequantizes the layers it cannot keep through float32, and a- # reservation made afterwards lets that transient peak land on an unreserved cache.- self._ram_cache.make_room(- predict_cast_state_dict_size(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- scaled_layers=fp8_layers,+ if int8_markers:+ # W8A8 activation scales and any marker of another format: meaningless on this path,+ # which dequantizes the weight and computes in `model_dtype`. They are dropped rather+ # than tolerated because the load below is strict -- and because they would otherwise be+ # cast and counted against the reservation for nothing.+ # Rebinding is safe here where z_image filters in place: `sd` is the only reference to+ # the dict, and the `sd.clear()` after the load acts on whatever `sd` names then -- the+ # same dict `load_state_dict(assign=True)` aliased its parameters from.+ 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, "Ideogram 4", model)++ # Reserve before the split for the same reason as below, and charge the int8 payloads+ # their actual one byte rather than the compute dtype's two.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns))- )- fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)- kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)+ kept = 0+ else:+ # Reserve before the split: it dequantizes the layers it cannot keep through float32,+ # and a reservation made afterwards lets that transient peak land on an unreserved cache.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ scaled_layers=fp8_layers,+ )+ )+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)# Strict: the released files are key-for-key this model, so a missing or extra key means a# different checkpoint, not a benign naming difference.@@ -333,6 +391,16 @@ class Ideogram4CheckpointModel(ModelLoader):# keeps the originals from staying reachable beside any fp8 copy made below.sd.clear()+ 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.9 GiB file stays 8.9 GiB resident on+ # every device. What it does not get is int8 *compute*.+ self._logger.info(+ f"Ideogram 4: kept {len(quantized)} layer(s) in int8 (int8_tensorwise checkpoint, "+ "dequantized per forward)"+ )+ return model+if kept and not fp8_layers:self._logger.info(f"Ideogram 4: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.pyindex 4dd890914b..75224e2dec 100644--- a/invokeai/backend/model_manager/starter_models/__init__.py+++ b/invokeai/backend/model_manager/starter_models/__init__.py@@ -125,9 +125,11 @@ from invokeai.backend.model_manager.starter_models.flux2 import ()from invokeai.backend.model_manager.starter_models.ideogram_4 import (ideogram_4_fp8,+ ideogram_4_int8,ideogram_4_nf4,ideogram_4_qwen3_vl_encoder_8b,ideogram_4_single_file,+ ideogram_4_unconditional_int8,ideogram_4_unconditional_single_file,)from invokeai.backend.model_manager.starter_models.krea_2 import (@@ -276,6 +278,8 @@ STARTER_MODELS: list[StarterModel] = [ideogram_4_fp8,ideogram_4_single_file,ideogram_4_unconditional_single_file,+ ideogram_4_int8,+ ideogram_4_unconditional_int8,ideogram_4_qwen3_vl_encoder_8b,cyberrealistic_sd1,rev_animated_sd1,diff --git a/invokeai/backend/model_manager/starter_models/ideogram_4.py b/invokeai/backend/model_manager/starter_models/ideogram_4.pyindex 919ba320ee..37870c4877 100644--- a/invokeai/backend/model_manager/starter_models/ideogram_4.py+++ b/invokeai/backend/model_manager/starter_models/ideogram_4.py@@ -35,8 +35,13 @@ ideogram_4_fp8 = StarterModel(# step, so the conditional transformer pulls the unconditional one in as a dependency along with the# encoder and the VAE. The repo is ungated, unlike the diffusers pipelines above, but the same# non-commercial license applies.+#+# The build is named on both branches of both pairs, because the user picks the unconditional branch+# by name in Components and any conditional accepts any unconditional. Dropping it from one name is+# how a user ends up guiding an int8 branch against an fp8 one without meaning to.ideogram_4_unconditional_single_file = StarterModel(- name="Ideogram 4 Unconditional (single file)",+ name="Ideogram 4 Unconditional (single file, fp8)",+ previous_names=["Ideogram 4 Unconditional (single file)"],base=BaseModelType.Ideogram4,source="https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_unconditional_fp8_scaled.safetensors",description="The unconditional branch of Ideogram 4, in ComfyUI scaled fp8. Useless on its own — "@@ -55,8 +60,32 @@ ideogram_4_qwen3_vl_encoder_8b = StarterModel(format=ModelFormat.Checkpoint,)+ideogram_4_unconditional_int8 = StarterModel(+ name="Ideogram 4 Unconditional (single file, int8)",+ base=BaseModelType.Ideogram4,+ source="https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_unconditional_int8_convrot.safetensors",+ description="The unconditional branch of Ideogram 4, in ComfyUI int8_tensorwise. Useless on its "+ "own — Ideogram 4 guides its conditional branch against this one. ~8.9GB",+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+)++ideogram_4_int8 = StarterModel(+ name="Ideogram 4 (single file, int8)",+ base=BaseModelType.Ideogram4,+ source="https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_int8_convrot.safetensors",+ description="Comfy-Org single-file Ideogram 4 in ComfyUI int8_tensorwise. Unlike the fp8 build "+ "it stays at its download size in memory on every device — 8.9GB per branch rather than ~17GB — "+ "because the weights are dequantized per forward instead of on load. Installs the unconditional "+ "branch, the Qwen3-VL 8B encoder and the VAE with it. Non-commercial license. ~28GB total",+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+ dependencies=[ideogram_4_unconditional_int8, ideogram_4_qwen3_vl_encoder_8b, flux2_vae],+)+ideogram_4_single_file = StarterModel(- name="Ideogram 4 (single file)",+ name="Ideogram 4 (single file, fp8)",+ previous_names=["Ideogram 4 (single file)"],base=BaseModelType.Ideogram4,source="https://huggingface.co/Comfy-Org/Ideogram-4/resolve/main/diffusion_models/ideogram4_fp8_scaled.safetensors",description="Comfy-Org single-file Ideogram 4 in ComfyUI scaled fp8. Installs the unconditional "diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex 4a6ceea97e..72406486e3 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -144,6 +144,36 @@ def parse_comfy_quant_bytes(raw: bytes) -> dict:return parsed if isinstance(parsed, dict) else {}+def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:+ """Every ``<layer>.comfy_quant`` marker in a safetensors file, read from the header alone.++ A header parse plus one seek per marker blob -- no tensor data. Two callers need the scheme+ before they have the weights: a loader deciding whether to commit to a ~20 GiB read, and model+ identification, whose state dict is on the meta device and therefore carries shapes and dtypes+ but no bytes to parse. Keys are the raw (un-renamed) layer names.++ Marker bytes go through the same tolerant parser the state-dict readers use. This reader runs+ FIRST, so a strict parse here is what a NUL-padded marker -- which Comfy writes, and which that+ parser exists to absorb -- would actually hit: a `JSONDecodeError` out of the middle of a load,+ naming neither the file nor the key.++ Raises whatever the file does (`OSError`, `struct.error`, `json.JSONDecodeError`) for a path+ that is not readable safetensors; callers that reach this with an unvalidated file catch it.+ """+ markers: dict[str, dict[str, Any]] = {}+ with open(path, "rb") as f:+ header_len = struct.unpack("<Q", f.read(8))[0]+ header = json.loads(f.read(header_len))+ header.pop("__metadata__", None)+ for key, entry in header.items():+ if not key.endswith(".comfy_quant"):+ continue+ start, end = entry["data_offsets"]+ f.seek(8 + header_len + start)+ markers[key[: -len(".comfy_quant")]] = parse_comfy_quant_bytes(f.read(end - start))+ return markers++def parse_comfy_quant_marker(blob: torch.Tensor) -> dict:"""Decode a ``<layer>.comfy_quant`` uint8 tensor into its JSON dict, or ``{}``."""try:@@ -415,8 +445,8 @@ def resolve_quantized_module_paths(return resolved-def _resolve_int8_target(model: torch.nn.Module, path: str) -> tuple[torch.nn.Module, str]:- """The owner and attribute name of the module a marker names, as ``setattr`` needs them.+def _resolve_int8_target(model: torch.nn.Module, path: str) -> tuple[torch.nn.Module, str, torch.nn.Linear]:+ """The owner, attribute name and module a marker names, as ``setattr`` and the swap need them.Refuses anything an ``Int8ConvrotLinear`` cannot stand in for. Without this, a marker naming amodule the built model lacks leaves ``get_submodule`` to raise a bare ``AttributeError`` out of@@ -437,7 +467,7 @@ def _resolve_int8_target(model: torch.nn.Module, path: str) -> tuple[torch.nn.Mof"'{path}' is marked int8_tensorwise but is a {type(target).__name__}, not an nn.Linear. ""Only a Linear weight can be kept in int8 storage.")- return parent, attribute+ return parent, attribute, targetdef _can_stay_int8(path: str, weight: Any, model: torch.nn.Module | None, skip_patterns: Iterable[str] = ()) -> bool:@@ -610,7 +640,19 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:"Only a Linear weight can be kept in int8 storage; dequantize this one instead.")check_int8_scale_layout(path, weight, scale)- parent, attribute = _resolve_int8_target(model, path)+ parent, attribute, target = _resolve_int8_target(model, path)+ bias = sd.get(f"{path}.bias")+ if (bias is None) is not (target.bias is None):+ # The replacement's buffers are whatever the checkpoint supplied, so from here on the+ # module's key set mirrors the file rather than the architecture -- and the strict+ # `load_state_dict` the loaders run afterwards can no longer tell the two apart. A+ # repack that drops all-zero biases would otherwise load, cache and render with every+ # quantized layer silently missing its offset.+ missing, extra = ("checkpoint", "model") if bias is None else ("model", "checkpoint")+ raise ValueError(+ f"'{path}' is marked int8_tensorwise and the {extra}'s Linear has a bias, but the "+ f"{missing} has none. The checkpoint does not match this architecture."+ )setattr(parent,attribute,@@ -618,7 +660,7 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:weight=weight,weight_scale=scale,convrot=bool(marker.get("convrot", False)),- bias=sd.get(f"{path}.bias"),+ bias=bias,group_size=int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE)),),)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 8e0c0087bf..60a882a89c 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -63244,7 +63244,7 @@"type": "string","enum": ["conditional", "unconditional"],"title": "Branch",- "description": "Which of Ideogram 4's two transformer branches this file holds. Read from the file's `model_type` metadata, with the filename as the fallback for stripped re-uploads."+ "description": "Which of Ideogram 4's two transformer branches this file holds. Read from the file's `model_type` metadata where it has any, and from the filename otherwise \u2014 the released int8 build records no metadata at all, so keep those files under their published names. Rename and re-install to correct it."}},"type": "object",@@ -63269,7 +63269,7 @@"branch"],"title": "Main_Checkpoint_Ideogram4_Config",- "description": "Model config for Ideogram 4 single-file transformer checkpoints (safetensors).\n\nOne file holds ONE of the two dual-branch transformers. The Qwen3-VL 8B text encoder and the\nFLUX.2 VAE are separate models, selected on the loader node; the diffusers pipeline folder\n(``Main_Diffusers_Ideogram4_Config``) is the variant that bundles everything.\n\nQuantization: plain bf16/fp16 and ComfyUI \"scaled fp8\" load. The ``int8_convrot`` and ``nvfp4``\nrepacks of the same files are recognised and rejected with `InvalidMatchError`, which keeps them\nout of the database entirely -- `NotAMatchError` would let them fall through to `Unknown_Config`\nand register a 9 GiB file that nothing can ever load."+ "description": "Model config for Ideogram 4 single-file transformer checkpoints (safetensors).\n\nOne file holds ONE of the two dual-branch transformers. The Qwen3-VL 8B text encoder and the\nFLUX.2 VAE are separate models, selected on the loader node; the diffusers pipeline folder\n(``Main_Diffusers_Ideogram4_Config``) is the variant that bundles everything.\n\nQuantization: plain bf16/fp16, ComfyUI \"scaled fp8\" and ComfyUI ``int8_tensorwise``(+convrot)\nall load. The ``nvfp4`` repack of the same files is recognised and rejected with\n`InvalidMatchError`, which keeps it out of the database entirely -- `NotAMatchError` would let\nit fall through to `Unknown_Config` and register a 5 GiB file that nothing can ever load."},"Main_Checkpoint_Krea2_Config": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex fb6b00bf1e..d2a6a1b50f 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -25806,10 +25806,10 @@ export type components = {* FLUX.2 VAE are separate models, selected on the loader node; the diffusers pipeline folder* (``Main_Diffusers_Ideogram4_Config``) is the variant that bundles everything.*- * Quantization: plain bf16/fp16 and ComfyUI "scaled fp8" load. The ``int8_convrot`` and ``nvfp4``- * repacks of the same files are recognised and rejected with `InvalidMatchError`, which keeps them- * out of the database entirely -- `NotAMatchError` would let them fall through to `Unknown_Config`- * and register a 9 GiB file that nothing can ever load.+ * Quantization: plain bf16/fp16, ComfyUI "scaled fp8" and ComfyUI ``int8_tensorwise``(+convrot)+ * all load. The ``nvfp4`` repack of the same files is recognised and rejected with+ * `InvalidMatchError`, which keeps it out of the database entirely -- `NotAMatchError` would let+ * it fall through to `Unknown_Config` and register a 5 GiB file that nothing can ever load.*/Main_Checkpoint_Ideogram4_Config: {/**@@ -25896,7 +25896,7 @@ export type components = {format: "checkpoint";/*** Branch- * @description Which of Ideogram 4's two transformer branches this file holds. Read from the file's `model_type` metadata, with the filename as the fallback for stripped re-uploads.+ * @description Which of Ideogram 4's two transformer branches this file holds. Read from the file's `model_type` metadata where it has any, and from the filename otherwise — the released int8 build records no metadata at all, so keep those files under their published names. Rename and re-install to correct it.* @enum {string}*/branch: "conditional" | "unconditional";diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex d084068ec5..1c95824de9 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -777,7 +777,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {branch: 'conditional',format: 'checkpoint',key: 'ideogram4-cond',- name: 'Ideogram 4 (single file)',+ name: 'Ideogram 4 (single file, fp8)',type: 'main',};const ideogram4Unconditional: MainModelConfig = {@@ -785,7 +785,7 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {branch: 'unconditional',format: 'checkpoint',key: 'ideogram4-uncond',- name: 'Ideogram 4 Unconditional (single file)',+ name: 'Ideogram 4 Unconditional (single file, fp8)',type: 'main',};const ideogram4Vae: VaeModelConfig = { base: 'flux2', key: 'flux2-vae', name: 'FLUX.2 VAE', type: 'vae' };diff --git a/tests/app/invocations/test_ideogram4_denoise_branches.py b/tests/app/invocations/test_ideogram4_denoise_branches.pyindex da8c995431..6e29345f90 100644--- a/tests/app/invocations/test_ideogram4_denoise_branches.py+++ b/tests/app/invocations/test_ideogram4_denoise_branches.py@@ -19,6 +19,7 @@ from invokeai.app.invocations.model import ModelIdentifierField, TransformerFielfrom invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogram4Transformerfrom invokeai.backend.ideogram4.transformer_pair import Ideogram4TransformerPairfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,Ideogram4ConditioningInfo,@@ -46,9 +47,14 @@ def _field(key: str) -> TransformerField:class _LoadedModel:- """The slice of `LoadedModel` this method uses, plus a record of how it was entered and left."""+ """The slice of `LoadedModel` this method uses, plus a record of how it was entered and left.++ `model` is the real attribute name: the node reads it before locking, to see whether the branch+ is an int8 build whose per-forward dequantization needs headroom of its own.+ """def __init__(self, model: torch.nn.Module, calls: list[tuple[str, int]], released: list[str], key: str) -> None:+ self.model = modelself._model = modelself._calls = callsself._released = released@@ -64,14 +70,24 @@ class _LoadedModel:def _context(- models: dict[str, torch.nn.Module], released: list[str], calls: list[tuple[str, int]] | None = None+ models: dict[str, torch.nn.Module],+ released: list[str],+ calls: list[tuple[str, int]] | None = None,+ loaded: list[str] | None = None,) -> SimpleNamespace:+ """`calls` records the *locks* and their reservations; `loaded` records the RAM-level loads.++ They are separate because the node's ordering distinguishes them: it reads both branches before+ locking either, and refuses a mis-wired graph before reading the second.+ """recorded = calls if calls is not None else []- return SimpleNamespace(- models=SimpleNamespace(- load=lambda identifier: _LoadedModel(models[identifier.key], recorded, released, identifier.key)- )- )+ reads = loaded if loaded is not None else []++ def load(identifier: ModelIdentifierField) -> _LoadedModel:+ reads.append(identifier.key)+ return _LoadedModel(models[identifier.key], recorded, released, identifier.key)++ return SimpleNamespace(models=SimpleNamespace(load=load))def _invocation(**fields) -> Ideogram4DenoiseInvocation:@@ -99,8 +115,10 @@ def test_two_single_files_are_both_held_for_the_whole_loop() -> None:invocation = _invocation(transformer=_field("cond"))invocation.unconditional_transformer = _field("uncond")+ loaded: list[str] = []+ calls: list[tuple[str, int]] = []with ExitStack() as stack:- conditional, unconditional = invocation._load_branches(_context(models, released), stack, 0)+ conditional, unconditional = invocation._load_branches(_context(models, released, calls, loaded), stack, 0)assert conditional is models["cond"]assert unconditional is models["uncond"]@@ -108,6 +126,10 @@ def test_two_single_files_are_both_held_for_the_whole_loop() -> None:assert released == []assert sorted(released) == ["cond", "uncond"]+ # Both branches are read before either is locked, which is what lets the reservation below be+ # the maximum of the two rather than each branch's own.+ assert loaded == ["cond", "uncond"]+ assert [key for key, _ in calls] == ["cond", "uncond"]def test_a_lone_single_file_is_refused() -> None:@@ -126,11 +148,72 @@ def test_a_bundled_pair_with_a_second_branch_connected_is_refused() -> None:invocation = _invocation(transformer=_field("pipeline"))invocation.unconditional_transformer = _field("uncond")+ loaded: list[str] = []with pytest.raises(ValueError, match="already carries both"), ExitStack() as stack:invocation._load_branches(- _context({"pipeline": pair, "uncond": Ideogram4Transformer(TINY)}, released), stack, 0+ _context({"pipeline": pair, "uncond": Ideogram4Transformer(TINY)}, released, loaded=loaded), stack, 0)+ # The refusal comes before the second branch is read: a mis-wired graph costs an error, not a+ # ~9 GiB load of a model the node is about to reject. The node reads both branches before it+ # locks either, so this is the ordering that has to be pinned, not the locking.+ assert loaded == ["pipeline"]+++def _int8_branch() -> Ideogram4Transformer:+ """A tiny branch whose largest linear is stored int8, as the `int8_convrot` build's are.++ In bfloat16 because that is what the loader produces, and the transient is two weight-sized+ tensors *in the compute dtype* -- a float32 model would quietly double the expected number.+ """+ model = Ideogram4Transformer(TINY).to(torch.bfloat16)+ linear = model.layers[0].feed_forward.w1+ model.layers[0].feed_forward.w1 = Int8ConvrotLinear(+ weight=torch.zeros(linear.out_features, linear.in_features, dtype=torch.int8),+ weight_scale=torch.ones(linear.out_features, 1),+ convrot=False,+ )+ return model+++def test_an_int8_branch_adds_its_dequantization_headroom() -> None:+ """`Int8ConvrotLinear` materializes the dequantized weight inside `forward`.++ That peak is not part of the model's resident size, so it has to be reserved — and it is+ measured from the model, since a bf16 or fp8 branch needs none of it.+ """+ dense = Ideogram4Transformer(TINY).to(torch.bfloat16)+ int8 = _int8_branch()+ largest = int8.layers[0].feed_forward.w1++ assert Ideogram4DenoiseInvocation._dequant_transient(dense) == 0+ assert Ideogram4DenoiseInvocation._dequant_transient(int8) == (+ 2 * largest.in_features * largest.out_features * torch.bfloat16.itemsize+ )++[email protected]("int8_branch", ["cond", "uncond"])+def test_a_mixed_pair_reserves_for_the_hungrier_branch(int8_branch: str) -> None:+ """The cache keeps the *last* lock's reservation, not the sum.++ Free VRAM is recomputed as `capacity - working_mem - in_use` at every lock, so a branch that+ reserves less hands back exactly the headroom the other one still needs. Both orders are pinned+ because both occur: the loader node allows an int8 branch guided against an fp8 one in either+ slot, and reserving only for the first branch would leave one of the two orders green.+ """+ models = {"cond": Ideogram4Transformer(TINY).to(torch.bfloat16), "uncond": Ideogram4Transformer(TINY)}+ models[int8_branch] = _int8_branch()+ calls: list[tuple[str, int]] = []+ invocation = _invocation(transformer=_field("cond"))+ invocation.unconditional_transformer = _field("uncond")+ transient = Ideogram4DenoiseInvocation._dequant_transient(models[int8_branch])+ assert transient > 0++ with ExitStack() as stack:+ invocation._load_branches(_context(models, [], calls), stack, 4 * 1024**3)++ assert calls == [("cond", 4 * 1024**3 + transient), ("uncond", 4 * 1024**3 + transient)]+def test_both_branches_reserve_the_same_activation_headroom() -> None:"""A reservation given to only the first branch is spent by the second.diff --git a/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py b/tests/backend/minimax_h3/test_pruned_transformer_and_converter.pyindex 65a86f2cc0..07719bb538 100644--- a/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py+++ b/tests/backend/minimax_h3/test_pruned_transformer_and_converter.py@@ -214,26 +214,6 @@ def test_converted_keys_match_full_model_exactly() -> None:model.load_state_dict(converted, strict=True, assign=True)-def test_read_comfy_quant_markers_from_header_only(tmp_path) -> None:- from safetensors.torch import save_file-- from invokeai.backend.quantization.int8_convrot import read_comfy_quant_markers-- marker_json = b'{"format": "fp8_scaled", "convrot": false}'- path = tmp_path / "tiny.safetensors"- save_file(- {- "blocks.0.mlp.fc2.weight": torch.zeros(2, 2),- "blocks.0.mlp.fc2.comfy_quant": torch.frombuffer(marker_json, dtype=torch.uint8).clone(),- "unrelated.weight": torch.zeros(1),- },- str(path),- )-- markers = read_comfy_quant_markers(path)- assert markers == {"blocks.0.mlp.fc2": {"format": "fp8_scaled", "convrot": False}}--def test_converter_swaps_fused_swiglu_halves() -> None:"""The remote-code fused fc1 stores [gate; value]; diffusers SwiGLU expects [value; gate](silu on the SECOND half). Verified bit-exactly against the diffusers folder release:diff --git a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.pyindex e487b5b551..a819f32272 100644--- a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py+++ b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py@@ -9,6 +9,7 @@ and lets the file fall through to `Unknown_Config`, which would register a 9 GiBmodel record nothing can load."""+import jsonfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import MagicMock, patch@@ -21,6 +22,8 @@ from invokeai.backend.model_manager.configs.identification_utils import InvalidMfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Ideogram4_Configfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}+_REQUIRED_FIELDS = {"hash": "blake3:fakehash","path": "/fake/models/ideogram4_fp8_scaled.safetensors",@@ -46,6 +49,19 @@ def _state_dict(**overrides: Any) -> dict[str, Any]:return sd+def _int8_layer(path: str, marker: dict | None = MARKER) -> dict[str, Any]:+ """One layer as the `int8_convrot` build stores it: codes, per-output-channel scale, marker."""+ layer: dict[str, Any] = {+ f"{path}.weight": torch.zeros(24, 8, dtype=torch.int8),+ f"{path}.weight_scale": torch.zeros(24, 1, dtype=torch.float32),+ }+ if marker is not None:+ layer[f"{path}.comfy_quant"] = torch.frombuffer(+ bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8+ ).clone()+ return layer++def _mod(state_dict: dict[str, Any], *, metadata: dict[str, str] | None = None, name: str = "ideogram4.safetensors"):mod = MagicMock()mod.path = Path(f"/fake/{name}")@@ -54,6 +70,22 @@ def _mod(state_dict: dict[str, Any], *, metadata: dict[str, str] | None = None,return mod+def _mod_on_disk(state_dict: dict[str, Any], tmp_path: Path, *, name: str = "ideogram4.safetensors"):+ """A mod whose `path` is a real file, for the checks that read the safetensors header.++ Marker *contents* are not in the state dict identification sees -- it is on the meta device --+ so the int8 refusal seeks into the file. A `MagicMock` path would make every one of those tests+ pass for the wrong reason.+ """+ path = tmp_path / name+ save_file(state_dict, path)+ mod = MagicMock()+ mod.path = path+ mod.load_state_dict.return_value = state_dict+ mod.metadata.return_value = {}+ return mod++def _identify(mod: MagicMock, **override_fields: Any) -> Main_Checkpoint_Ideogram4_Config:with (patch("invokeai.backend.model_manager.configs.main.raise_if_not_file"),@@ -151,15 +183,38 @@ class TestRefusals:with pytest.raises(InvalidMatchError, match="nvfp4"):_identify(_mod(sd))- def test_rejects_the_int8_repack(self) -> None:- # As released: bf16 input projection, int8 block linears.- sd = _state_dict(**{"layers.0.attention.qkv.weight": torch.zeros(24, 8, dtype=torch.int8)})+ def test_accepts_the_int8_repack(self, tmp_path: Path) -> None:+ # As released: bf16 input projection, int8 block linears with per-output-channel scales and+ # an `int8_tensorwise` marker each. This build carries no `model_type` metadata at all, so+ # its branch comes from the filename -- which makes that fallback load-bearing here rather+ # than a courtesy.+ sd = _state_dict(**_int8_layer("layers.0.attention.qkv"))- with pytest.raises(InvalidMatchError, match="int8"):- _identify(_mod(sd))+ config = _identify(_mod_on_disk(sd, tmp_path, name="ideogram4_unconditional_int8_convrot.safetensors"))++ assert config.branch == "unconditional"++ @pytest.mark.parametrize(+ ("marker", "case"),+ [+ (None, "no marker at all"),+ ({"format": "int8_dynamic"}, "a scheme this loader cannot build"),+ ],+ )+ def test_rejects_int8_weights_with_no_readable_marker(self, tmp_path: Path, marker: dict | None, case: str) -> None:+ """The loader refuses these, so identification has to as well.++ A rotated weight loaded as if it were not one generates noise, which is why+ `reject_unmarked_int8_weights` exists. Letting the file install anyway would move that+ refusal to the first render -- after a 9 GiB download and three installed dependencies.+ """+ sd = _state_dict(**_int8_layer("layers.0.attention.qkv", marker=marker))++ with pytest.raises(InvalidMatchError, match="no readable 'int8_tensorwise' marker"):+ _identify(_mod_on_disk(sd, tmp_path, name="ideogram4_int8.safetensors"))def test_accepts_the_scaled_fp8_release(self) -> None:- # The one quantized build this loader does handle: fp8 weight plus a per-tensor scale.+ # The other quantized build: fp8 weight plus a per-tensor scale.sd = _state_dict(**{"input_proj.weight": torch.zeros(8, 4, dtype=torch.float8_e4m3fn),@@ -181,28 +236,41 @@ class TestRefusalReachesTheInstaller:reports."""- @pytest.mark.parametrize(- ("weight", "expected"),- [- (torch.zeros(24, 8, dtype=torch.int8), "int8"),- (torch.zeros(24, 4, dtype=torch.uint8), "nvfp4"),- ],- )- def test_an_unsupported_repack_is_not_registered_as_unknown(- self, tmp_path: Path, weight: torch.Tensor, expected: str- ) -> None:+ def test_an_unsupported_repack_is_not_registered_as_unknown(self, tmp_path: Path) -> None:from invokeai.backend.model_manager.configs.factory import ModelConfigFactoryfrom invokeai.backend.model_manager.model_on_disk import ModelOnDisk- sd = _state_dict(**{"layers.0.attention.qkv.weight": weight})- if expected == "nvfp4":- sd["layers.0.attention.qkv.weight_scale_2"] = torch.zeros((), dtype=torch.float32)-- checkpoint = tmp_path / "ideogram4_repack.safetensors"+ sd = _state_dict(+ **{+ "layers.0.attention.qkv.weight": torch.zeros(24, 4, dtype=torch.uint8),+ "layers.0.attention.qkv.weight_scale_2": torch.zeros((), dtype=torch.float32),+ }+ )+ checkpoint = tmp_path / "ideogram4_nvfp4_mixed.safetensors"save_file(sd, checkpoint, metadata={"model_type": "ideogram4_cond"})result = ModelConfigFactory.from_model_on_disk(ModelOnDisk(checkpoint), {}, allow_unknown=True)assert result.config is None, "an unsupported repack must not be registered at all"reasons = [str(detail) for detail in result.details.values() if isinstance(detail, InvalidMatchError)]- assert any(expected in reason for reason in reasons), reasons+ assert any("nvfp4" in reason for reason in reasons), reasons++ def test_a_supported_repack_is_registered(self, tmp_path: Path) -> None:+ """The other half of the refusal.++ `InvalidMatchError` suppresses the Unknown fallback for every class, so a detector that+ fired one tensor too wide would take the int8 build down with it — and silently, since the+ symptom is a file that simply stops installing.+ """+ from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+ from invokeai.backend.model_manager.model_on_disk import ModelOnDisk++ sd = _state_dict(**_int8_layer("layers.0.attention.qkv"))+ checkpoint = tmp_path / "ideogram4_int8_convrot.safetensors"+ save_file(sd, checkpoint)++ result = ModelConfigFactory.from_model_on_disk(ModelOnDisk(checkpoint), {}, allow_unknown=True)++ assert result.config is not None+ assert result.config.type is ModelType.Main+ assert getattr(result.config, "branch", None) == "conditional"diff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.pyindex 27498c3cec..6da6d051a8 100644--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py@@ -10,6 +10,7 @@ A tiny `Ideogram4Config` stands in for the released geometry: same module tree,of 458."""+import jsonfrom types import SimpleNamespacefrom unittest.mock import MagicMock@@ -20,6 +21,11 @@ from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Ideogram4_Configfrom invokeai.backend.model_manager.load.model_loaders.ideogram4 import Ideogram4CheckpointModelfrom invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.quantization.int8_convrot import (+ CONVROT_GROUP_SIZE,+ Int8ConvrotLinear,+ build_regular_hadamard,+)FP8 = torch.float8_e4m3fn@@ -34,6 +40,19 @@ TINY_CONFIG = Ideogram4Config(mrope_section=(4, 2, 2),)+# convrot rotates in groups along the input dim, so the int8 cases need a geometry whose linears are+# a whole number of groups wide. Everything else stays as narrow as the released layout allows.+INT8_CONFIG = Ideogram4Config(+ emb_dim=CONVROT_GROUP_SIZE,+ num_layers=1,+ num_heads=2,+ intermediate_size=CONVROT_GROUP_SIZE,+ adanln_dim=CONVROT_GROUP_SIZE,+ in_channels=8,+ llm_features_dim=32,+ mrope_section=(16, 8, 8),+)+# One Linear the cast must keep quantized, and the two it must not.KEPT = "layers.0.feed_forward.w1"SKIPPED = ("input_proj", "t_embedding.mlp_in")@@ -64,7 +83,15 @@ def _checkpoint(paths: tuple[str, ...]) -> tuple[dict[str, torch.Tensor], dict[sreturn state_dict, originals-def _driver(monkeypatch, tmp_path, state_dict: dict, *, keep_fp8: bool, trace: dict | None = None):+def _driver(+ monkeypatch,+ tmp_path,+ state_dict: dict,+ *,+ keep_fp8: bool,+ trace: dict | None = None,+ geometry: Ideogram4Config = TINY_CONFIG,+):"""Drive the loader with the cache and the fp8 storage pass recorded rather than stubbed out.`trace` collects what the loader *did*: `casting_calls` counts entries into@@ -77,6 +104,7 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, *, keep_fp8: bool, trace: drecorded = trace if trace is not None else {}recorded.setdefault("casting_calls", 0)recorded.setdefault("fp8_weights_at_make_room", None)+ recorded.setdefault("reserved", None)checkpoint = tmp_path / "ideogram4_fp8_scaled.safetensors"checkpoint.touch()@@ -84,7 +112,8 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, *, keep_fp8: bool, trace: dpath=str(checkpoint), name="ideogram4", branch="conditional")- def make_room(_bytes: int) -> None:+ def make_room(reserved: int) -> None:+ recorded["reserved"] = reservedrecorded["fp8_weights_at_make_room"] = sum(1 for v in state_dict.values() if v.dtype is FP8)def apply_casting(model, _config, _submodel):@@ -103,15 +132,21 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, *, keep_fp8: bool, trace: dmonkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: None)monkeypatch.setattr(module.TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))monkeypatch.setattr(module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: torch.float32))- monkeypatch.setattr(- "invokeai.backend.ideogram4.modeling_ideogram4.Ideogram4Config", lambda: TINY_CONFIG, raising=True- )+ monkeypatch.setattr("invokeai.backend.ideogram4.modeling_ideogram4.Ideogram4Config", lambda: geometry, raising=True)return loader, config-def _load(monkeypatch, tmp_path, state_dict, *, keep_fp8: bool, trace: dict | None = None) -> torch.nn.Module:- loader, config = _driver(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, trace=trace)- return loader._load_model(config, SubModelType.Transformer)+def _load(+ monkeypatch,+ tmp_path,+ state_dict,+ *,+ keep_fp8: bool,+ trace: dict | None = None,+ geometry: Ideogram4Config = TINY_CONFIG,+) -> torch.nn.Module:+ loader, model_config = _driver(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, trace=trace, geometry=geometry)+ return loader._load_model(model_config, SubModelType.Transformer)def test_without_the_fp8_matmul_the_scales_are_folded_into_full_precision_weights(monkeypatch, tmp_path) -> None:@@ -195,3 +230,201 @@ def test_only_the_transformer_submodel_is_served(monkeypatch, tmp_path) -> None:with pytest.raises(ValueError, match="holds only a transformer"):loader._load_model(config, SubModelType.VAE)+++MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}++# The released int8 build quantizes the six linears of every block and nothing else. `adaln_modulation`+# is the one with a bias, so it is the one worth driving.+INT8_LAYERS = ("layers.0.attention.o", "layers.0.adaln_modulation")+++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]:+ """Per-output-channel int8 with no rotation."""+ scale = weight.abs().amax(dim=1, keepdim=True) / 127.0+ return torch.clamp(torch.round(weight / scale), -128, 127).to(torch.int8), scale.to(torch.float32)+++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)+++def _int8_checkpoint(+ paths: tuple[str, ...] = INT8_LAYERS, *, convrot: bool = True+) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ """A full state dict for the tiny geometry with `paths` stored int8_tensorwise (+convrot).++ `convrot=False` is for the layers a repack quantizes that the released build does not: the+ rotation works in groups of 256 along the input dim, and `input_proj` is 8 wide. It is still a+ valid `int8_tensorwise` marker -- what makes the layer interesting is the int8 storage.+ """+ torch.manual_seed(0)+ reference = Ideogram4Transformer(INT8_CONFIG)+ state_dict = {key: value.clone().to(torch.float32) for key, value in reference.state_dict().items()}++ originals: dict[str, torch.Tensor] = {}+ for path in paths:+ key = f"{path}.weight"+ originals[key] = state_dict[key].clone()+ if convrot:+ state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_convrot(state_dict[key])+ else:+ state_dict[key], state_dict[f"{path}.weight_scale"] = _quantize_tensorwise(state_dict[key])+ state_dict[f"{path}.comfy_quant"] = _marker_blob({**MARKER, "convrot": convrot})++ return state_dict, originals+++def _reservation_for(+ before_load: dict[str, torch.Tensor], staying_int8: tuple[str, ...], dtype: torch.dtype = torch.float32+) -> int:+ """What the load occupies, with the four widths spelled out rather than recomputed.++ Takes the state dict as it was *before* the load, which pops the markers and rebinds the dict.++ A payload that stays int8 is one byte and its scale stays at the fp32 it is pinned at. A marker+ is dropped, and so is the scale of a marked layer the split widens -- that one is folded into+ its weight, which arrives at the compute width like every dense tensor. Charging a kept int8+ payload two bytes asks the cache to evict roughly twice what the load needs; charging a widened+ one a single byte leaves the reservation short by exactly the layers the split grew.+ """+ marked = {key[: -len(".comfy_quant")] for key in before_load if key.endswith(".comfy_quant")}+ widened = marked - set(staying_int8)+ pinned = {f"{path}.{suffix}" for path in staying_int8 for suffix in ("weight", "weight_scale")}+ dropped = {f"{path}.comfy_quant" for path in marked} | {f"{path}.weight_scale" for path in widened}+ total = 0+ for key, tensor in before_load.items():+ if key in dropped:+ continue+ total += tensor.nelement() * (tensor.element_size() if key in pinned else dtype.itemsize)+ return total+++def test_an_int8_checkpoint_stays_int8_resident_and_un_rotates(monkeypatch, tmp_path) -> None:+ """The end state, not the decision.++ `Int8ConvrotLinear` holds the stored codes and dequantizes per forward, which is the entire+ point: the file's size is the resident size. The weight it reconstructs must also be the+ *un-rotated* one — a checkpoint taken down the fp8 path instead would be scaled but never+ derotated, which loads cleanly and generates noise.+ """+ state_dict, originals = _int8_checkpoint()+ biases = {key: value.clone() for key, value in state_dict.items() if key.endswith(".bias")}+ trace: dict = {}++ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)++ for path in INT8_LAYERS:+ layer = model.get_submodule(path)+ assert isinstance(layer, Int8ConvrotLinear), path+ assert layer.weight.dtype is torch.int8+ assert layer.convrot is True+ # int8 keeps ~2 decimal digits per weight, 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[f"{path}.weight"]+ assert torch.allclose(reconstructed, original, rtol=0.05, atol=0.05 * original.abs().max())++ # `adaln_modulation` is the one quantized layer with a bias, and the swapped module carries it+ # as a buffer rather than a parameter -- so the strict load below cannot see it go missing.+ assert torch.equal(model.get_submodule("layers.0.adaln_modulation").bias, biases["layers.0.adaln_modulation.bias"])+ # The fp8 storage pass must not run over int8 codes either.+ assert trace["casting_calls"] == 0+++def test_an_unusable_activation_scale_does_not_break_the_strict_load(monkeypatch, tmp_path) -> None:+ """W8A8 sidecars are metadata for a mode this path does not implement.++ The load is strict, so a repack that ships `.input_scale` next to its int8 weights would fail+ on an unexpected key -- rejecting a file that is otherwise perfectly loadable.+ """+ state_dict, _ = _int8_checkpoint()+ state_dict[f"{INT8_LAYERS[0]}.input_scale"] = torch.ones((), dtype=torch.float32)++ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)++ assert isinstance(model.get_submodule(INT8_LAYERS[0]), Int8ConvrotLinear)++[email protected]("path", SKIPPED)+def test_a_repack_that_quantizes_a_dtype_deriving_layer_is_dequantized(monkeypatch, tmp_path, path: str) -> None:+ """The int8 half of the skip patterns, which the released build never exercises.++ `Ideogram4Transformer.forward` and `Ideogram4EmbedScalar.forward` read `input_proj` and+ `t_embedding`'s weight dtype and cast x, t and the conditioning to it. An `Int8ConvrotLinear`+ there reports `torch.int8`, which is not a dtype torch computes in -- so the layer has to come+ back dense even though its marker says otherwise.+ """+ state_dict, originals = _int8_checkpoint((path,), convrot=False)+ for key, value in _int8_checkpoint((INT8_LAYERS[0],))[0].items():+ if key.startswith(f"{INT8_LAYERS[0]}."):+ state_dict[key] = value+ before_load = {key: value.clone() for key, value in state_dict.items()}+ trace: dict = {}++ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)++ skipped = model.get_submodule(path)+ assert not isinstance(skipped, Int8ConvrotLinear)+ assert skipped.weight.dtype is torch.float32+ original = originals[f"{path}.weight"]+ assert torch.allclose(skipped.weight, original, rtol=0.05, atol=0.05 * original.abs().max())+ # The block linear it was mixed with still keeps its codes.+ assert isinstance(model.get_submodule(INT8_LAYERS[0]), Int8ConvrotLinear)+ # And the widened layer was reserved for at its widened width: charging it one byte because a+ # marker claims it leaves the reservation short by exactly the layers the split grew.+ assert trace["reserved"] == _reservation_for(before_load, (INT8_LAYERS[0],))+++def test_the_int8_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 VRAM/RAM contract:+ # two bytes per int8 payload evicts roughly twice what an 8.9 GiB file needs.+ state_dict, _ = _int8_checkpoint()+ before_load = {key: value.clone() for key, value in state_dict.items()}+ trace: dict = {}++ _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace, geometry=INT8_CONFIG)++ assert trace["reserved"] == _reservation_for(before_load, INT8_LAYERS)+++def test_a_missing_bias_on_a_quantized_layer_is_refused(monkeypatch, tmp_path) -> None:+ """The one hole the strict load cannot cover.++ `Int8ConvrotLinear` registers `bias` only when the checkpoint has one, so after the swap the+ module's key set mirrors the file instead of the architecture. A repack that drops all-zero+ biases would leave every block's adaLN modulation without its offset -- wrong `scale_msa`,+ `gate_msa`, `scale_mlp`, `gate_mlp` -- and load, cache and render with nothing in the log.+ """+ state_dict, _ = _int8_checkpoint()+ del state_dict["layers.0.adaln_modulation.bias"]++ with pytest.raises(ValueError, match="layers.0.adaln_modulation"):+ _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)+++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 for the ride would be cast to the compute dtype without its scale+ -- off by `1/weight_scale` -- while `strict=False` swallows the orphaned scale. There is no+ setting under which this file is loadable, so it is refused rather than half-loaded.+ """+ state_dict, _ = _int8_checkpoint()+ state_dict["final_layer.linear.weight"], state_dict["final_layer.linear.weight_scale"] = _quantize_scaled_fp8(+ state_dict["final_layer.linear.weight"]+ )++ with pytest.raises(ValueError, match="mixing int8_tensorwise with scaled fp8"):+ _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, geometry=INT8_CONFIG)diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.pyindex 09f0fa8769..ba7258d4be 100644--- a/tests/backend/quantization/test_int8_convrot_state_dict.py+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py@@ -10,6 +10,7 @@ import jsonimport pytestimport torch+from safetensors.torch import save_filefrom invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,@@ -18,6 +19,8 @@ from invokeai.backend.quantization.int8_convrot import (drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,predict_int8_cast_size,+ read_comfy_quant_markers,+ reject_foreign_quantization_scales,reject_unmarked_int8_weights,split_int8_convrot_layers,swap_in_int8_linears,@@ -330,3 +333,70 @@ class TestTheKeysTheOrphanCheckAndTheSidecarDropActOn:}assert set(drop_unconsumed_quantization_sidecars(sd)) == {"blocks.0.input_scaler.weight"}+++class TestTheForeignScaleCheck:+ """`reject_foreign_quantization_scales` decides which unclaimed `weight_scale` is fatal.++ Inside the int8 branch the fp8 pipeline is skipped, so a scaled-fp8 layer that came along would+ be cast without its scale -- off by `1/weight_scale`, silently. Both filters below exist because+ the failure is fatal and a false positive costs a user a checkpoint that worked.+ """++ @staticmethod+ def _model() -> torch.nn.Module:+ model = torch.nn.Module()+ model.proj = torch.nn.Linear(4, 4)+ model.other = torch.nn.Linear(4, 4)+ return model++ def test_an_fp8_weight_this_model_consumes_is_fatal(self) -> None:+ sd = {+ "proj.weight": torch.zeros(4, 4, dtype=torch.int8),+ "proj.weight_scale": torch.ones(4, 1),+ "other.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn),+ "other.weight_scale": torch.ones(()),+ }++ with pytest.raises(ValueError, match=r"other\.weight_scale"):+ reject_foreign_quantization_scales(sd, {"proj": MARKER}, "Ideogram 4", self._model())++ def test_a_scale_on_a_dense_weight_is_not(self) -> None:+ """A merged single file carries a bundled encoder too, and these loaders do not prefix-filter+ it out. The weight's dtype is what tells a foreign *quantized* layer from a foreign dense+ one; a dense weight loads correctly whatever sits beside it."""+ sd = {"other.weight": torch.zeros(4, 4), "other.weight_scale": torch.ones(())}++ reject_foreign_quantization_scales(sd, {}, "Ideogram 4", self._model())++ def test_a_scale_on_a_module_this_model_does_not_have_is_not(self) -> None:+ """An all-in-one export bundles a scaled-fp8 *submodel* beside the int8 transformer. Those+ keys are discarded by the load rather than cast, so they cannot load unscaled."""+ sd = {+ "text_encoder.fc.weight": torch.zeros(4, 4, dtype=torch.float8_e4m3fn),+ "text_encoder.fc.weight_scale": torch.ones(()),+ }++ reject_foreign_quantization_scales(sd, {}, "Ideogram 4", self._model())+++def test_read_comfy_quant_markers_reads_a_marker_off_a_file(tmp_path) -> None:+ """The scheme, from the file rather than from a state dict.++ Two callers need it that way: a loader deciding whether to commit to a ~20 GiB read, and model+ identification, whose state dict is on the meta device and therefore has no bytes to parse.+ Unrelated tensors are not reported, and a weight without a marker contributes nothing.+ """+ marker_json = b'{"format": "fp8_scaled", "convrot": false}'+ path = tmp_path / "tiny.safetensors"+ save_file(+ {+ "blocks.0.mlp.fc2.weight": torch.zeros(2, 2),+ "blocks.0.mlp.fc2.comfy_quant": torch.frombuffer(marker_json, dtype=torch.uint8).clone(),+ "unrelated.weight": torch.zeros(1),+ },+ str(path),+ )++ markers = read_comfy_quant_markers(path)+ assert markers == {"blocks.0.mlp.fc2": {"format": "fp8_scaled", "convrot": False}}