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
fix(minimax-h3): refuse scaled fp8 by name instead of in the qkv split
Alexander Eichhorn172339704053
diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.pyindex 353ad051c4..0c5cd3c7ae 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py@@ -22,8 +22,9 @@ The two ``MiniMaxH3Scheduler`` instances (video shift 12.0, audio shift 3.0) aredirectly by the denoise invocation - they are stateless configs, not loaded weights."""+from collections.abc import Mappingfrom pathlib import Path-from typing import Optional+from typing import Any, Optionalimport torch@@ -45,6 +46,60 @@ from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_from invokeai.backend.util.devices import TorchDevice+def _reject_formats_declared_in_the_header(model_path: Path, what: str, logger: Any) -> None:+ """Refuse a quantization format this loader cannot read, from the header alone.++ Before the tensor read, which is ~20 GiB for the transformer and ~25 GiB for the encoder. Both+ header transports are read, because which one a file uses depends on the tool that produced it,+ not on the format: a per-tensor ``.comfy_quant`` marker, or an entry in ``_quantization_metadata``.+ FLUX.2's Comfy-Org fp8 build uses only the second, and reading only the first let a file of that+ shape through to the converter, which died in the fused-qkv split with a bare ``IndexError`` that+ named neither fp8 nor the format.++ The two are read with different strictness on purpose. A per-tensor marker exists only to declare+ a scheme, so one without a readable ``format`` is refused as unreadable, as it always was. A header+ entry can carry per-layer flags and nothing else -- ``full_precision_matrix_mult`` alone is a+ well-formed entry -- so one without a ``format`` declares nothing and is skipped; refusing it would+ turn away a valid int8 build for a hint this loader does not even read. An entry that is not a+ mapping at all is refused as unreadable rather than left to raise ``AttributeError``.+ """+ from invokeai.backend.quantization.fp8_scaled import parse_quantization_metadata, read_safetensors_metadata+ from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT, read_comfy_quant_markers++ declared = [marker.get("format") for marker in read_comfy_quant_markers(model_path).values()]+ for entry in parse_quantization_metadata(read_safetensors_metadata(model_path, logger)).values():+ if not isinstance(entry, Mapping):+ declared.append(None)+ elif "format" in entry:+ declared.append(entry["format"])+ unsupported = sorted({str(fmt or "unreadable") for fmt in declared if fmt != INT8_TENSORWISE_FORMAT})+ if unsupported:+ raise ValueError(+ f"Unsupported quantization format(s) {unsupported} in {what} {model_path.name}. "+ "Only unquantized and Comfy 'int8_tensorwise' (int8/int8-convrot) single files are supported."+ )+++def _reject_float8_weights(sd: dict[str, Any], what: str, model_path: Path) -> None:+ """Refuse float8 weights that nothing in the header declared.++ The older ComfyUI scaled-fp8 shape declares itself nowhere -- fp8 codes and a ``weight_scale``+ beside them, no marker, no header entry -- so the header gate cannot see it. Refused here, after+ the read but before the converter, which is where it otherwise failed: in the qkv split on a+ per-tensor scale, or at ``load_state_dict`` on an orphaned scale reported as an "unexpected key".+ Keyed on the dtype rather than on a scale key, so a raw fp8 file with no scale is named too+ instead of loading fp8 parameters that fail at the first matmul.+ """+ from invokeai.backend.quantization.fp8_scaled import FP8_WEIGHT_DTYPES++ carried = sorted(key for key, value in sd.items() if getattr(value, "dtype", None) in FP8_WEIGHT_DTYPES)+ if carried:+ raise ValueError(+ f"{what} {model_path.name} carries {len(carried)} float8 weight(s) (e.g. {', '.join(carried[:3])}). "+ "Only unquantized and Comfy 'int8_tensorwise' (int8/int8-convrot) single files are supported."+ )++def _raise_if_no_weight_shards(submodel_path: Path, submodel_label: str) -> None:"""Fail with an actionable message when a components-only (slim) install is asked for asubmodel whose weights it does not carry.@@ -190,7 +245,6 @@ class MiniMaxH3CheckpointModel(ModelLoader):)from invokeai.backend.quantization.int8_convrot import (INT8_TENSORWISE_FORMAT,- read_comfy_quant_markers,swap_in_int8_linears,)@@ -200,22 +254,9 @@ class MiniMaxH3CheckpointModel(ModelLoader):# the vendored attention classes); see contiguous_attention for the measurements.patch_minimax_h3_attention_contiguous_qkv()- # Reject unsupported quantization formats from the header alone, before committing to- # the ~20 GiB tensor read (the fp8_scaled repacks share this key layout).- unsupported = sorted(- {- str(marker.get("format") or "unreadable")- for marker in read_comfy_quant_markers(model_path).values()- if marker.get("format") != INT8_TENSORWISE_FORMAT- }- )- if unsupported:- raise ValueError(- f"Unsupported quantization format(s) {unsupported} in MiniMax H3 checkpoint {model_path.name}. "- "Only unquantized and Comfy 'int8_tensorwise' (int8/int8-convrot) single files are supported."- )-+ _reject_formats_declared_in_the_header(model_path, "MiniMax H3 checkpoint", self._logger)sd = load_file(model_path)+ _reject_float8_weights(sd, "MiniMax H3 checkpoint", model_path)rope_freq_dim = sd["rope.inv_freq"].shape[0] if "rope.inv_freq" in sd else 16sd, quant_markers = convert_minimax_h3_checkpoint_to_diffusers(sd)@@ -334,29 +375,14 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):)from invokeai.backend.quantization.int8_convrot import (INT8_TENSORWISE_FORMAT,- read_comfy_quant_markers,swap_in_int8_linears,)model_path = Path(config.path)- # Reject unsupported quantization formats from the header alone, before the ~25 GiB- # tensor read (the nvfp4_awq repacks share this key layout).- unsupported = sorted(- {- str(marker.get("format") or "unreadable")- for marker in read_comfy_quant_markers(model_path).values()- if marker.get("format") != INT8_TENSORWISE_FORMAT- }- )- if unsupported:- raise ValueError(- f"Unsupported quantization format(s) {unsupported} in MiniMax H3 text encoder "- f"{model_path.name}. Only unquantized and Comfy 'int8_tensorwise' (int8/int8-convrot) "- "single files are supported."- )-+ _reject_formats_declared_in_the_header(model_path, "MiniMax H3 text encoder", self._logger)sd = load_file(model_path)+ _reject_float8_weights(sd, "MiniMax H3 text encoder", model_path)sd, quant_markers = convert_minimax_h3_text_encoder_checkpoint(sd)self._ram_cache.make_room(sum(t.nelement() * t.element_size() for t in sd.values()))diff --git a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.pyindex 6788acc339..02f2206540 100644--- a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py+++ b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py@@ -163,3 +163,151 @@ def test_a_nul_padded_header_marker_is_read(tmp_path) -> None:assert markers == {"blocks.0.attn.out_proj": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP_SIZE}}+++def _write_fp8_checkpoint(tmp_path: Path, *, declared_in_header: bool) -> Path:+ """A tiny pruned H3 checkpoint in ComfyUI scaled fp8: e4m3 codes plus a per-tensor scale on the+ fused qkv and the out projection, the two layers the converter handles differently."""+ import json++ from tests.fixtures.quantized_payloads import quantize_scaled_fp8++ torch.manual_seed(0)+ sd = _tiny_remote_code_state_dict()+ layers = {}+ for path in ("blocks.0.attn.qkv_proj", "blocks.0.attn.out_proj"):+ payload = quantize_scaled_fp8(sd[f"{path}.weight"])+ sd[f"{path}.weight"], sd[f"{path}.weight_scale"] = payload.codes, payload.scale.reshape(())+ layers[path] = {"format": "float8_e4m3fn"}+ metadata = {"_quantization_metadata": json.dumps({"format_version": "1.0", "layers": layers})}+ path = tmp_path / "minimax_h3_fp8_scaled.safetensors"+ save_file(sd, str(path), metadata=metadata if declared_in_header else None)+ return path+++def test_a_header_only_fp8_build_is_refused_before_the_tensor_read(tmp_path, monkeypatch) -> None:+ """The gate read per-tensor `.comfy_quant` markers and nothing else, but the producer tool decides+ the transport: FLUX.2's Comfy-Org fp8 build names every layer in `_quantization_metadata` and+ carries no marker at all. Such a file passed the gate, paid for the full tensor read, and died in+ the fused-qkv split on a per-tensor scale -- measured as a bare `IndexError: tuple index out of+ range`, which names neither fp8 nor the format. The header says what it is; read it there.+ """+ import safetensors.torch++ path = _write_fp8_checkpoint(tmp_path, declared_in_header=True)+ monkeypatch.setattr(+ safetensors.torch, "load_file", lambda _path: pytest.fail("the tensors were read for a file refused by name")+ )++ with pytest.raises(ValueError, match=r"float8_e4m3fn.*MiniMax H3 checkpoint"):+ _load(path)+++def test_an_undeclared_fp8_build_is_refused_by_name(tmp_path) -> None:+ """The older ComfyUI shape: fp8 weights and a `weight_scale` beside them, declared nowhere --+ neither marker nor header. Nothing can be refused before the read, but it can be before the+ converter, which is where it failed: the qkv split on the scale, or `load_state_dict` on the+ orphaned out-projection scale as an "unexpected key"."""+ path = _write_fp8_checkpoint(tmp_path, declared_in_header=False)++ with pytest.raises(ValueError, match=r"float8 weight"):+ _load(path)+++def test_the_text_encoder_reads_the_header_the_same_way(tmp_path, monkeypatch) -> None:+ """The encoder carried its own copy of the marker-only gate, so it had the same blind spot. Both+ now go through one helper; this pins that the encoder is wired to it *before* its tensor read.+ What the call buys is the ~25 GiB not spent: with it gone, a float8 file is still refused, by+ name, one step later by the dtype check. Only a declared format that is not float8 -- nvfp4,+ say -- would be misdiagnosed without it."""+ import json++ import safetensors.torch++ from invokeai.backend.model_manager.load.model_loaders.minimax_h3 import MiniMaxH3TextEncoderCheckpointModel++ layers = {"model.layers.0.mlp.down_proj": {"format": "float8_e4m3fn"}}+ path = tmp_path / "qwen3vl_32b_minimax_h3_fp8_scaled.safetensors"+ save_file(+ {"model.layers.0.mlp.down_proj.weight": torch.zeros(4, 4).to(torch.float8_e4m3fn)},+ str(path),+ metadata={"_quantization_metadata": json.dumps({"format_version": "1.0", "layers": layers})},+ )+ monkeypatch.setattr(+ safetensors.torch, "load_file", lambda _path: pytest.fail("the tensors were read for a file refused by name")+ )+ loader = object.__new__(MiniMaxH3TextEncoderCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()++ with pytest.raises(ValueError, match=r"float8_e4m3fn.*MiniMax H3 text encoder"):+ loader._load_text_encoder_from_singlefile(SimpleNamespace(path=str(path)))+++def _encoder_loader():+ from invokeai.backend.model_manager.load.model_loaders.minimax_h3 import MiniMaxH3TextEncoderCheckpointModel++ loader = object.__new__(MiniMaxH3TextEncoderCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ return loader+++def test_the_text_encoder_refuses_undeclared_fp8_after_the_read(tmp_path) -> None:+ """The encoder's dtype check, which the header cell above cannot see: this file declares nothing,+ so the gate lets it through and the refusal has to come from the tensors themselves."""+ path = tmp_path / "qwen3vl_32b_minimax_h3_fp8_scaled.safetensors"+ save_file(+ {+ "model.layers.0.mlp.down_proj.weight": torch.zeros(4, 4).to(torch.float8_e4m3fn),+ "model.layers.0.mlp.down_proj.weight_scale": torch.tensor(1.0),+ },+ str(path),+ )++ with pytest.raises(ValueError, match=r"MiniMax H3 text encoder .* float8 weight"):+ _encoder_loader()._load_text_encoder_from_singlefile(SimpleNamespace(path=str(path)))+++def test_a_raw_fp8_file_with_no_scale_is_refused_too(tmp_path) -> None:+ """The dtype check keys on the dtype, not on a scale key, and that is what this pins: a raw+ float8 file carries no side channel at all, and this loader assigns without casting, so it would+ load fp8 parameters that fail at the first matmul. e5m2 rather than e4m3fn, so a check narrowed+ to one float8 flavour would let it through."""+ torch.manual_seed(0)+ sd = _tiny_remote_code_state_dict()+ sd[QUANTIZED_SOURCE_KEY] = sd[QUANTIZED_SOURCE_KEY].to(torch.float8_e5m2)+ path = tmp_path / "minimax_h3_fp8_e5m2.safetensors"+ save_file(sd, str(path))++ with pytest.raises(ValueError, match=r"float8 weight"):+ _load(path)+++def test_an_int8_build_that_also_writes_the_header_still_loads(tmp_path) -> None:+ """The other half of reading the header. No published H3 int8 build writes+ `_quantization_metadata` today, so nothing else in the tree would notice a gate that refused one:+ an `int8_tensorwise` entry has to pass, and so does an entry carrying only a per-layer flag,+ which declares no scheme at all."""+ import json++ torch.manual_seed(0)+ sd = _tiny_remote_code_state_dict()+ quantized, scale, _restored = quantize_convrot(sd[QUANTIZED_SOURCE_KEY], group_size=GROUP_SIZE)+ sd[QUANTIZED_SOURCE_KEY] = quantized+ sd["blocks.0.attn.out_proj.weight_scale"] = scale+ sd["blocks.0.attn.out_proj.comfy_quant"] = comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP_SIZE}+ )+ layers = {+ "blocks.0.attn.out_proj": {"format": "int8_tensorwise"},+ "blocks.0.mlp.fc1": {"full_precision_matrix_mult": True},+ }+ path = tmp_path / "minimax_h3_int8_convrot_with_header.safetensors"+ save_file(+ sd, str(path), metadata={"_quantization_metadata": json.dumps({"format_version": "1.0", "layers": layers})}+ )++ model = _load(path)++ assert isinstance(_quantized_module(model), Int8ConvrotLinear)