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(krea2): load ComfyUI-GGUF Q8_CR transformers (#9697)
Alexander Eichhorn2b2faac84a4a
diff --git a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdxindex f6809c3f6d..000709c777 100644--- a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx@@ -44,7 +44,7 @@ page lists the builds it supports.InvokeAI recognizes the format from the file's contents, so you install them like any other model:-- **GGUF** (`.gguf`, llama.cpp quantization such as Q4_K or Q8_0): weights stay packed in memory and are unpacked layer by layer during generation. Supported for the FLUX.1, FLUX.2, Z-Image, Krea-2, Qwen-Image and Wan transformers, and for the T5, Qwen3, Qwen3-VL, Mistral and Gemma 2 text encoders.+- **GGUF** (`.gguf`, llama.cpp quantization such as Q4_K or Q8_0): weights stay packed in memory and are unpacked layer by layer during generation. Supported for the FLUX.1, FLUX.2, Z-Image, Krea-2, Qwen-Image and Wan transformers, and for the T5, Qwen3, Qwen3-VL, Mistral and Gemma 2 text encoders. ComfyUI-GGUF's `Q8_CR` files, which store int8 (`int8_convrot`) layers inside a `.gguf`, load for the Krea-2 transformer; for other models, and for ComfyUI-GGUF's `Q4_CR`, installation is refused with a message saying so.- **NF4** (bitsandbytes): 4-bit, CUDA only.- **SDNQ**: see [SDNQ Quantization](/configuration/optimization/sdnq-quantization/).- **int8** (`int8_convrot`, from ComfyUI repackages): the weights stay int8 in memory on every device, including Apple Silicon, and need no setting to turn on. Supported for FLUX.1, FLUX.2 Klein, Z-Image, Krea-2, Ideogram 4, MiniMax H3, LTX-2 and the PiD decoders, and for the Qwen3 8B, Qwen3-VL and LTX-2 Gemma encoders.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex 65e9e74b6d..d87a444e5c 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -36,6 +36,7 @@ LoRA). For lower VRAM, use a smaller transformer build:| GGUF Q4_K_M (starter model) | ≈ 7 GB | stays packed, unpacked per layer || GGUF Q8_0 (starter model) | ≈ 13 GB | near-full quality || int8 (`int8_convrot`) | ≈ 12.6 GiB | stays int8 on every device, no FP8 setting needed |+| GGUF Q8_CR (ComfyUI-GGUF) | ≈ 12.8 GiB | the same int8 inside a `.gguf`, stays int8 on every device || fp8 / `fp8_scaled` | ≈ 12.6 GB | with FP8 Storage (switched on at install) or `fp8_compute` || MXFP8 | ≈ 24 GB | unpacked to BF16 at load; prefer the fp8, NVFP4 or GGUF build |@@ -84,6 +85,7 @@ encoder closely; the remaining difference is the quantization of the encoder.`qwen3vl` architecture tag and does not install a plain Qwen3 file as one.- The `mmproj-*.gguf` file next to it holds the vision part and is not needed. Installing it is refusedwith a message saying so.+- ComfyUI-GGUF's `Q8_CR` encoder files are refused at install; only the transformer loads from `Q8_CR`.- LoRAs with text-encoder layers still apply to a quantized encoder.## Conditioning enhancersdiff --git a/invokeai/backend/model_manager/configs/base.py b/invokeai/backend/model_manager/configs/base.pyindex cc6637233a..4c70e61a7e 100644--- a/invokeai/backend/model_manager/configs/base.py+++ b/invokeai/backend/model_manager/configs/base.py@@ -102,6 +102,10 @@ class Config_Base(ABC, BaseModel):"""Set of all non-abstract subclasses of Config_Base, for use during model probing. In other words, this is the setof all known model config types."""+ DECODES_GGUF_Q8_CR: ClassVar[bool] = False+ """Whether this config's loader decodes ComfyUI-GGUF ``Q8_CR`` (int8 convrot) layers. Off by default, so a GGUF+ config refuses those files at install until its loader asks ``gguf_sd_loader`` to decode them."""+model_config = ConfigDict(validate_assignment=True,json_schema_serialization_defaults_required=True,diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.pyindex 6aa10f0bd9..1c893d06d8 100644--- a/invokeai/backend/model_manager/configs/factory.py+++ b/invokeai/backend/model_manager/configs/factory.py@@ -198,6 +198,7 @@ from invokeai.backend.model_manager.taxonomy import (ModelType,variant_type_adapter,)+from invokeai.backend.quantization.gguf.loaders import parse_q8_cr_markerslogger = logging.getLogger(__name__)@@ -657,6 +658,27 @@ class ModelConfigFactory:e.__cause__ = Nonereturn e+ @staticmethod+ def _raise_for_unsupported_gguf_quantization(mod: ModelOnDisk, config: Config_Base) -> None:+ """Refuse a GGUF whose ComfyUI-GGUF quantization the matched config's loader cannot decode.++ Here rather than in each GGUF config: the question is the same for all of them, and a GGUF config+ added later is refused by default instead of installing a file it fails on at the first render.+ `InvalidMatchError`, so the installer shows the reason rather than registering an unknown model.+ Read from the cached metadata, so a large file is not re-read once per candidate.+ """+ if getattr(config, "format", None) is not ModelFormat.GGUFQuantized:+ return+ try:+ markers = parse_q8_cr_markers(mod.metadata(), mod.path.name)+ except ValueError as e:+ raise InvalidMatchError(str(e)) from None+ if markers and not type(config).DECODES_GGUF_Q8_CR:+ raise InvalidMatchError(+ f"{mod.path.name} is a ComfyUI-GGUF Q8_CR (int8 convrot) file, which this model type cannot load "+ "yet. Use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."+ )+@staticmethoddef from_dict(fields: dict[str, Any]) -> AnyModelConfig:"""Return the appropriate config object from raw dict values."""@@ -864,7 +886,9 @@ class ModelConfigFactory:try:# Technically, from_model_on_disk returns a Config_Base, but in practice it will always be a member of# the AnyModelConfig union.- details[candidate_name] = candidate_class.from_model_on_disk(mod, fields) # type: ignore+ candidate = candidate_class.from_model_on_disk(mod, fields)+ ModelConfigFactory._raise_for_unsupported_gguf_quantization(mod, candidate)+ details[candidate_name] = candidate # type: ignoreexcept NotAMatchError as e:# This means the model didn't match this config class. It's not an error, just no match.details[candidate_name] = ModelConfigFactory._detach_traceback(e)diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex bb1c7153c7..7c3534c0f2 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -1,7 +1,7 @@import refrom abc import ABCfrom pathlib import Path-from typing import Any, Literal, Self+from typing import Any, ClassVar, Literal, Selfimport torchfrom pydantic import BaseModel, Field@@ -2043,6 +2043,8 @@ class Main_Checkpoint_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Conclass Main_GGUF_Krea2_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):"""Model config for GGUF-quantized Krea-2 transformer models (single-file)."""+ DECODES_GGUF_Q8_CR: ClassVar[bool] = True+base: Literal[BaseModelType.Krea2] = Field(default=BaseModelType.Krea2)format: Literal[ModelFormat.GGUFQuantized] = Field(default=ModelFormat.GGUFQuantized)variant: Krea2VariantType = Field()diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex dcf516039d..9f4a9a82ba 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -63,6 +63,8 @@ from invokeai.backend.quantization.int8_convrot import (install_int8_convrot_layers,reject_unmarked_int8_weights,resolve_quantized_module_paths,+ split_int8_convrot_layers,+ swap_in_int8_linears,)from invokeai.backend.quantization.load_plan import reserve_for_loadfrom invokeai.backend.quantization.nvfp4 import (@@ -642,7 +644,9 @@ class Krea2GGUFCheckpointModel(ModelLoader):GGUF ships only the transformer; the VAE (Qwen-Image), Qwen3-VL encoder, tokenizer and schedulerare sourced separately by the Krea-2 model-loader invocation (mix-and-match, like Z-Image/FLUX).- The GGML tensors stay quantized and are dequantized on-the-fly during inference.+ The GGML tensors stay quantized and are dequantized on-the-fly during inference. ComfyUI-GGUF's+ ``Q8_CR`` layers arrive from `gguf_sd_loader` as an ``int8_tensorwise`` export and stay int8 as+ `Int8ConvrotLinear`, beside whatever GGML-quantized layers the same file mixes in."""def _load_model(@@ -669,15 +673,41 @@ class Krea2GGUFCheckpointModel(ModelLoader):compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)# GGMLTensor wrappers (kept on CPU; dequantized on-the-fly by the cache during inference).- sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype)+ sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype, q8_cr="decode")sd = CheckpointPrefix.detect(sd).strip(sd)+ # As in the single-file loader: the key conversion drops these weights but not their markers.+ sd = _drop_discarded_native_final_layers(sd)+ # Before the key conversion, which carries `.weight_scale` along with its weight but not+ # `.comfy_quant` -- see the single-file loader above.+ int8_markers = extract_int8_convrot_markers(sd)+ # An `I8` tensor the metadata does not claim is still a GGMLTensor of dtype int8, and `gguf` has+ # no dequantizer for it: without this it fails on the first denoise step instead of here.+ reject_unmarked_int8_weights(sd, int8_markers, "Krea-2 GGUF")# GGUF conversions use the native/ComfyUI compact key naming; remap to diffusers keys.+ key_map: dict[str, str] = {}if _is_native_krea2_format(sd):- sd = _convert_krea2_native_to_diffusers(sd)+ sd = _convert_krea2_native_to_diffusers(sd, key_map=key_map)with accelerate.init_empty_weights():model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)+ if int8_markers:+ # Not `install_int8_convrot_layers`: its cast and RAM reservation are for a state dict of+ # dense tensors, and casting a GGMLTensor to another dtype raises. Everything else in this+ # file stays the GGMLTensor it already is, so only the split and the swap apply.+ quantized = split_int8_convrot_layers(+ sd,+ resolve_quantized_module_paths(int8_markers, key_map),+ compute_dtype,+ model=model,+ skip_patterns=_model_declared_skip_patterns(model),+ )+ swap_in_int8_linears(model, sd, quantized)+ self._logger.info(+ f"Krea-2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 "+ "(ComfyUI-GGUF Q8_CR, dequantized per forward)"+ )+load_state_dict_ignoring_extras(model, sd, source="Krea-2 GGUF checkpoint", assign=True, allow_missing=True)# Reject GGUF layouts that don't fully populate the diffusers Krea2Transformer2DModel (city96/# ComfyUI GGUFs may use key names needing conversion). Failing here beats a confusing meta-tensordiff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.pyindex 6087a195ad..f8de6f242e 100644--- a/invokeai/backend/model_manager/model_on_disk.py+++ b/invokeai/backend/model_manager/model_on_disk.py@@ -201,7 +201,9 @@ class ModelOnDisk:checkpoint = torch.load(path, map_location="meta")assert isinstance(checkpoint, dict)elif path.suffix.endswith(".gguf"):- checkpoint = gguf_sd_loader(path, compute_dtype=torch.float32)+ # Identification reads shapes and never builds a module. Whether a Q8_CR file's quantization+ # is supported is decided from its metadata by `ModelConfigFactory`, once, not per candidate.+ checkpoint = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="ignore")elif path.suffix.endswith(".safetensors"):if _is_sdnq_safetensors(path):checkpoint = sdnq_sd_loader(path, compute_dtype=torch.float32)diff --git a/invokeai/backend/quantization/gguf/loaders.py b/invokeai/backend/quantization/gguf/loaders.pyindex 0ef98433f7..f5abfa0450 100644--- a/invokeai/backend/quantization/gguf/loaders.py+++ b/invokeai/backend/quantization/gguf/loaders.py@@ -1,14 +1,18 @@import gc+import jsonimport math+from collections.abc import Mappingfrom pathlib import Path-from typing import Any+from typing import Any, Literalimport ggufimport numpy as npimport torch+from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIXfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES+from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMATfrom invokeai.backend.util.logging import InvokeAILoggerlogger = InvokeAILogger.get_logger()@@ -91,10 +95,89 @@ def _read_comfy_orig_shapes(reader: gguf.GGUFReader) -> dict[str, torch.Size]:return orig_shapes-def gguf_sd_loader(path: Path, compute_dtype: torch.dtype) -> dict[str, GGMLTensor]:+COMFY_QUANT_KEY_PREFIX = "comfy.gguf.quant."++Q8CRMode = Literal["refuse", "decode", "ignore"]+++def parse_q8_cr_markers(fields: Mapping[str, Any], source: str) -> dict[str, dict[str, Any]]:+ """Parse ComfyUI-GGUF's ``Q8_CR`` layers from a GGUF's ``comfy.gguf.quant.<weight name>`` metadata.++ ``Q8_CR`` (github.com/molbal/ComfyUI-GGUF) is ComfyUI's ``int8_tensorwise`` + convrot scheme in a+ GGUF container: the int8 codes are stored under GGML type ``I8`` (GGUF has no other int8 type), a+ per-output-row F32 scale beside them as ``<weight name>_scale``, and the JSON that a safetensors+ export keeps in ``<layer>.comfy_quant`` here lives in the metadata, as a string. ``I8`` is not a+ GGML quantization -- ``gguf`` has no dequantizer for it -- so these layers cannot ride the+ GGMLTensor path at all.++ ``fields`` maps metadata keys to their string values; other keys are ignored. Returns the int8+ markers keyed by weight name, in the form :mod:`int8_convrot` reads. Raises ``ValueError`` for+ anything else the converter writes (``int4_cr``, the retired ``int4_pytorch``): those tensors are+ ``I8`` too, and nothing here decodes them. Model identification turns that into the installer's+ refusal, so a file is refused for the same reason at install and at load.+ """+ layers: dict[str, dict[str, Any]] = {}+ for key, value in fields.items():+ if not key.startswith(COMFY_QUANT_KEY_PREFIX):+ continue+ weight_name = key[len(COMFY_QUANT_KEY_PREFIX) :]+ try:+ config = json.loads(value)+ except Exception as e:+ raise ValueError(f"{source}: GGUF metadata {key!r} is not valid quantization JSON: {e}") from None+ if not isinstance(config, dict) or config.get("format") != INT8_TENSORWISE_FORMAT:+ fmt = config.get("format") if isinstance(config, dict) else config+ raise ValueError(+ f"{source}: tensor {weight_name!r} uses ComfyUI-GGUF quantization {fmt!r}, which is not "+ f"supported. Only {INT8_TENSORWISE_FORMAT!r} (Q8_CR) layers can be loaded from GGUF."+ )+ if not weight_name.endswith(".weight"):+ raise ValueError(f"{source}: {INT8_TENSORWISE_FORMAT} metadata names {weight_name!r}, not a weight.")+ marker = dict(config)+ # The converter's own loader treats `convrot` without `weight_rotated` as a file from an older+ # converter that stored the codes unrotated, and runs it without the rotation. Un-rotating+ # weights that were never rotated would scramble them, so follow it.+ if marker.get("convrot") and not marker.get("weight_rotated", False):+ marker["convrot"] = False+ marker.pop("convrot_groupsize", None)+ layers[weight_name] = marker+ return layers+++def gguf_sd_loader(path: Path, compute_dtype: torch.dtype, *, q8_cr: Q8CRMode = "refuse") -> dict[str, torch.Tensor]:+ """Read a GGUF file into a state dict of ``GGMLTensor``s, dequantized on the fly at use.++ ``q8_cr`` says what to do with ComfyUI-GGUF ``Q8_CR`` layers (see :func:`parse_q8_cr_markers`):++ - ``"decode"``: their weight, scale and bias come back as plain tensors with a ``<layer>.comfy_quant``+ marker beside them -- exactly a safetensors ``int8_tensorwise`` export, so the loader decodes both+ containers with the same :mod:`int8_convrot` code. Only a loader that does so may ask for this.+ - ``"refuse"``: any other loader. Raises before the tensors are read; without it the int8 codes reach+ a plain ``nn.Linear`` and the load fails on a dtype error that names neither the file nor the format.+ Identification refuses such files at install already, so this guards records made before it did.+ - ``"ignore"``: model identification, which needs shapes and never builds a module. The file reads as+ it always has; whether its quantization is supported is the installer's question, answered from+ the metadata (see ``ModelConfigFactory``), so it is not raised here once per candidate config.+ """with WrappedGGUFReader(path) as reader:- sd: dict[str, GGMLTensor] = {}+ sd: dict[str, torch.Tensor] = {}orig_shapes = _read_comfy_orig_shapes(reader)+ int8_layers: dict[str, dict[str, Any]] = {}+ if q8_cr != "ignore":+ quant_fields = {k: f.contents() for k, f in reader.fields.items() if k.startswith(COMFY_QUANT_KEY_PREFIX)}+ int8_layers = parse_q8_cr_markers(quant_fields, path.name)+ if int8_layers and q8_cr == "refuse":+ raise ValueError(+ f"{path.name} holds {len(int8_layers)} ComfyUI-GGUF Q8_CR (int8 convrot) layer(s), e.g. "+ f"{next(iter(int8_layers))!r}. Loading Q8_CR from GGUF is not supported for this model type; "+ "use a GGML-quantized (Q8_0, Q4_K, ...) or safetensors build instead."+ )+ int8_scales = {f"{name}_scale" for name in int8_layers}+ int8_biases = {f"{name[: -len('.weight')]}.bias" for name in int8_layers}+ missing = sorted((int8_layers.keys() | int8_scales) - {tensor.name for tensor in reader.tensors})+ if missing:+ raise ValueError(f"{path.name}: Q8_CR metadata names layers the file does not hold, e.g. {missing[0]!r}.")+for tensor in reader.tensors:# Use .copy() to create a true copy of the data, not a view.# This is critical on Windows where the memory-mapped file cannot be deleted@@ -110,12 +193,31 @@ def gguf_sd_loader(path: Path, compute_dtype: torch.dtype) -> dict[str, GGMLTensf"different element count than its stored shape {tuple(shape)}.")shape = orig_shape++ if tensor.name in int8_layers or tensor.name in int8_scales:+ expected = gguf.GGMLQuantizationType.I8 if tensor.name in int8_layers else gguf.GGMLQuantizationType.F32+ if tensor.tensor_type != expected:+ raise ValueError(+ f"{path.name}: Q8_CR tensor {tensor.name!r} is stored as {tensor.tensor_type.name}, "+ f"expected {expected.name}."+ )+ sd[tensor.name] = torch_tensor.reshape(shape)+ continue+if tensor.tensor_type in TORCH_COMPATIBLE_QTYPES:torch_tensor = torch_tensor.view(*shape)- sd[tensor.name] = GGMLTensor(+ ggml_tensor = GGMLTensor(torch_tensor,ggml_quantization_type=tensor.tensor_type,tensor_shape=shape,compute_dtype=compute_dtype,)+ # An int8 layer's bias becomes a buffer of `Int8ConvrotLinear`, whose forward casts it to the+ # activation dtype -- a dtype change a GGMLTensor refuses.+ sd[tensor.name] = ggml_tensor.get_dequantized_tensor() if tensor.name in int8_biases else ggml_tensor++ for weight_name, marker in int8_layers.items():+ raw = json.dumps(marker).encode("utf-8")+ marker_key = f"{weight_name[: -len('.weight')]}{COMFY_QUANT_SUFFIX}"+ sd[marker_key] = torch.frombuffer(bytearray(raw), dtype=torch.uint8)return sddiff --git a/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.py b/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.pynew file mode 100644index 0000000000..668e9d5b9a--- /dev/null+++ b/tests/backend/model_manager/configs/test_gguf_q8_cr_identification.py@@ -0,0 +1,76 @@+"""Install-time decisions for ComfyUI-GGUF ``Q8_CR`` files, made through ``ModelConfigFactory``.++These run at the *default* ``allow_unknown``, because that is what decides what the user sees: a file a+config recognises but cannot load must come back as a refusal with its reason, not register as an Unknown+model whose explanation is only in the server log. Fixtures are real GGUF files of a few kilobytes.+"""++from pathlib import Path+from typing import Any++import pytest+import torch++from invokeai.backend.model_manager.configs.factory import ModelConfigFactory+from invokeai.backend.model_manager.configs.main import Main_GGUF_Krea2_Config+from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_gguf++_OVERRIDE_FIELDS: dict[str, object] = {+ "hash": "blake3:fakehash",+ "path": "/fake/models/test-model",+ "file_size": 1000,+ "name": "test-model",+ "description": "test",+ "source": "test",+ "source_type": "path",+ "key": "test-key",+}+++def _krea2_q8_cr(path: Path, marker: dict[str, Any]) -> Path:+ """A native-named Krea-2 GGUF with one quantized layer, as ComfyUI-GGUF's converter writes one."""+ payload = quantize_convrot(torch.randn(4, 256))+ write_gguf(+ path,+ {+ "txtfusion.projector.weight": torch.ones(12, 1),+ "first.weight": torch.ones(8, 4),+ "tproj.0.weight": torch.ones(8, 4),+ "blocks.0.attn.wq.weight": payload.codes,+ "blocks.0.attn.wq.weight_scale": payload.scale,+ },+ quant={"blocks.0.attn.wq.weight": marker},+ )+ return path+++def _identify(path: Path) -> Any:+ return ModelConfigFactory.from_model_on_disk(path, dict(_OVERRIDE_FIELDS), allow_unknown=True)+++def test_a_q8_cr_krea2_gguf_installs_as_a_krea2_gguf(tmp_path: Path) -> None:+ result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))++ assert isinstance(result.config, Main_GGUF_Krea2_Config)+ assert not result.invalid_matches+++def test_a_q8_cr_gguf_is_refused_with_its_reason_where_the_loader_cannot_decode_it(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The gate every other GGUF config sits behind. Driven through the Krea-2 config with its+ capability switched off, so the fixture is one that is otherwise known to install."""+ monkeypatch.setattr(Main_GGUF_Krea2_Config, "DECODES_GGUF_Q8_CR", False)++ result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q8_CR.gguf", q8_cr_marker()))++ assert result.config is None+ assert any("Q8_CR" in str(reason) for reason in result.invalid_matches)+++def test_a_q4_cr_gguf_is_refused_with_its_reason(tmp_path: Path) -> None:+ """ComfyUI-GGUF's Q4_CR is advertised beside Q8_CR and stores its codes as I8 as well."""+ result = _identify(_krea2_q8_cr(tmp_path / "krea2_turbo-Q4_CR.gguf", {"format": "int4_cr", "backing": "w4a4"}))++ assert result.config is None+ assert any("int4_cr" in str(reason) for reason in result.invalid_matches)diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex eb0b4516e1..29082594df 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -208,7 +208,7 @@ def test_gguf_loader_constructs_and_materializes_model(monkeypatch, tmp_path) ->monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2Transformer, raising=False)monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.krea2.gguf_sd_loader",- lambda _path, *, compute_dtype: {"weight": torch.ones(2, 2, dtype=compute_dtype)},+ lambda _path, *, compute_dtype, **_kwargs: {"weight": torch.ones(2, 2, dtype=compute_dtype)},)monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",@@ -226,6 +226,70 @@ def test_gguf_loader_constructs_and_materializes_model(monkeypatch, tmp_path) ->assert torch.equal(model.weight, torch.ones(2, 2))+def _gguf_driver(monkeypatch, path, model_class):+ import diffusers++ config = Main_GGUF_Krea2_Config.model_construct(path=str(path), variant=Krea2VariantType.Turbo)+ loader = object.__new__(Krea2GGUFCheckpointModel)+ loader._logger = MagicMock()+ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", model_class, raising=False)+ 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,+ )+ return loader, config+++def test_gguf_loader_keeps_a_q8_cr_layer_int8_through_the_native_rename(monkeypatch, tmp_path) -> None:+ """A ComfyUI-GGUF Q8_CR file names its layers natively, and its markers are read before the rename+ to diffusers keys -- which carries the scale along with the weight but not the marker. The marker has+ to follow the weight's own rename, or `wq` never becomes an `Int8ConvrotLinear` and its codes land in+ a plain Linear. The dense neighbours stay the GGMLTensors the GGUF path always produced."""+ from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+ from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_gguf++ width = _TinyNativeKrea2.WIDTH+ # The smallest regular Hadamard: the tiny model is narrower than the 256 every real build uses.+ group_size = 4+ torch.manual_seed(7)+ payload = quantize_convrot(torch.randn(width, width), group_size=group_size)+ tensors = {+ **_native_block(width),+ "blocks.0.attn.wq.weight": payload.codes,+ "blocks.0.attn.wq.weight_scale": payload.scale,+ }+ path = tmp_path / "krea2_q8_cr.gguf"+ write_gguf(path, tensors, quant={"blocks.0.attn.wq.weight": q8_cr_marker(group_size=group_size)})+ loader, config = _gguf_driver(monkeypatch, path, _TinyNativeKrea2)++ model = loader._load_from_gguf(config)++ to_q = model.transformer_blocks[0].attn.to_q+ assert isinstance(to_q, Int8ConvrotLinear)+ assert to_q.weight.dtype is torch.int8+ assert torch.allclose(to_q._dequantized_weight(torch.device("cpu"), torch.float32), payload.dequantized, atol=1e-5)+ assert isinstance(model.img_in.weight, GGMLTensor)+++def test_gguf_loader_refuses_an_i8_tensor_no_metadata_claims(monkeypatch, tmp_path) -> None:+ """`gguf` has no dequantizer for `I8`, so an unclaimed int8 tensor used to load and then fail on the+ first denoise step with `Dequantization for I8 is not yet implemented`."""+ from tests.fixtures.quantized_payloads import write_gguf++ path = tmp_path / "krea2_unmarked.gguf"+ write_gguf(+ path, {**_native_block(_TinyNativeKrea2.WIDTH), "blocks.0.attn.wq.weight": torch.zeros(8, 8, dtype=torch.int8)}+ )+ loader, config = _gguf_driver(monkeypatch, path, _TinyNativeKrea2)++ with pytest.raises(ValueError, match="blocks.0.attn.wq.weight"):+ loader._load_from_gguf(config)++def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeypatch, tmp_path) -> None:"""The encoder path carries the same hazard as the transformer, plus one of its own.diff --git a/tests/backend/quantization/gguf/test_loaders.py b/tests/backend/quantization/gguf/test_loaders.pyindex 4539af5a72..bd533a636c 100644--- a/tests/backend/quantization/gguf/test_loaders.py+++ b/tests/backend/quantization/gguf/test_loaders.py@@ -5,7 +5,9 @@ import numpy as npimport pytestimport torch+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_ggufdef _write_gguf(path, *, orig_shape: Sequence[float] | None) -> None:@@ -66,3 +68,125 @@ def test_gguf_sd_loader_ignores_malformed_orig_shape(tmp_path, orig_shape):sd = gguf_sd_loader(path, compute_dtype=torch.bfloat16)assert tuple(sd["first.weight"].shape) == (1536, 256)+++def _q8_cr_layer(name: str, out_features: int = 4, group_size: int = 256, seed: int = 0) -> dict[str, torch.Tensor]:+ """One Q8_CR layer's tensors as ComfyUI-GGUF writes them."""++ torch.manual_seed(seed)+ payload = quantize_convrot(torch.randn(out_features, group_size), group_size=group_size)+ return {f"{name}.weight": payload.codes, f"{name}.weight_scale": payload.scale}+++def test_a_q8_cr_layer_loads_as_an_int8_tensorwise_export(tmp_path):+ """The codes, scale and marker come back exactly as a safetensors export holds them -- and a+ GGML-quantized neighbour in the same file, as the converter's mixed plans write one, stays the+ GGMLTensor it was. (The decode itself is driven end to end by the Krea-2 loader tests.)"""+ from invokeai.backend.quantization.int8_convrot import extract_int8_convrot_markers++ path = tmp_path / "model.gguf"+ tensors = _q8_cr_layer("blocks.0.attn.wq")+ write_gguf(+ path,+ {**tensors, "blocks.0.prenorm.scale": torch.ones(256)},+ quant={"blocks.0.attn.wq.weight": q8_cr_marker()},+ q8_0={"blocks.0.mlp.up.weight": torch.randn(4, 64)},+ )++ sd = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")++ weight, scale = sd["blocks.0.attn.wq.weight"], sd["blocks.0.attn.wq.weight_scale"]+ assert not isinstance(weight, GGMLTensor) and torch.equal(weight, tensors["blocks.0.attn.wq.weight"])+ assert not isinstance(scale, GGMLTensor) and torch.equal(scale, tensors["blocks.0.attn.wq.weight_scale"])+ assert extract_int8_convrot_markers(sd) == {"blocks.0.attn.wq": q8_cr_marker()}+ up = sd["blocks.0.mlp.up.weight"]+ assert isinstance(up, GGMLTensor) and up.get_dequantized_tensor().shape == (4, 64)+ assert isinstance(sd["blocks.0.prenorm.scale"], GGMLTensor)+++def test_a_q8_cr_file_is_refused_unless_the_caller_decodes_int8(tmp_path):+ """Every loader but the ones wired for int8 would put the codes into a plain Linear."""++ path = tmp_path / "model.gguf"+ write_gguf(path, _q8_cr_layer("blocks.0.attn.wq"), quant={"blocks.0.attn.wq.weight": q8_cr_marker()})++ with pytest.raises(ValueError, match=r"model\.gguf holds 1 ComfyUI-GGUF Q8_CR"):+ gguf_sd_loader(path, compute_dtype=torch.float32)+++def test_identification_reads_a_q8_cr_file_as_it_always_has(tmp_path):+ """Identification asks only for shapes, once per candidate config. A format it cannot decode must not+ raise there -- the factory refuses it from the metadata, with its reason -- and nothing is translated."""++ path = tmp_path / "model.gguf"+ write_gguf(path, _q8_cr_layer("proj"), quant={"proj.weight": {"format": "int4_cr", "backing": "w4a4"}})++ sd = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="ignore")++ assert isinstance(sd["proj.weight"], GGMLTensor)+ assert "proj.comfy_quant" not in sd++[email protected]("weight_rotated", [pytest.param(None, id="missing"), pytest.param(False, id="false")])+def test_a_convrot_layer_not_marked_weight_rotated_is_read_unrotated(tmp_path, weight_rotated):+ """Older converters stored the codes unrotated under `convrot: true`; ComfyUI-GGUF's own loader+ runs those without the rotation, and un-rotating them would scramble the weight."""+ from invokeai.backend.quantization.int8_convrot import extract_int8_convrot_markers++ path = tmp_path / "model.gguf"+ marker = q8_cr_marker(weight_rotated=weight_rotated)+ if weight_rotated is None:+ del marker["weight_rotated"]+ write_gguf(path, _q8_cr_layer("proj"), quant={"proj.weight": marker})++ markers = extract_int8_convrot_markers(gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode"))++ assert markers["proj"]["convrot"] is False+ assert "convrot_groupsize" not in markers["proj"]+++def test_an_int8_layers_bias_is_read_as_a_plain_tensor(tmp_path):+ """`Int8ConvrotLinear` casts its bias to the activation dtype, which a GGMLTensor refuses."""++ path = tmp_path / "model.gguf"+ bias = torch.arange(4, dtype=torch.float32)+ write_gguf(path, {**_q8_cr_layer("proj"), "proj.bias": bias}, quant={"proj.weight": q8_cr_marker()})++ sd = gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")++ assert not isinstance(sd["proj.bias"], GGMLTensor)+ assert torch.equal(sd["proj.bias"], bias)+++ ("quant", "tensors", "message"),+ [+ pytest.param(+ {"proj.weight": {"format": "int4_cr", "backing": "w4a4"}},+ {},+ "quantization 'int4_cr', which is not supported",+ id="int4",+ ),+ pytest.param({"proj.weight": "{not json"}, {}, "is not valid quantization JSON", id="malformed-json"),+ pytest.param({"proj": q8_cr_marker()}, {}, "names 'proj', not a weight", id="not-a-weight"),+ pytest.param(+ {"proj.weight": q8_cr_marker()},+ {"proj.weight_scale": None},+ "does not hold.*'proj.weight_scale'",+ id="missing-scale",+ ),+ pytest.param(+ {"proj.weight": q8_cr_marker()},+ {"proj.weight_scale": torch.ones(4, 1, dtype=torch.float16)},+ "'proj.weight_scale' is stored as F16, expected F32",+ id="scale-not-f32",+ ),+ ],+)+def test_a_q8_cr_file_the_decode_cannot_read_is_refused(tmp_path, quant, tensors, message):+ path = tmp_path / "model.gguf"+ layer = {**_q8_cr_layer("proj"), **tensors}+ write_gguf(path, {k: v for k, v in layer.items() if v is not None}, quant=quant)++ with pytest.raises(ValueError, match=message):+ gguf_sd_loader(path, compute_dtype=torch.float32, q8_cr="decode")diff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.pyindex 2dba76f065..c611afec8b 100644--- a/tests/fixtures/quantized_payloads.py+++ b/tests/fixtures/quantized_payloads.py@@ -201,3 +201,55 @@ def mxfp8_marker(*, block_size: int = MX_BLOCK_SIZE) -> dict[str, object]:writes, so a rename on our side has to be caught by a test, not mirrored by one."""return {"format": "mxfp8", "block_size": block_size}+++def q8_cr_marker(*, group_size: int = CONVROT_GROUP_SIZE, **overrides: Any) -> dict[str, Any]:+ """The JSON ComfyUI-GGUF's converter stores per ``Q8_CR`` weight (``quantize_int8_convrot`` in+ github.com/molbal/ComfyUI-GGUF ``tools/convert.py``). Unlike a safetensors ``.comfy_quant`` it says+ ``weight_rotated`` explicitly; that converter's loader runs a ``convrot`` layer without it unrotated.+ """+ return {+ "format": "int8_tensorwise",+ "convrot": True,+ "weight_rotated": True,+ "per_row": True,+ "convrot_groupsize": group_size,+ **overrides,+ }+++def write_gguf(+ path: Any,+ tensors: Mapping[str, torch.Tensor],+ *,+ quant: Mapping[str, Mapping[str, Any] | str] | None = None,+ q8_0: Mapping[str, torch.Tensor] | None = None,+ architecture: str = "krea2",+) -> None:+ """Write a GGUF the way ComfyUI-GGUF lays out a ``Q8_CR`` file.++ ``tensors`` are stored by dtype: int8 as GGML ``I8`` (how the converter stores Q8_CR codes), float32+ as ``F32``, float16 as ``F16``. ``quant`` maps a weight name to its JSON, written as the string+ ``comfy.gguf.quant.<weight name>`` (a string is written as it is, for malformed metadata). ``q8_0`` tensors are GGML-quantized, which is what the converter's+ target-size plans put beside Q8_CR layers in the same file.+ """+ import gguf++ qtypes = {+ torch.int8: gguf.GGMLQuantizationType.I8,+ torch.float32: gguf.GGMLQuantizationType.F32,+ torch.float16: gguf.GGMLQuantizationType.F16,+ }+ writer = gguf.GGUFWriter(str(path), architecture)+ for name, marker in (quant or {}).items():+ writer.add_string(f"comfy.gguf.quant.{name}", marker if isinstance(marker, str) else json.dumps(dict(marker)))+ for name, tensor in tensors.items():+ writer.add_tensor(name, tensor.numpy(), raw_dtype=qtypes[tensor.dtype])+ for name, tensor in (q8_0 or {}).items():+ data = tensor.to(torch.float32).numpy()+ packed = gguf.quants.quantize(data, gguf.GGMLQuantizationType.Q8_0)+ writer.add_tensor(name, packed, raw_dtype=gguf.GGMLQuantizationType.Q8_0)+ writer.write_header_to_file()+ writer.write_kv_data_to_file()+ writer.write_tensors_to_file()+ writer.close()