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
Merge branch 'main' into feat/int8-convrot-shared
Alexander Eichhorn6f03097b1871
diff --cc invokeai/backend/model_manager/load/model_loaders/krea2.pyindex fc4172f76a,fb78ef2c27..0c619923da--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@@ -25,21 -29,26 +29,33 @@@ from invokeai.backend.model_manager.taxSubModelType,)from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config+ from invokeai.backend.quantization.fp8_scaled import (+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ detach_layer_sidechannel,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ full_precision_hints_respected,+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ read_safetensors_metadata,+ reattach_layer_sidechannel,+ should_keep_fp8_weights,+ split_fp8_scaled_layers,+ strip_layer_path_prefix,+ warn_on_unattached_scales,+ )from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import (+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ resolve_quantized_module_paths,+ swap_in_int8_linears,+)from invokeai.backend.util.devices import TorchDevice- if TYPE_CHECKING:- # torch is imported lazily inside the helpers below; this is annotations-only.- import torch--# Kept as a module-level alias: this helper moved to model_manager.util.qwen3_vl so the MiniMax H3# loader can share it without importing across family loaders._normalize_qwen3vl_rope_config = normalize_qwen3vl_rope_config@@@ -116,46 -115,22 +122,41 @@@ def _remap_native_layer_paths(layer_nam"""import torch- scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(".weight_scale")]- if not scale_keys:- return sd- out = dict(sd)- for scale_key in scale_keys:- weight_key = scale_key.replace(".weight_scale", ".weight")- if weight_key in out and not out[weight_key].is_floating_point():- # An int8_tensorwise layer. Scaling it here without un-rotating it produces a state dict- # that loads cleanly and generates noise, which is the failure the marker path exists to- # prevent -- so leave both the weight and its scale for that path to consume.+ mapping: dict[str, str] = {}+ for name in layer_names:+ if not isinstance(name, str):continue- if weight_key in out:- weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()- scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()- out[weight_key] = (weight * scale).to(dtype)- del weight- del out[scale_key]- return out+ try:+ converted = _convert_krea2_native_to_diffusers({f"{name}.weight": torch.empty(0)})+ except Exception:+ continue+ for key in converted:+ if isinstance(key, str) and key.endswith(".weight"):+ mapping[name] = key[: -len(".weight")]+ break+ return mapping-def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:+# The original final-block up/down projections have no counterpart in the diffusers+# ``Krea2FinalLayer`` (a clean AdaLN + linear). Named once because two steps act on them: the+# converter drops them, and the single-file loader drops them *before* dequantizing so it never+# spends work - or trips over an exotic scale layout - on tensors that are about to be discarded.+DISCARDED_NATIVE_FINAL_KEYS = ("last.down", "last.up")+++def _drop_discarded_native_final_layers(sd: dict[str, Any]) -> dict[str, Any]:+ """Remove the dropped final-block projections together with their quantization metadata."""+ doomed = {+ f"{path}{suffix}"+ for path in DISCARDED_NATIVE_FINAL_KEYS+ for suffix in (".weight", ".weight_scale", ".comfy_quant")+ }+ if not doomed & set(sd):+ return sd+ return {k: v for k, v in sd.items() if k not in doomed}+++def _convert_krea2_native_to_diffusers(sd: dict[str, Any], *, key_map: dict[str, str] | None = None) -> dict[str, Any]:"""Convert a native/ComfyUI-format Krea-2 state dict (e.g. GGUF) to diffusers Krea2Transformer2DModel keys.Top-level module renames::@@@ -387,38 -353,84 +388,117 @@@ class Krea2CheckpointModel(ModelLoader)model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = load_file(model_path)+ metadata = read_safetensors_metadata(model_path, self._logger)sd = _strip_comfyui_prefix(sd)- # Per-layer `.comfy_quant` markers are read first (they are popped out of `sd` here, before- # the key conversion). Checkpoints ship the flags in either the header or these markers;- # without both, a checkpoint using only the per-tensor form has its- # full_precision_matrix_mult layers silently multiplied in fp8. The header wins on the rare- # checkpoint carrying both. Header names carry the prefix that was just stripped off the- # state dict, so strip it from them too or they match nothing.- layer_hints = {- **extract_comfy_quant_hints(sd),- **strip_layer_path_prefix(parse_quantization_metadata(metadata)),- }- if _is_native_krea2_format(sd):- # Take the quantization side channel out before renaming. The converter renames- # ".weight"-suffixed keys by substring and five more by whole-key equality, so a sibling- # ".scale_weight", ".input_scale", or any scale on one of the equality-renamed keys- # (e.g. `last.linear.weight_scale`) would be left behind at its old path while the- # weight moves — and then silently dropped, leaving the weight unscaled.- detached = detach_layer_sidechannel(sd)- sd = _convert_krea2_native_to_diffusers(sd)- # The metadata and the detached scales still name layers natively; rename both the same- # way or the per-layer flags (notably full_precision_matrix_mult) match nothing.- path_map = _remap_native_layer_paths({*detached, *layer_hints})- orphaned = reattach_layer_sidechannel(sd, detached, path_map)- if orphaned:- # INFO, not DEBUG: a dropped scale leaves its weight off by 1/weight_scale with no- # other symptom, so the one line that mentions it must be visible by default.- self._logger.info(- f"Krea-2: dropped quantization side-channel for {len(orphaned)} module(s) with no "- f"diffusers counterpart (e.g. {orphaned[0]})."- )- layer_hints = {path_map.get(name, name): hints for name, hints in layer_hints.items()}-- # ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).- 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:- # Legacy behavior: fold the scales into the weights. Keeping them quantized without the- # fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)- fp8_layers = {}+ # Discard what the key conversion below would discard anyway, before anything is spent on+ # it. One repack quantizes `last.up` with a blockwise scale grid this decode does not+ # implement; refusing a tensor that is on its way to the bin would be an odd way to fail.+ sd = _drop_discarded_native_final_layers(sd)- # ComfyUI 'int8_tensorwise' checkpoints (Comfy-Org's *_int8_convrot.safetensors): dequantize- # and un-rotate the marked layers. This must run BEFORE the fp8 path, which keys off- # `.weight_scale` alone and would happily scale an int8 weight without ever un-rotating it --- # producing a state dict that loads cleanly and generates noise. It must also run BEFORE the- # key conversion below, which renames `.attn.wq.weight` by substring and so carries- # `.weight_scale` along but NOT `.comfy_quant`; decoding here keeps marker and weight paired.++++ # Two ComfyUI side-channel formats reach this loader and a checkpoint carries one or the++ # other, so the format is decided once here. `int8_tensorwise` has to be recognised before++ # the key conversion below: that conversion renames `.weight` by substring and so carries a++ # sibling `.weight_scale` along but NOT `.comfy_quant`, which would separate an int8 weight++ # from the marker that says it is rotated. Taken down the fp8 path instead, such a weight++ # would be scaled but never un-rotated -- a state dict that loads cleanly and generates++ # noise.+ int8_markers = extract_int8_convrot_markers(sd)- # ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights. The- # compute dtype is resolved first so the dequantized weights land there directly instead of- # transiently materializing the whole model in float32.- sd = _dequantize_scaled_fp8(sd, model_dtype)- sd = drop_unconsumed_quantization_sidecars(sd)- # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.- key_map: dict[str, str] = {}- if _is_native_krea2_format(sd):- sd = _convert_krea2_native_to_diffusers(sd, key_map=key_map)- quantized = resolve_quantized_module_paths(int8_markers, key_map)++++ if int8_markers:++ sd = drop_unconsumed_quantization_sidecars(sd)++ # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.++ key_map: dict[str, str] = {}++ if _is_native_krea2_format(sd):++ sd = _convert_krea2_native_to_diffusers(sd, key_map=key_map)++ quantized = resolve_quantized_module_paths(int8_markers, key_map)++ else:++ # Per-layer `.comfy_quant` markers are read first (they are popped out of `sd` here, before++ # the key conversion). Checkpoints ship the flags in either the header or these markers;++ # without both, a checkpoint using only the per-tensor form has its++ # full_precision_matrix_mult layers silently multiplied in fp8. The header wins on the rare++ # checkpoint carrying both. Header names carry the prefix that was just stripped off the++ # state dict, so strip it from them too or they match nothing.++ layer_hints = {++ **extract_comfy_quant_hints(sd),++ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),++ }++ if _is_native_krea2_format(sd):++ # Take the quantization side channel out before renaming. The converter renames++ # ".weight"-suffixed keys by substring and five more by whole-key equality, so a sibling++ # ".scale_weight", ".input_scale", or any scale on one of the equality-renamed keys++ # (e.g. `last.linear.weight_scale`) would be left behind at its old path while the++ # weight moves — and then silently dropped, leaving the weight unscaled.++ detached = detach_layer_sidechannel(sd)++ sd = _convert_krea2_native_to_diffusers(sd)++ # The metadata and the detached scales still name layers natively; rename both the same++ # way or the per-layer flags (notably full_precision_matrix_mult) match nothing.++ path_map = _remap_native_layer_paths({*detached, *layer_hints})++ orphaned = reattach_layer_sidechannel(sd, detached, path_map)++ if orphaned:++ # INFO, not DEBUG: a dropped scale leaves its weight off by 1/weight_scale with no++ # other symptom, so the one line that mentions it must be visible by default.++ self._logger.info(++ f"Krea-2: dropped quantization side-channel for {len(orphaned)} module(s) with no "++ f"diffusers counterpart (e.g. {orphaned[0]})."++ )++ layer_hints = {path_map.get(name, name): hints for name, hints in layer_hints.items()}++++ # ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).++ 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:++ # Legacy behavior: fold the scales into the weights. Keeping them quantized without the++ # fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.++ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)++ fp8_layers = {}with accelerate.init_empty_weights():model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)- # int8 payloads are one byte, not two: reserving the compute dtype's width for them would- # ask the cache to free ~12 GB that this load never uses.- new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())- self._ram_cache.make_room(new_sd_size)- cast_unquantized(sd, model_dtype, quantized)- swap_in_int8_linears(model, sd, quantized)- skip_patterns = _model_declared_skip_patterns(model)- # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are- # folded here, with their scale applied. Left to `cast_state_dict` they would be cast- # *without* it and `attach_fp8_scales` would then skip them for no longer being fp8 —- # a weight silently off by 1/weight_scale. Krea-2's `time_embed.linear_1/linear_2` are- # ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.- # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable- # subset through fp32, so reserving afterwards lets that transient peak land on an- # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers- # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would- # charge those 1 byte/element and arrive at 2.- self._ram_cache.make_room(- predict_cast_state_dict_size(++ if int8_markers:++ # int8 payloads are one byte, not two: reserving the compute dtype's width for them++ # would ask the cache to free ~12 GB that this load never uses.++ new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())++ self._ram_cache.make_room(new_sd_size)++ cast_unquantized(sd, model_dtype, quantized)++ swap_in_int8_linears(model, sd, quantized)++ # The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.++ fp8_layers = {}++ kept = 0++ else:++ skip_patterns = _model_declared_skip_patterns(model)++ # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are++ # folded here, with their scale applied. Left to `cast_state_dict` they would be cast++ # *without* it and `attach_fp8_scales` would then skip them for no longer being fp8 —++ # a weight silently off by 1/weight_scale. Krea-2's `time_embed.linear_1/linear_2` are++ # ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.++ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable++ # subset through fp32, so reserving afterwards lets that transient peak land on an++ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers++ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would++ # charge those 1 byte/element and arrive at 2.++ self._ram_cache.make_room(++ predict_cast_state_dict_size(++ sd,++ model_dtype,++ keep_fp8=keep_fp8,++ model=model,++ skip_patterns=skip_patterns,++ scaled_layers=fp8_layers,++ )++ )++++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)++ # A checkpoint with raw fp8 weights (fp8 tensors and no weight_scale) yields no fp8_layers at++ # all, but its weights are still usable on the tensor cores, so the same `keep_fp8` covers++ # both kinds.++ kept = cast_state_dict(+ 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)- # A checkpoint with raw fp8 weights (fp8 tensors and no weight_scale) yields no fp8_layers at- # all, but its weights are still usable on the tensor cores, so the same `keep_fp8` covers- # both kinds.- kept = cast_state_dict(- sd,- model_dtype,- keep_fp8=keep_fp8,- model=model,- skip_patterns=skip_patterns,- )model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")@@@ -536,7 -592,21 +660,25 @@@ def _qwen3vl_target_key(key: str) -> stComfyUI/native layout uses a single ``model.`` prefix for both towers; transformers splits them:``model.visual.*`` -> ``visual.*`` and ``model.<rest>`` (layers/embed_tokens/norm) -> ``language_model.<rest>``.++ Shared by the state-dict remap and the fp8 layer-hint remap so the two cannot drift apart: a hint+ keyed by a path the model does not have matches nothing and is silently ignored.+ """+ # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.+ key = key[len("model.") :] if key.startswith("model.") else key+ if key.startswith("visual.") or key.startswith("language_model."):+ # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").+ return key+ # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.+ return "language_model." + key++-def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:- """Remap ComfyUI single-file Qwen3-VL keys to the transformers ``Qwen3VLModel`` layout."""++def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any], *, key_map: dict[str, str] | None = None) -> dict[str, Any]:++ """Remap ComfyUI single-file Qwen3-VL keys to the transformers ``Qwen3VLModel`` layout.++++ `key_map` records old key -> new key when given, which `resolve_quantized_module_paths` needs to++ carry `comfy_quant` markers onto the module paths the model actually has.+ """out: dict[str, Any] = {}source_of: dict[Any, Any] = {}what = "Qwen3-VL encoder checkpoint"@@@ -544,17 -614,7 +686,10 @@@if not isinstance(k, str):_put_unique_key(out, k, v, source=k, source_of=source_of, what=what)continue- # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.- key = k[len("model.") :] if k.startswith("model.") else k- if key.startswith("visual.") or key.startswith("language_model."):- # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").- new_key = key- else:- # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.- new_key = "language_model." + key- _put_unique_key(out, _qwen3vl_target_key(k), v, source=k, source_of=source_of, what=what)++ new_key = _qwen3vl_target_key(k)+ _put_unique_key(out, new_key, v, source=k, source_of=source_of, what=what)+ if key_map is not None:+ key_map[k] = new_keyreturn out@@@ -638,35 -698,69 +773,95 @@@ class Qwen3VLEncoderCheckpointLoader(Momodel_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)sd = load_file(str(model_path))- # ComfyUI 'int8_tensorwise' encoders, decoded first for the same two reasons as the- # transformer above -- and for a third one here: an int8 layer's `.weight_scale` would- # otherwise make the fp8 detection below answer yes, and the encoder would be kept- # "fp8-resident" over weights that were never fp8.- metadata = read_safetensors_metadata(model_path, self._logger)- # Per-layer markers must be read before extract_fp8_scaled_layers() drops them, and before- # the key remap, which would not carry a ".comfy_quant" suffix to a sensible destination.- layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}-- # Remap BEFORE pulling the scales out. The remap rewrites whole keys, so each- # ".weight_scale" travels with its ".weight" and the recovered layer paths already match the- # model's module paths — which is what attach_fp8_scales() resolves them against.- sd = _remap_qwen3vl_singlefile_keys(sd)- layer_hints = {_qwen3vl_target_key(path): hints for path, hints in layer_hints.items()}-- # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale). Only the language-model linears are- # quantized in the checkpoints seen so far; the visual tower stays bf16 either way.- fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)- source_is_fp8 = bool(fp8_layers) or any(- getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()- )- # Resolved once. `device_supports_fp8_matmul` deliberately does not cache an inconclusive- # probe, so two calls can disagree: a transient failure here followed by a success below- # would leave the scales already folded while the raw Linears stay quantized, i.e. the- # encoder silently on the storage path with the matmul log line never printed.- keep_matmul_fp8 = should_keep_fp8_weights(target_device)- if fp8_layers and not keep_matmul_fp8:- # Legacy behavior: fold the scales into the weights. Without the fp8 matmul, staying- # quantized would save VRAM but cost speed, so the two are tied to the same setting.- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)++ # Same one-or-the-other split as the transformer above, and here it also guards the fp8++ # *detection*: an int8 layer ships a `.weight_scale` too, so probing for scales without++ # ruling out int8 first would keep the encoder "fp8-resident" over weights that were never++ # fp8.+ int8_markers = extract_int8_convrot_markers(sd)- # Detect an fp8 source (ComfyUI 'scaled fp8' weight_scale keys, or raw float8 weights) BEFORE- # dequantizing. An fp8-on-disk encoder is kept fp8-resident with layerwise upcasting below, so- # it occupies ~half the VRAM of the dequantized bf16 model (the whole point of shipping fp8).- # An int8 layer's scale is not evidence of fp8, so those are excluded -- otherwise an int8- # encoder would be kept "fp8-resident" over weights that were never fp8.- source_is_fp8 = any(- isinstance(k, str) and k.endswith(".weight_scale") and k[: -len(".weight_scale")] not in int8_markers- for k in sd- ) or any(getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values())- # ComfyUI 'scaled fp8': fold weight_scale into the weights, then drop quantization metadata.- sd = _dequantize_scaled_fp8(sd, model_dtype)- sd = drop_unconsumed_quantization_sidecars(sd)- key_map: dict[str, str] = {}- sd = _remap_qwen3vl_singlefile_keys(sd, key_map=key_map)- quantized = resolve_quantized_module_paths(int8_markers, key_map)++++ if int8_markers:++ sd = drop_unconsumed_quantization_sidecars(sd)++ key_map: dict[str, str] = {}++ sd = _remap_qwen3vl_singlefile_keys(sd, key_map=key_map)++ quantized = resolve_quantized_module_paths(int8_markers, key_map)++ source_is_fp8 = False+ fp8_layers = {}++ keep_matmul_fp8 = False++ # An int8 encoder is dense bf16 after `cast_unquantized`, so neither fp8 consumer below++ # applies: nothing is fp8-resident to keep, and re-quantizing to fp8 storage would undo++ # the un-rotation this path just did.++ use_fp8_storage = False++ else:++ metadata = read_safetensors_metadata(model_path, self._logger)++ # Per-layer markers must be read before extract_fp8_scaled_layers() drops them, and before++ # the key remap, which would not carry a ".comfy_quant" suffix to a sensible destination.++ layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}++++ # Remap BEFORE pulling the scales out. The remap rewrites whole keys, so each++ # ".weight_scale" travels with its ".weight" and the recovered layer paths already match the++ # model's module paths — which is what attach_fp8_scales() resolves them against.++ sd = _remap_qwen3vl_singlefile_keys(sd)++ layer_hints = {_qwen3vl_target_key(path): hints for path, hints in layer_hints.items()}++++ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale). Only the language-model linears are++ # quantized in the checkpoints seen so far; the visual tower stays bf16 either way.++ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++ source_is_fp8 = bool(fp8_layers) or any(++ getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()++ )++ # Resolved once. `device_supports_fp8_matmul` deliberately does not cache an inconclusive++ # probe, so two calls can disagree: a transient failure here followed by a success below++ # would leave the scales already folded while the raw Linears stay quantized, i.e. the++ # encoder silently on the storage path with the matmul log line never printed.++ keep_matmul_fp8 = should_keep_fp8_weights(target_device)++ if fp8_layers and not keep_matmul_fp8:++ # Legacy behavior: fold the scales into the weights. Without the fp8 matmul, staying++ # quantized would save VRAM but cost speed, so the two are tied to the same setting.++ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)++ fp8_layers = {}te_config = self._load_hf_config()with accelerate.init_empty_weights():model = Qwen3VLModel._from_config(te_config)- new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())- self._ram_cache.make_room(new_sd_size)- cast_unquantized(sd, model_dtype, quantized)- swap_in_int8_linears(model, sd, quantized)- # Same ordering contract as every other loader in this series: split *before* the cast.- # A per-key `if dtype is not FP8_DTYPE` cast looks equivalent and is not — it keeps every- # fp8 tensor quantized, including the ones that must not stay:- #- # - a 1-D fp8 norm (checkpoints that "quantize everything" ship these) would keep its- # scale as an unused buffer on a non-Linear and the forward would compute on the raw- # fp8 codes, i.e. off by 1/weight_scale with nothing logged;- # - an e5m2 scaled weight would be cast *without* its scale, since only e4m3fn is spared;- # - a block-wise scale would reach `scaled_mm_linear` unchecked and raise mid-generation.- #- # `split_fp8_scaled_layers` applies exactly those filters and dequantizes the affected- # layers *with* their scale, so what remains is what the matmul can actually consume.- # The storage path below re-quantizes to fp8 anyway, so casting the raw fp8 Linears to- # `model_dtype` here would double both this reservation and the host-RAM peak (~4.4 -> ~8.9- # GiB on the 4B encoder) for a round trip that ends where it started -- e4m3fn is a subset- # of bf16, so it is value-exact. Keep them for either consumer.- use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)- keep_fp8 = keep_matmul_fp8 or use_fp8_storage- # Reserve before the split: it dequantizes its unusable subset through fp32, so reserving- # afterwards lets that transient peak land on an unreserved cache. `scaled_layers` keeps the- # prediction in step with the split's own scale-layout filter.- self._ram_cache.make_room(- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)- )- fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)- # No `skip_patterns` here on purpose: this model declares none, and the storage pass below- # applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect- # on a 2-D Linear -- such a weight would arrive fp8 from the state dict, be skipped by the- # cast pass, and forward on raw fp8 codes. `_apply_fp8_to_nn_module` now restores the compute- # dtype on the modules it skips, so the two lists are independent again.- cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)++ if int8_markers:++ # int8 payloads are one byte, not two.++ new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())++ self._ram_cache.make_room(new_sd_size)++ cast_unquantized(sd, model_dtype, quantized)++ swap_in_int8_linears(model, sd, quantized)++ else:++ # Same ordering contract as every other loader in this series: split *before* the cast.++ # A per-key `if dtype is not FP8_DTYPE` cast looks equivalent and is not — it keeps every++ # fp8 tensor quantized, including the ones that must not stay:++ #++ # - a 1-D fp8 norm (checkpoints that "quantize everything" ship these) would keep its++ # scale as an unused buffer on a non-Linear and the forward would compute on the raw++ # fp8 codes, i.e. off by 1/weight_scale with nothing logged;++ # - an e5m2 scaled weight would be cast *without* its scale, since only e4m3fn is spared;++ # - a block-wise scale would reach `scaled_mm_linear` unchecked and raise mid-generation.++ #++ # `split_fp8_scaled_layers` applies exactly those filters and dequantizes the affected++ # layers *with* their scale, so what remains is what the matmul can actually consume.++ # The storage path below re-quantizes to fp8 anyway, so casting the raw fp8 Linears to++ # `model_dtype` here would double both this reservation and the host-RAM peak (~4.4 -> ~8.9++ # GiB on the 4B encoder) for a round trip that ends where it started -- e4m3fn is a subset++ # of bf16, so it is value-exact. Keep them for either consumer.++ use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)++ keep_fp8 = keep_matmul_fp8 or use_fp8_storage++ # Reserve before the split: it dequantizes its unusable subset through fp32, so reserving++ # afterwards lets that transient peak land on an unreserved cache. `scaled_layers` keeps the++ # prediction in step with the split's own scale-layout filter.++ self._ram_cache.make_room(++ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)++ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)++ # No `skip_patterns` here on purpose: this model declares none, and the storage pass below++ # applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect++ # on a 2-D Linear -- such a weight would arrive fp8 from the state dict, be skipped by the++ # cast pass, and forward on raw fp8 codes. `_apply_fp8_to_nn_module` now restores the compute++ # dtype on the modules it skips, so the two lists are independent again.++ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Qwen3-VL encoder checkpoint")diff --cc invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 70453f7fe8,a6e0255283..706f0abb98--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@@ -34,13 -38,27 +38,33 @@@ from invokeai.backend.model_manager.taxModelType,SubModelType,)+ from invokeai.backend.quantization.fp8_scaled import (+ QKV_SPLIT_SIDECHANNEL_SUFFIXES,+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ expand_weight_scale,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ full_precision_hints_respected,+ is_scale_metadata_key,+ iter_weight_scale_pairs,+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ read_safetensors_metadata,+ should_keep_fp8_weights,+ split_fp8_scaled_layers,+ split_qkv_sidechannel,+ strip_layer_path_prefix,+ warn_on_unattached_scales,+ )from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.int8_convrot import (+ cast_unquantized,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ swap_in_int8_linears,+)from invokeai.backend.quantization.sdnq.detection import is_sdnq_folderfrom invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loaderfrom invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer@@@ -125,12 -145,16 +151,19 @@@ def _convert_z_image_gguf_to_diffusers(prefix = key.rsplit(".attention.qkv.", 1)[0]suffix = key.rsplit(".attention.qkv.", 1)[1] # "weight" or "bias"- # Quantization side-channels have to follow their weight through the split, or they- # are left behind under a module name that no longer exists -- and a loader then sees- # a quantized weight with no scale, or a scale it cannot pair with anything.if suffix not in ("weight", "bias"):- for target in ("to_q", "to_k", "to_v"):- new_sd[f"{prefix}.attention.{target}.{suffix}"] = _split_qkv_sidechannel(value, suffix, target)+ # Quantization side-channel for the fused weight. It has to travel with the split,+ # or the recovered scale is keyed on `...attention.qkv`, a module path that no+ # longer exists — `attach_fp8_scales` then finds nothing and the three split- # weights stay quantized but *unscaled*, i.e. off by 1/weight_scale.++ # weights stay quantized but *unscaled*, i.e. off by 1/weight_scale. The same++ # applies to a `comfy_quant` marker, which is why that suffix is in the list too:++ # without it `extract_int8_convrot_markers` would find no marker for the split++ # weights and reject the checkpoint as having orphaned int8 tensors.+ if suffix in QKV_SPLIT_SIDECHANNEL_SUFFIXES:+ for name, part in zip(("to_q", "to_k", "to_v"), split_qkv_sidechannel(key, value), strict=True):+ new_sd[f"{prefix}.attention.{name}.{suffix}"] = part+ continue+ new_sd[key] = valuecontinue# Split the fused QKV tensor into Q, K, V@@@ -503,31 -534,52 +543,98 @@@ class ZImageCheckpointModel(ModelLoaderfor k in keys_to_remove:del sd[k]- # ComfyUI 'int8_tensorwise' checkpoints. The markers are read *after* the key conversion- # above, which carries them (and their scales) through the fused-QKV split onto the module- # names the model actually has -- so no re-keying is needed here.- # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight). Until now the loader- # deleted those scales and cast the weight — silently producing a weight off by- # 1/weight_scale — and had no way to tell such a checkpoint from a raw fp8 one.- layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}- fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)-- # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights- # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting them- # here would discard both the VRAM saving and the tensor cores before the model is built.- keep_fp8 = should_keep_fp8_weights(self._torch_device)- if fp8_layers and not keep_fp8:- # Legacy behavior, but now with the scale actually applied: fold it into the weight.- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)- fp8_layers = {}-- # Honor the model's own precision-sensitive list. Z-Image declares- # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to- # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the forward- # dies in `x.abs()`. Those layers must be dequantized even though the rest stays quantized.- skip_patterns = _model_declared_skip_patterns(model)- # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so- # `cast_state_dict` never strips a scale it cannot put back.- # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable- # subset through fp32, so reserving afterwards lets that transient peak land on an- # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers- # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would- # charge those 1 byte/element and arrive at 2.- self._ram_cache.make_room(- predict_cast_state_dict_size(++ # Two ComfyUI side-channel formats reach this loader, and a checkpoint carries one or the++ # other: `comfy_quant` names its format per layer, and `int8_tensorwise` never appears in a++ # file that also ships fp8 weight scales. Deciding once, up front, keeps the two casts from++ # having to understand each other -- `cast_unquantized` treats int8 payloads as opaque,++ # `cast_state_dict` reasons about fp8 matmul eligibility, and neither is correct for the++ # other's tensors.+ int8_markers = extract_int8_convrot_markers(sd)- # Filtered in place rather than rebound: the `sd.clear()` below has to reach the same dict- # the checkpoint was read into, or the originals stay alive through it and peak RAM- # overshoots the `make_room()` reservation (see test_state_dict_is_released_before_the_fp8_cast).- kept = drop_unconsumed_quantization_sidecars(sd)- sd.clear()- sd.update(kept)- del kept++++ # Outside the branch on purpose: an int8 weight whose marker is missing leaves `int8_markers`++ # empty, so a check living inside the int8 path would never see the very case it exists for.++ # Such a weight would take the fp8 path, be treated as an ordinary tensor and load into a++ # model that runs and generates noise.+ orphans = sorted(k for k, v in sd.items() if v.dtype is torch.int8 and k[: -len(".weight")] not in int8_markers)+ if orphans:+ raise ValueError(+ f"Z-Image checkpoint has {len(orphans)} int8 weight(s) with no `comfy_quant` marker, "+ f"e.g. {orphans[:3]}. Loading them would produce a model that runs and generates noise."+ )+- # int8 payloads are one byte, not two: reserving the compute dtype's width for them would- # ask the cache to free memory this load never uses.- new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())- self._ram_cache.make_room(new_sd_size)++ if int8_markers:++ # Markers are read *after* the key conversion above, which carries them (and their++ # scales) through the fused-QKV split onto the module names the model actually has --++ # so no re-keying is needed here.++ #++ # Filtered in place rather than rebound: the `sd.clear()` below has to reach the same++ # dict the checkpoint was read into, or the originals stay alive through it and peak++ # RAM overshoots the `make_room()` reservation (see++ # test_state_dict_is_released_before_the_fp8_cast).++ kept_sd = drop_unconsumed_quantization_sidecars(sd)++ sd.clear()++ sd.update(kept_sd)++ del kept_sd++++ # int8 payloads are one byte, not two: reserving the compute dtype's width for them++ # would ask the cache to free memory this load never uses.++ new_sd_size = sum(ten.nelement() * max(ten.element_size(), model_dtype.itemsize) for ten in sd.values())++ self._ram_cache.make_room(new_sd_size)++++ cast_unquantized(sd, model_dtype, int8_markers)++ swap_in_int8_linears(model, sd, int8_markers)++ # The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.++ fp8_layers: dict[str, Any] = {}++ kept = 0++ else:++ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight). Until now the loader++ # deleted those scales and cast the weight — silently producing a weight off by++ # 1/weight_scale — and had no way to tell such a checkpoint from a raw fp8 one.++ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}++ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++++ # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights++ # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting++ # them here would discard both the VRAM saving and the tensor cores before the model is++ # built.++ keep_fp8 = should_keep_fp8_weights(self._torch_device)++ if fp8_layers and not keep_fp8:++ # Legacy behavior, but now with the scale actually applied: fold it into the weight.++ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)++ fp8_layers = {}++++ # Honor the model's own precision-sensitive list. Z-Image declares++ # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to++ # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the++ # forward dies in `x.abs()`. Those layers must be dequantized even though the rest stays++ # quantized.++ skip_patterns = _model_declared_skip_patterns(model)++ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so++ # `cast_state_dict` never strips a scale it cannot put back.++ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable++ # subset through fp32, so reserving afterwards lets that transient peak land on an++ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens++ # layers whose scale layout `scaled_mm` cannot apply, and without the mapping the++ # prediction would charge those 1 byte/element and arrive at 2.++ self._ram_cache.make_room(++ predict_cast_state_dict_size(++ sd,++ model_dtype,++ keep_fp8=keep_fp8,++ model=model,++ skip_patterns=skip_patterns,++ scaled_layers=fp8_layers,++ )++ )+- cast_unquantized(sd, model_dtype, int8_markers)- swap_in_int8_linears(model, sd, int8_markers)++ 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,- 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,- )model.load_state_dict(sd, assign=True)# `assign=True` aliases every param to its `sd` tensor, so the dict keeps the whole modeldiff --cc tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex 2446039d2e,90eed6cbdb..fee0590d92--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@@ -62,73 -59,6 +64,80 @@@ def test_single_file_loader_constructs_ram_cache.make_room.assert_called_once()+def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_path) -> None:+ """The decode has to be *wired in*, not merely available.++ Every other test of this feature exercises the helpers directly, so deleting the call from+ `_load_from_singlefile` would leave them all green while the loader silently produced a+ scaled-but-still-rotated model. This one drives the loader itself and checks the weight that+ actually reaches the module.+ """+ import json++ import diffusers+ import safetensors.torch++ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard++ torch.manual_seed(0)+ original = torch.randn(4, CONVROT_GROUP_SIZE)+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE)+ rotated = (original.view(4, 1, CONVROT_GROUP_SIZE) @ hadamard.T).view(4, CONVROT_GROUP_SIZE)+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})+ # A marker is always `<layer>.comfy_quant`; a quantized weight is a submodule's, never the+ # model's own, so the fixture mirrors that.+ state_dict = {+ "proj.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),+ "proj.weight_scale": scale.to(torch.float32),+ "proj.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),+ }++ class _TinyInt8Krea2Transformer(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)++ checkpoint_path = tmp_path / "krea2_int8_convrot.safetensors"+ checkpoint_path.touch()+ config = Main_Checkpoint_Krea2_Config.model_construct(+ path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None+ )+ loader = object.__new__(Krea2CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())++ loader._logger = MagicMock()+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model++ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)+ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )++ model = loader._load_from_singlefile(config)+++ # This is also what pins the one-or-the-other split in the loader: the fixture's int8 weight++ # carries a `.weight_scale`, which is exactly what an fp8 scaled layer looks like from outside.++ # Route it down the fp8 path and it is scaled but never un-rotated -- `load_state_dict` then++ # refuses the still-int8 tensor, and failing that the correlation below does. (Verified by++ # forcing the branch: the test fails.)++ #+ # The weight stays quantized: that is the whole point of the swap, and it is what keeps a+ # 12 GB checkpoint at 12 GB instead of the ~24 GB a dense decode would produce.+ assert isinstance(model.proj, Int8ConvrotLinear)+ assert model.proj.weight.dtype is torch.int8++ # And it still computes the un-rotated weight, which the fp8 path alone would never produce.+ dequantized = model.proj._dequantized_weight(torch.device("cpu"), torch.float32).flatten()+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999+ assert torch.corrcoef(torch.stack([dequantized, rotated.flatten()]))[0, 1].abs() < 0.2++def test_diffusers_loader_reaches_transformer_from_pretrained(monkeypatch, tmp_path) -> None:config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)loader = object.__new__(Krea2DiffusersModel)diff --cc tests/backend/model_manager/load/test_krea2_state_dict_utils.pyindex 31cc6ff7bc,d9058268bb..0b65b4430c--- a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py@@@ -17,8 -17,6 +17,7 @@@ import torcfrom invokeai.backend.model_manager.load.model_loaders.krea2 import (KREA2_TRANSFORMER_CONFIG,_convert_krea2_native_to_diffusers,- _dequantize_scaled_fp8,+ _drop_discarded_native_final_layers,_is_native_krea2_format,_normalize_qwen3vl_rope_config,_reject_incomplete_load,@@@ -25,13 -24,12 +25,19 @@@_remap_qwen3vl_singlefile_keys,_strip_comfyui_prefix,)+ from invokeai.backend.quantization.fp8_scaled import (+ FP8_DTYPE,+ detach_layer_sidechannel,+ extract_fp8_scaled_layers,+ reattach_layer_sidechannel,+ )+from invokeai.backend.quantization.int8_convrot import (+ CONVROT_GROUP_SIZE,+ build_regular_hadamard,+ drop_unconsumed_quantization_sidecars,+ extract_int8_convrot_markers,+ resolve_quantized_module_paths,+)class TestNormalizeQwen3vlRopeConfig:@@@ -386,151 -342,81 +350,208 @@@ class TestConvertedShapesMatchRealKrea2assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"+def _quantized_int8_layer(path: str, weight: torch.Tensor) -> dict:+ """A convrot-rotated int8 layer in the native key spelling, as Comfy-Org ships it."""+ import json++ out_f, in_f = weight.shape+ h = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)+ rotated = (weight.view(out_f, in_f // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ h.T).view(out_f, in_f)+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})+ return {+ f"{path}.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),+ f"{path}.weight_scale": scale.to(torch.float32),+ f"{path}.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),+ }+++class TestInt8LayersSurviveTheLoaderPipeline:+ """Two steps between the file and the model would quietly ruin an int8 layer.++ Neither fails loudly if it is broken - both produce a state dict that loads cleanly and+ generates noise - so each is pinned by a test that shows the damage.+ """+- def test_the_fp8_fold_leaves_an_int8_weight_and_its_scale_alone(self) -> None:- """The fp8 path keys off `.weight_scale` and never consults the marker. Folding the scale- into an int8 weight without un-rotating it is exactly the silent corruption the marker- exists to prevent, so it skips anything that is not floating point."""- torch.manual_seed(0)- sd = _quantized_int8_layer("blocks.0.mlp.down", torch.randn(64, 2 * CONVROT_GROUP_SIZE))- before = {k: v.clone() for k, v in sd.items()}-- out = _dequantize_scaled_fp8(sd, torch.float32)-- assert out["blocks.0.mlp.down.weight"].dtype is torch.int8- assert torch.equal(out["blocks.0.mlp.down.weight"], before["blocks.0.mlp.down.weight"])- assert "blocks.0.mlp.down.weight_scale" in out, "the scale the int8 layer still needs was consumed"-- def test_an_fp8_layer_is_still_folded(self) -> None:- sd = {- "blocks.0.attn.wq.weight": torch.ones(4, 4, dtype=torch.float8_e4m3fn),- "blocks.0.attn.wq.weight_scale": torch.tensor(2.0),- }- out = _dequantize_scaled_fp8(sd, torch.float32)- assert "blocks.0.attn.wq.weight_scale" not in out- assert torch.allclose(out["blocks.0.attn.wq.weight"], torch.full((4, 4), 2.0))-+ def test_the_key_conversion_renames_the_scale_but_orphans_the_marker(self) -> None:+ """Why the module paths are resolved by following the weight's own rename rather than the+ marker's key: the within-block renames are substring replacements of `.attn.wq.weight`,+ which `.weight_scale` contains and `.comfy_quant` does not."""+ torch.manual_seed(1)+ sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))++ converted = _convert_krea2_native_to_diffusers(sd)++ assert "transformer_blocks.0.attn.to_q.weight" in converted+ assert "transformer_blocks.0.attn.to_q.weight_scale" in converted+ assert "transformer_blocks.0.attn.wq.comfy_quant" in converted+ assert "transformer_blocks.0.attn.to_q.comfy_quant" not in converted++ def test_the_marker_is_re_keyed_onto_the_module_the_weight_landed_on(self) -> None:+ torch.manual_seed(2)+ sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))+ markers = extract_int8_convrot_markers(sd)++ key_map: dict[str, str] = {}+ _convert_krea2_native_to_diffusers(sd, key_map=key_map)++ assert resolve_quantized_module_paths(markers, key_map) == {+ "transformer_blocks.0.attn.to_q": markers["blocks.0.attn.wq"]+ }++ def test_a_diffusers_named_checkpoint_needs_no_re_keying(self) -> None:+ """No conversion runs, so the empty map has to resolve to the paths as they are."""+ markers = {"transformer_blocks.0.attn.to_q": {"format": "int8_tensorwise"}}+ assert resolve_quantized_module_paths(markers, {}) == markers+++class TestUnconsumedQuantizationSidecars:+ def test_markers_and_activation_scales_are_dropped(self) -> None:+ """`input_scale` is an activation scale for W8A8 inference; this code dequantizes the+ weight and computes in bf16, so there is nothing to apply it to. One Qwen3-VL repack+ ships 337 of them, under a spelling the previous filter did not match."""+ sd = {+ "layer.weight": torch.ones(2, 2),+ "layer.comfy_quant": torch.zeros(4, dtype=torch.uint8),+ "layer.input_scale": torch.ones(1),+ "other.scale_input": torch.ones(1),+ }+ assert set(drop_unconsumed_quantization_sidecars(sd)) == {"layer.weight"}++ def test_a_clean_state_dict_is_unchanged(self) -> None:+ sd = {"layer.weight": torch.ones(2, 2), "layer.bias": torch.zeros(2)}+ assert set(drop_unconsumed_quantization_sidecars(sd)) == set(sd)+++class TestDiscardedFinalProjections:+ def test_the_dropped_projections_take_their_quantization_metadata_with_them(self) -> None:+ """`last.down`/`last.up` have no diffusers counterpart, and one real repack quantizes+ `last.up` with a scale layout the decode refuses. Dropping them before the decode keeps a+ tensor that is on its way to the bin from failing the load."""+ sd = {+ "last.up.weight": torch.zeros(4, 4, dtype=torch.int8),+ "last.up.weight_scale": torch.ones(2, 2),+ "last.up.comfy_quant": torch.zeros(8, dtype=torch.uint8),+ "last.down.weight": torch.zeros(4, 4),+ "last.linear.weight": torch.ones(4, 4),+ }+ out = _drop_discarded_native_final_layers(sd)+ assert set(out) == {"last.linear.weight"}++ def test_a_state_dict_without_them_is_returned_unchanged(self) -> None:+ sd = {"last.linear.weight": torch.ones(2, 2)}+ assert _drop_discarded_native_final_layers(sd) is sd+++class TestEverySuffixSurvivesTheKeyConversion:+ """A quantized layer travels as three keys, and the converter has to move all of them.++ The within-block renames are substring replacements of `.attn.wq.weight`, so `.weight_scale`+ rides along by construction. The top-level renames are prefix slices, so they carry any+ suffix. `last.linear` used to be neither -- an exact match per suffix, which silently left+ `last.linear.weight_scale` under its old name.+ """++ @pytest.mark.parametrize(+ ("native", "diffusers"),+ [+ ("blocks.0.attn.wq", "transformer_blocks.0.attn.to_q"),+ ("blocks.3.mlp.down", "transformer_blocks.3.ff.down"),+ ("txtfusion.refiner_blocks.1.attn.wv", "text_fusion.refiner_blocks.1.attn.to_v"),+ ("first", "img_in"),+ ("tmlp.0", "time_embed.linear_1"),+ ("tmlp.2", "time_embed.linear_2"),+ ("tproj.1", "time_mod_proj"),+ ("txtmlp.1", "txt_in.linear_1"),+ ("txtmlp.3", "txt_in.linear_2"),+ ("last.linear", "final_layer.linear"),+ ],+ )+ def test_the_weight_and_its_scale_land_on_the_same_module(self, native: str, diffusers: str) -> None:+ sd = {f"{native}.weight": torch.zeros(4, 4, dtype=torch.int8), f"{native}.weight_scale": torch.ones(4, 1)}+ key_map: dict[str, str] = {}+ out = _convert_krea2_native_to_diffusers(sd, key_map=key_map)++ assert f"{diffusers}.weight" in out+ assert f"{diffusers}.weight_scale" in out, "the scale was left behind under its old name"+ assert key_map[f"{native}.weight"] == f"{diffusers}.weight"+++++ class TestNativeConversionCarriesTheQuantizationSideChannel:+ """Regression guard for scales orphaned by the native -> diffusers rename.++ `_convert_krea2_native_to_diffusers` renames `.weight` keys by substring *and* renames five+ more by whole-key equality. Neither carries a sibling scale: `.scale_weight` and `.input_scale`+ do not contain `.weight`, and `last.linear.weight_scale` is not equal to `last.linear.weight`.+ An orphaned scale is then dropped by `extract_fp8_scaled_layers` (no fp8 weight sits at the old+ path any more) and the weight is left quantized but unscaled - off by exactly 1/weight_scale,+ with nothing logged, because the layer never enters `fp8_layers` for+ `warn_on_unattached_scales` to see.+ """++ @staticmethod+ def _convert(sd: dict) -> dict:+ detached = detach_layer_sidechannel(sd)+ converted = _convert_krea2_native_to_diffusers(sd)+ orphaned = reattach_layer_sidechannel(converted, detached, _remap_native_layer_paths(set(detached)))+ return converted, orphaned++ def test_every_spelling_and_rename_style_survives(self) -> None:+ fp8 = torch.ones(4, 4).to(FP8_DTYPE)+ sd = {+ # substring rename, `.weight_scale` spelling+ "blocks.0.attn.wq.weight": fp8.clone(),+ "blocks.0.attn.wq.weight_scale": torch.tensor(0.5),+ "blocks.0.attn.wq.input_scale": torch.tensor(0.25),+ # substring rename, `.scale_weight` spelling+ "blocks.0.attn.wk.weight": fp8.clone(),+ "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),+ # whole-key-equality rename+ "last.linear.weight": fp8.clone(),+ "last.linear.weight_scale": torch.tensor(0.5),+ }++ converted, orphaned = self._convert(sd)+ layers = extract_fp8_scaled_layers(converted)++ assert set(layers) == {+ "transformer_blocks.0.attn.to_q",+ "transformer_blocks.0.attn.to_k",+ "final_layer.linear",+ }+ assert orphaned == []+ # The calibrated activation scale must come across too, or every forward pays an amax pass.+ assert layers["transformer_blocks.0.attn.to_q"].input_scale is not None++ def test_no_fp8_weight_is_left_without_its_scale(self) -> None:+ """The property that actually matters, stated directly."""+ fp8 = torch.ones(4, 4).to(FP8_DTYPE)+ sd = {+ "blocks.0.attn.wk.weight": fp8.clone(),+ "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),+ "last.linear.weight": fp8.clone(),+ "last.linear.weight_scale": torch.tensor(0.5),+ }++ converted, _ = self._convert(sd)+ layers = extract_fp8_scaled_layers(converted)++ unscaled = [+ key+ for key, value in converted.items()+ if key.endswith(".weight")+ and getattr(value, "dtype", None) is FP8_DTYPE+ and key[: -len(".weight")] not in layers+ ]+ assert unscaled == []++ def test_a_scale_on_a_dropped_module_is_reported(self) -> None:+ """`last.down`/`last.up` have no diffusers counterpart, so their scales go too - loudly."""+ sd = {+ "last.down.weight": torch.ones(4, 4).to(FP8_DTYPE),+ "last.down.weight_scale": torch.tensor(0.5),+ }++ _, orphaned = self._convert(sd)++ assert orphaned == ["last.down"]diff --cc tests/backend/model_manager/load/test_z_image_state_dict_utils.pyindex 242ba397b9,42b43c70ce..3b3f00daa6--- a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py+++ b/tests/backend/model_manager/load/test_z_image_state_dict_utils.py@@@ -7,9 -5,8 +7,9 @@@ import torcfrom invokeai.backend.model_manager.load.model_loaders.z_image import (_convert_z_image_gguf_to_diffusers,- _split_qkv_sidechannel,+ _remap_z_image_layer_paths,)+from invokeai.backend.quantization.int8_convrot import extract_int8_convrot_markersfrom tests.backend.model_manager.load.state_dicts.utils import keys_to_mock_state_dictfrom tests.backend.model_manager.load.state_dicts.z_image_transformer_comfyui_keys import (state_dict_keys as z_image_keys,@@@ -73,70 -70,81 +73,102 @@@ class TestConvertZImageGgufToDiffusersassert torch.allclose(out["blk.attention.to_v.weight"], qkv[4:6])+def _marker_blob(marker: dict) -> torch.Tensor:+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)+++MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}++- class TestTheFusedQkvSplitCarriesQuantizationMetadata:- """A quantized fused QKV travels as three keys, and all three have to reach the same three- modules. The weight already split; the scale and the marker did not, and were left behind- under a module name the model does not have."""-- def test_a_per_output_channel_scale_splits_with_its_weight(self) -> None:- scale = torch.arange(3 * 4, dtype=torch.float32).reshape(3 * 4, 1)- pieces = [_split_qkv_sidechannel(scale, "weight_scale", t) for t in ("to_q", "to_k", "to_v")]- assert [tuple(p.shape) for p in pieces] == [(4, 1)] * 3- assert torch.equal(torch.cat(pieces), scale)-- def test_a_marker_is_copied_whole_to_all_three(self) -> None:- """The regression that motivated the suffix check: a 72-byte JSON blob is divisible by- three, so a rule based on the tensor's shape cuts it into three fragments of broken JSON."""- blob = _marker_blob(MARKER)- assert len(blob) % 3 == 0, "the fixture has to reproduce the divisible-by-three trap"- for target in ("to_q", "to_k", "to_v"):- piece = _split_qkv_sidechannel(blob, "comfy_quant", target)- assert torch.equal(piece, blob)- assert json.loads(bytes(piece.numpy().tobytes()).decode()) == MARKER-- def test_a_per_tensor_scale_is_copied_rather_than_split(self) -> None:- for scale in (torch.tensor(0.5), torch.tensor([0.5])):- assert torch.equal(_split_qkv_sidechannel(scale, "weight_scale", "to_k"), scale)-- def test_weight_scale_and_marker_land_on_the_same_three_modules(self) -> None:- prefix = "layers.0.attention"- sd = {- f"{prefix}.qkv.weight": torch.arange(3 * 4 * 8, dtype=torch.int8).reshape(3 * 4, 8),- f"{prefix}.qkv.weight_scale": torch.arange(3 * 4, dtype=torch.float32).reshape(3 * 4, 1),- f"{prefix}.qkv.comfy_quant": _marker_blob(MARKER),- # `x_embedder.` is what makes the loader run this conversion at all.- "x_embedder.weight": torch.zeros(2, 2),- }- out = _convert_z_image_gguf_to_diffusers(sd)+ class TestQkvQuantizationSideChannel:+ """A scaled-fp8 checkpoint puts a `scale_weight` next to the fused `qkv.weight`.- for target in ("to_q", "to_k", "to_v"):- assert f"{prefix}.{target}.weight" in out- assert f"{prefix}.{target}.weight_scale" in out- assert f"{prefix}.{target}.comfy_quant" in out- assert not any(".qkv." in k for k in out), "the fused keys must not survive"+ Left on `...attention.qkv`, the recovered scale is keyed on a module path the diffusers model+ does not have, so `attach_fp8_scales` finds nothing and the three split weights stay quantized+ but *unscaled* — off by 1/weight_scale, with no error anywhere.+ """++ def test_per_tensor_scale_reaches_all_three_projections(self):+ out = _convert_z_image_gguf_to_diffusers(+ {+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),+ "blk.attention.qkv.scale_weight": torch.tensor(0.25),+ }+ )+ assert not any(".attention.qkv." in k for k in out)+ for name in ("to_q", "to_k", "to_v"):+ assert torch.equal(out[f"blk.attention.{name}.scale_weight"], torch.tensor(0.25))++ def test_per_channel_scale_is_split_like_the_weight(self):+ out = _convert_z_image_gguf_to_diffusers(+ {+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),+ "blk.attention.qkv.weight_scale": torch.arange(6, dtype=torch.float32),+ }+ )+ assert torch.equal(out["blk.attention.to_q.weight_scale"], torch.tensor([0.0, 1.0]))+ assert torch.equal(out["blk.attention.to_k.weight_scale"], torch.tensor([2.0, 3.0]))+ assert torch.equal(out["blk.attention.to_v.weight_scale"], torch.tensor([4.0, 5.0]))++ def test_marker_blob_is_copied_not_split(self):+ # `.comfy_quant` is a 1-D JSON byte string describing the layer, not a per-channel vector.+ blob = torch.frombuffer(b'{"format":"float8_e4m3fn"}', dtype=torch.uint8).clone()+ out = _convert_z_image_gguf_to_diffusers(+ {+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),+ "blk.attention.qkv.comfy_quant": blob,+ }+ )+ for name in ("to_q", "to_k", "to_v"):+ assert torch.equal(out[f"blk.attention.{name}.comfy_quant"], blob)++ def test_unknown_suffix_is_left_alone(self):+ out = _convert_z_image_gguf_to_diffusers(+ {+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),+ "blk.attention.qkv.something_else": torch.tensor(1.0),+ }+ )+ assert "blk.attention.qkv.something_else" in out++ def test_undivisible_scale_is_rejected_rather_than_mis_split(self):+ with pytest.raises(ValueError, match="Cannot split fused QKV quantization data"):+ _convert_z_image_gguf_to_diffusers(+ {+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),+ "blk.attention.qkv.weight_scale": torch.arange(4, dtype=torch.float32),+ }+ )+ def test_the_markers_are_readable_after_the_conversion(self) -> None:+ """Why Z-Image reads them after converting rather than before: unlike Krea-2's converter,+ this one carries `.comfy_quant` onto the final module names, so no re-keying is needed."""+ prefix = "layers.0.attention"+ sd = {+ f"{prefix}.qkv.weight": torch.zeros(3 * 4, 256, dtype=torch.int8),+ f"{prefix}.qkv.weight_scale": torch.ones(3 * 4, 1),+ f"{prefix}.qkv.comfy_quant": _marker_blob(MARKER),+ "x_embedder.weight": torch.zeros(2, 2),+ }+ markers = extract_int8_convrot_markers(_convert_z_image_gguf_to_diffusers(sd))+ assert set(markers) == {f"{prefix}.to_q", f"{prefix}.to_k", f"{prefix}.to_v"}+ assert all(m == MARKER for m in markers.values())+- def test_a_qkv_weight_that_does_not_divide_by_three_is_refused(self) -> None:- sd = {"layers.0.attention.qkv.weight": torch.zeros(7, 8), "x_embedder.weight": torch.zeros(2, 2)}- with pytest.raises(ValueError, match="not divisible by 3"):- _convert_z_image_gguf_to_diffusers(sd)++ class TestMetadataPathRemap:+ """`_quantization_metadata` names layers in the checkpoint's scheme; the scales are recovered+ after the rename, so the per-layer hints have to follow the same route."""++ def test_renamed_layers_map_one_to_one(self):+ mapping = _remap_z_image_layer_paths(["x_embedder", "final_layer.linear", "layers.0.attention.out"])+ assert mapping["x_embedder"] == ["all_x_embedder.2-1"]+ assert mapping["final_layer.linear"] == ["all_final_layer.2-1.linear"]+ assert mapping["layers.0.attention.out"] == ["layers.0.attention.to_out.0"]++ def test_fused_qkv_maps_to_all_three_projections(self):+ mapping = _remap_z_image_layer_paths(["layers.0.attention.qkv"])+ assert mapping["layers.0.attention.qkv"] == [+ "layers.0.attention.to_q",+ "layers.0.attention.to_k",+ "layers.0.attention.to_v",+ ]