Skip to content

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

feat(moss-image): load the Qwen3.5 encoder from Comfy-Org's int8 build (#10177)

Alexander Eichhornf51366092565
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
index ded5fc7133..8913cbadca 100644
--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx
@@ -69,8 +69,8 @@ Others are recognized by their layer names and fail, or misbehave, only when the
| Qwen3 0.6B / 4B / 8B | Z-Image (4B), FLUX.2 Klein (4B, 8B), Anima (0.6B) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Qwen3-VL 4B / 8B | Krea-2, FLUX.3, Ideogram 4, Qwen-Image-2.1 (8B) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ |
| Qwen3-VL 32B (truncated) | MiniMax H3 | in the Diffusers folder | ✓ | L | ✓ | L | ✗ | ✗ |
-| Qwen3.5 4B | Anima 3.8B | ✗ | ✓ | L | L | L | ✗ | ✗ |
-| Qwen3.5 9B | MOSS-Image | in the Diffusers folder | ✓ | L | L | L | ✗ | ✗ |
+| Qwen3.5 4B | Anima 3.8B | ✗ | ✓ | R | – | R | ✗ | ✗ |
+| Qwen3.5 9B | MOSS-Image | in the Diffusers folder | ✓ | R | ✓ | R | ✗ | ✗ |
| Qwen2.5-VL | Qwen-Image | ✓ | ✓ | ✓ | L | ✓ | ✗ | ✗ |
| Mistral Small 3 | FLUX.2 dev | ✓ | ✓ | ✓ | L | ✓ | ✓ | ✗ |
| Ministral 3B | ERNIE-Image | ✓ | ✓ | ✓ | L | L | R | ✗ |
@@ -108,6 +108,16 @@ the 4B and MOSS-Image only the 9B, and each refuses the other. A 9B file must ho
of a sharded export, the first shard is refused at install with a message and the others install as unknown
models. Install the whole MOSS-Image Diffusers folder or a merged single file instead.
+The Qwen3.5 9B encoder also installs in ComfyUI's `int8_convrot` build. It keeps its quantized layers in int8 and
+widens the embedding when it loads; the vision tower, LM head and multi-token-prediction head in the file are not read.
+The files in Comfy-Org's MOSS-Image repository (`text_encoders/`) have the same tensors as the FLUX.3 prompt
+upsampler, so nothing in the file tells the two apart; InvokeAI goes by where the file came from. Installing it from
+that repository by URL, or with the **Qwen3.5 9B Encoder (int8)** starter model, gives a Qwen3.5 encoder, and
+Reidentify repairs an older Text LLM record made from that URL. A local copy of the file installs as a
+[Text LLM](#text-llms), so use the starter or the URL. A model already installed as a Qwen3.5 encoder stays one when
+it is reidentified. w4a8, fp8 scaled, nvfp4 and mxfp8 builds are refused at install with a message. No int8 build
+of the 4B exists to test against.
+
## Text LLMs
Text LLMs rewrite prompts in [Expand Prompt](/users-guide/image-generation/prompt-tools/#expand-prompt) and run the
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
index d029ac19ec..9a1d8e2d6e 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
@@ -75,11 +75,15 @@ When a single-file MOSS-Image model is selected, the **Components** section next
- **Qwen3.5 Encoder**: a single-file Qwen3.5 9B encoder, such as the ComfyUI export
`moss-image-qwen35.safetensors`. A file that carries the vision tower as well loads; the vision tower stays
- on disk. The shards of a sharded export, such as the files in the pipeline's `text_encoder/` folder, do not
+ on disk. The bf16 files in Comfy-Org's MOSS-Image repository install as this encoder when installed from their URL. The shards of a sharded export, such as the files in the pipeline's `text_encoder/` folder, do not
work on their own: the first shard is refused at install with a message saying so, and the others install as
unknown models. The shards in `transformer/` install as unknown models too. Install the whole Diffusers
folder or a merged single file instead. Anima-3.8B uses the Qwen3.5 4B, which installs under the same encoder type. The two are
- not interchangeable, so the picker lists only 9B encoders.
+ not interchangeable, so the picker lists only 9B encoders. ComfyUI's int8 build of the encoder works as well:
+ install it with the **Qwen3.5 9B Encoder (int8)** starter model or from its Comfy-Org URL. A local copy of the file is
+ identified as a Text LLM, because nothing in it distinguishes it from the FLUX.3 prompt upsampler. On an RTX 4090 it
+ renders the same scene as the bf16 encoder with shifted details, and the file is about half the size. The w4a8
+ build is refused at install.
- **VAE**: a FLUX.2 VAE. MOSS-Image ships the FLUX.2 VAE with a smaller decoder (the ComfyUI export
`moss-image-vae.safetensors`); it installs under the FLUX.2 base. Any other FLUX.2 VAE works too, for
example the **FLUX.2 VAE** starter model.
diff --git a/invokeai/app/services/model_manager/model_manager_default.py b/invokeai/app/services/model_manager/model_manager_default.py
index 5e20e8e2ff..e8c362aaeb 100644
--- a/invokeai/app/services/model_manager/model_manager_default.py
+++ b/invokeai/app/services/model_manager/model_manager_default.py
@@ -23,6 +23,7 @@ from invokeai.app.services.model_records.model_records_base import (
ModelRecordServiceBase,
)
from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
+from invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Config
from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
@@ -84,6 +85,10 @@ class ModelManagerService(ModelManagerServiceBase):
override_fields = {"source": config.source, "source_type": config.source_type}
if encoder_id := getattr(config, "image_encoder_model_id", None):
override_fields["image_encoder_model_id"] = encoder_id
+ if isinstance(config, Qwen35Encoder_Checkpoint_Config):
+ # A Qwen3.5 encoder file can be the same tensors as a Text LLM (Comfy-Org's int8 MOSS-Image encoder against
+ # the FLUX.3 upsampler), and a local copy has no source to tell them apart: keep the type it was given.
+ override_fields["type"] = config.type
result = ModelConfigFactory.from_model_on_disk(mod, override_fields)
if result.config is None:
raise InvalidModelException("Unable to identify model format")
diff --git a/invokeai/backend/model_manager/configs/qwen3_5_encoder.py b/invokeai/backend/model_manager/configs/qwen3_5_encoder.py
index 2eb3fb3b01..e8d78e89f7 100644
--- a/invokeai/backend/model_manager/configs/qwen3_5_encoder.py
+++ b/invokeai/backend/model_manager/configs/qwen3_5_encoder.py
@@ -7,9 +7,11 @@ are what tell them apart, and the Qwen3 and Qwen3-VL configs reject them for the
one requires them.
"""
+import re
from collections.abc import Container
from typing import Any, Literal, Optional, Self
+import torch
from pydantic import Field
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Base
@@ -21,7 +23,9 @@ from invokeai.backend.model_manager.configs.identification_utils import (
)
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, Qwen35VariantType
+from invokeai.backend.quantization.fp8_scaled import FP8_WEIGHT_DTYPES, WEIGHT_SCALE_SUFFIXES, is_scale_metadata_key
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT, read_comfy_quant_markers
from invokeai.backend.qwen3_5.qwen3_5_vl import QWEN3_5_VL_LANGUAGE_MODEL_PREFIX, QWEN3_5_VL_VARIANTS
#: Where a Qwen3.5 language model's `layers.` and `embed_tokens.` sit: bare (ComfyUI text-encoder
@@ -40,6 +44,30 @@ QWEN3_5_FINAL_NORM_VARIANTS = frozenset({Qwen35VariantType.Qwen35_9B})
#: The first block of a `Qwen3_5ForConditionalGeneration` vision tower, under transformers' names.
_QWEN3_5_VISION_TOWER_KEY = "model.visual.blocks.0.attn.qkv.weight"
+# ComfyUI's w4a8 build of the FLUX.3 prompt upsampler (`asym_w4a8_int8`): packed 4-bit codes beside a codebook and
+# per-channel and per-group scales, which no loader here decodes.
+_W4A8_SUFFIXES = (".weight_codebook", ".weight_s_channel", ".weight_s_rel")
+
+# mxfp8's per-block scale: one E8M0 exponent per 32 weights, stored as bytes or as the float8 exponent type.
+_MXFP8_SCALE_DTYPES = tuple(
+ dtype for dtype in (torch.uint8, getattr(torch, "float8_e8m0fnu", None)) if dtype is not None
+)
+
+
+#: Where Comfy-Org publishes MOSS-Image's Qwen3.5 encoders: a `resolve`/`blob` URL of its `text_encoders/` folder at any
+#: revision, or the same file as a Hugging Face `repo_id[:variant]::subfolder` source. These files carry the vision
+#: tower, `lm_head.weight` and `mtp.*` -- the key set of the FLUX.3 prompt upsampler -- so only where they came from
+#: tells the two apart.
+_MOSS_IMAGE_ENCODER_SOURCE = re.compile(
+ r"^(?:https?://[^/]+/Comfy-Org/MOSS-Image/(?:resolve|blob)/[^/?#]+/|Comfy-Org/MOSS-Image(?::[^:/]*)?::)"
+ r"text_encoders/[^/?#]+\.safetensors(?:[?#].*)?$"
+)
+
+
+def is_moss_image_encoder_source(source: Any) -> bool:
+ """Whether an install source is one of Comfy-Org's MOSS-Image text encoder files (a Qwen3.5 encoder, never a Text LLM)."""
+ return isinstance(source, str) and _MOSS_IMAGE_ENCODER_SOURCE.match(source) is not None
+
def has_qwen3_5_linear_attention(state_dict: dict[str | int, Any]) -> bool:
"""True if the state dict holds Gated DeltaNet (`linear_attn`) layers -- Qwen3.5, never Qwen3."""
@@ -70,9 +98,10 @@ def is_qwen3_5_vision_language_lm(state_dict: dict[str | int, Any]) -> bool:
"""Whether this is a whole `Qwen3_5ForConditionalGeneration` that loads as a Text LLM.
Language model, vision tower and LM head under transformers' names, at a size with a vendored config: the
- FLUX.3 prompt upsampler's single files, which are `TextLLM_Checkpoint_Config`'s. The LM head sets them apart
- from an encoder export of the same model -- MOSS-Image's has the vision tower without one. Anything else stays
- the encoder config's, LM head or not: a 4B with its tower, which Anima-3.8B can read, or a text-only export.
+ FLUX.3 prompt upsampler's single files, which are `TextLLM_Checkpoint_Config`'s. The weights alone cannot tell
+ them from Comfy-Org's MOSS-Image encoders, which carry the same tensors (tower, `lm_head`, `mtp.*`);
+ `is_moss_image_encoder_source` does that, by where the file came from. Anything else stays the encoder config's,
+ LM head or not: a 4B with its tower, which Anima-3.8B can read, or a text-only export.
"""
return (
qwen3_5_key_prefix(state_dict) == QWEN3_5_VL_LANGUAGE_MODEL_PREFIX
@@ -111,6 +140,54 @@ def _raise_if_not_whole(state_dict: dict[str | int, Any], prefix: str, variant:
)
+def raise_for_unsupported_qwen3_5_quantization(mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:
+ """Refuse every quantized Qwen3.5 build but ComfyUI's int8_tensorwise: with bf16, all the loaders can build.
+
+ `InvalidMatchError`: the file is this model, so the installer shows the reason instead of registering a model
+ nothing loads. Anima-3.8B's raw fp8 projections carry no scale and pass on purpose: the encoder loader casts them
+ exactly. An int8 layer counts when its weight is int8 and its marker -- read from the file, since
+ identification sees dtypes and shapes but no bytes -- says int8_tensorwise; any other scale or marker is a scheme
+ the loader refuses.
+ """
+ keys = [key for key in state_dict if isinstance(key, str)]
+ int8_layers = {
+ key.removesuffix(".weight")
+ for key in keys
+ if key.endswith(".weight") and getattr(state_dict[key], "dtype", None) is torch.int8
+ }
+ scheme = _foreign_quantization(state_dict, keys, int8_layers)
+ if scheme is None and int8_layers:
+ markers = read_comfy_quant_markers(mod.path)
+ unmarked = sorted(
+ layer for layer in int8_layers if markers.get(layer, {}).get("format") != INT8_TENSORWISE_FORMAT
+ )
+ if unmarked:
+ scheme = f"int8 without an {INT8_TENSORWISE_FORMAT} marker (e.g. '{unmarked[0]}')"
+ if scheme is not None:
+ raise InvalidMatchError(
+ f"{mod.path.name} is quantized as {scheme}, which InvokeAI cannot load for this model. "
+ "Install the bf16 or int8_convrot build instead."
+ )
+
+
+def _foreign_quantization(state_dict: dict[str | int, Any], keys: list[str], int8_layers: set[str]) -> str | None:
+ """Name a quantization side channel that belongs to no int8 layer, or None if there is none."""
+ if any(key.endswith(_W4A8_SUFFIXES) for key in keys):
+ return "ComfyUI's w4a8 (asym_w4a8_int8)"
+ if any(key.endswith(".weight_scale_2") for key in keys):
+ return "nvfp4"
+ for key in keys:
+ layer = key.rsplit(".", 1)[0]
+ if not is_scale_metadata_key(key) or layer in int8_layers:
+ continue
+ if key.endswith(WEIGHT_SCALE_SUFFIXES) and getattr(state_dict.get(f"{layer}.weight"), "dtype", None) in (
+ FP8_WEIGHT_DTYPES
+ ):
+ return "mxfp8" if getattr(state_dict[key], "dtype", None) in _MXFP8_SCALE_DTYPES else "scaled fp8"
+ return "scaled fp8" if key == "scaled_fp8" else f"an unsupported scheme (it carries '{key}')"
+ return None
+
+
class Qwen35Encoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):
"""Configuration for single-file Qwen3.5 text encoders (safetensors)."""
@@ -130,11 +207,17 @@ class Qwen35Encoder_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):
prefix = qwen3_5_key_prefix(state_dict)
if prefix is None:
raise NotAMatchError("state dict does not look like a Qwen3.5 language model (no linear_attn layer 0)")
- # The FLUX.3 prompt upsampler is a TextLLM. An explicit type still installs it here.
- if override_fields.get("type") != ModelType.Qwen35Encoder and is_qwen3_5_vision_language_lm(state_dict):
+ # The FLUX.3 prompt upsampler is a TextLLM. An explicit type, or Comfy-Org's MOSS-Image encoder source, still
+ # installs a file of its layout here.
+ if (
+ override_fields.get("type") != ModelType.Qwen35Encoder
+ and not is_moss_image_encoder_source(override_fields.get("source"))
+ and is_qwen3_5_vision_language_lm(state_dict)
+ ):
raise NotAMatchError("state dict is a whole Qwen3.5 vision-language model with an LM head: a TextLLM")
if any(isinstance(v, GGMLTensor) for v in state_dict.values()):
raise NotAMatchError("state dict looks like GGUF quantized")
+ raise_for_unsupported_qwen3_5_quantization(mod, state_dict)
variant = override_fields.pop("variant", None) or get_qwen3_5_variant(state_dict, prefix)
if variant is None:
diff --git a/invokeai/backend/model_manager/configs/text_llm.py b/invokeai/backend/model_manager/configs/text_llm.py
index c6cf1a6b4c..edf3a94384 100644
--- a/invokeai/backend/model_manager/configs/text_llm.py
+++ b/invokeai/backend/model_manager/configs/text_llm.py
@@ -3,14 +3,12 @@ from typing import (
Self,
)
-import torch
from pydantic import Field
from typing_extensions import Any
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Config_Base, Diffusers_Config_Base
from invokeai.backend.model_manager.configs.gemma4_encoder import is_ltx2_gemma4_encoder_folder
from invokeai.backend.model_manager.configs.identification_utils import (
- InvalidMatchError,
NotAMatchError,
common_config_paths,
get_class_name_from_config_dict_or_raise,
@@ -19,15 +17,17 @@ from invokeai.backend.model_manager.configs.identification_utils import (
raise_if_not_dir,
raise_if_not_file,
)
-from invokeai.backend.model_manager.configs.qwen3_5_encoder import is_qwen3_5_vision_language_lm
+from invokeai.backend.model_manager.configs.qwen3_5_encoder import (
+ is_moss_image_encoder_source,
+ is_qwen3_5_vision_language_lm,
+ raise_for_unsupported_qwen3_5_quantization,
+)
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
ModelFormat,
ModelType,
)
-from invokeai.backend.quantization.fp8_scaled import FP8_WEIGHT_DTYPES, WEIGHT_SCALE_SUFFIXES, is_scale_metadata_key
-from invokeai.backend.quantization.int8_convrot import INT8_TENSORWISE_FORMAT, read_comfy_quant_markers
# Gemma-2-2b's hidden size. Only this size is handled by the dedicated PiD Gemma2 encoder config; larger
# Gemma 2 variants (9B=3584, 27B=4608) are rejected there and must stay classifiable as a generic TextLLM.
@@ -48,15 +48,6 @@ _SUPPORTS_IMAGES_DESCRIPTION = (
"Whether the model has a vision tower and processor, so Expand Prompt can condition on an image"
)
-# ComfyUI's w4a8 build of the FLUX.3 prompt upsampler (`asym_w4a8_int8`): packed 4-bit codes beside a codebook and
-# per-channel and per-group scales, which no loader here decodes.
-_W4A8_SUFFIXES = (".weight_codebook", ".weight_s_channel", ".weight_s_rel")
-
-# mxfp8's per-block scale: one E8M0 exponent per 32 weights, stored as bytes or as the float8 exponent type.
-_MXFP8_SCALE_DTYPES = tuple(
- dtype for dtype in (torch.uint8, getattr(torch, "float8_e8m0fnu", None)) if dtype is not None
-)
-
class TextLLM_Diffusers_Config(Diffusers_Config_Base, Config_Base):
"""Model config for a language model folder: a causal LM (Llama, Phi, Qwen, Mistral, ...) or an allow-listed
@@ -127,8 +118,8 @@ class TextLLM_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):
The layout is transformers' own `Qwen3_5ForConditionalGeneration` state dict, as ComfyUI exports the FLUX.3
prompt upsampler (bf16, or `int8_tensorwise` with a multi-token-prediction head the loader drops). The file
carries weights only; the loader supplies config, tokenizer and processor from the vendored Qwen3.5 assets,
- which exist for the 9B. Its LM head sets it apart from the Qwen3.5 text-encoder exports, which have none and
- are `Qwen35Encoder_Checkpoint_Config`'s.
+ which exist for the 9B. Comfy-Org's MOSS-Image encoders have the same tensors and are
+ `Qwen35Encoder_Checkpoint_Config`'s; they are told apart by their install source.
"""
type: Literal[ModelType.TextLLM] = Field(default=ModelType.TextLLM)
@@ -146,58 +137,16 @@ class TextLLM_Checkpoint_Config(Checkpoint_Config_Base, Config_Base):
raise_for_override_fields(cls, override_fields)
+ if override_fields.get("type") != ModelType.TextLLM and is_moss_image_encoder_source(
+ override_fields.get("source")
+ ):
+ raise NotAMatchError("Comfy-Org's MOSS-Image text encoders are Qwen3.5 encoders, not Text LLMs")
+
state_dict = mod.load_state_dict()
if not is_qwen3_5_vision_language_lm(state_dict):
raise NotAMatchError(
"state dict is not a whole Qwen3.5 vision-language model (model.language_model.*, model.visual.*, "
"lm_head) of a size with a vendored config"
)
- _raise_for_unsupported_quantization(mod, state_dict)
+ raise_for_unsupported_qwen3_5_quantization(mod, state_dict)
return cls(**override_fields)
-
-
-def _raise_for_unsupported_quantization(mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:
- """Refuse every quantized build but ComfyUI's int8_tensorwise: with bf16, all the loader can build.
-
- `InvalidMatchError`: the file is this model, so the installer shows the reason instead of registering a model
- nothing loads. An int8 layer counts when its weight is int8 and its marker -- read from the file, since
- identification sees dtypes and shapes but no bytes -- says int8_tensorwise; any other scale or marker is a scheme
- the loader refuses.
- """
- keys = [key for key in state_dict if isinstance(key, str)]
- int8_layers = {
- key.removesuffix(".weight")
- for key in keys
- if key.endswith(".weight") and getattr(state_dict[key], "dtype", None) is torch.int8
- }
- scheme = _foreign_quantization(state_dict, keys, int8_layers)
- if scheme is None and int8_layers:
- markers = read_comfy_quant_markers(mod.path)
- unmarked = sorted(
- layer for layer in int8_layers if markers.get(layer, {}).get("format") != INT8_TENSORWISE_FORMAT
- )
- if unmarked:
- scheme = f"int8 without an {INT8_TENSORWISE_FORMAT} marker (e.g. '{unmarked[0]}')"
- if scheme is not None:
- raise InvalidMatchError(
- f"{mod.path.name} is quantized as {scheme}, which InvokeAI cannot load for this model. "
- "Install the bf16 or int8_convrot build instead."
- )
-
-
-def _foreign_quantization(state_dict: dict[str | int, Any], keys: list[str], int8_layers: set[str]) -> str | None:
- """Name a quantization side channel that belongs to no int8 layer, or None if there is none."""
- if any(key.endswith(_W4A8_SUFFIXES) for key in keys):
- return "ComfyUI's w4a8 (asym_w4a8_int8)"
- if any(key.endswith(".weight_scale_2") for key in keys):
- return "nvfp4"
- for key in keys:
- layer = key.rsplit(".", 1)[0]
- if not is_scale_metadata_key(key) or layer in int8_layers:
- continue
- if key.endswith(WEIGHT_SCALE_SUFFIXES) and getattr(state_dict.get(f"{layer}.weight"), "dtype", None) in (
- FP8_WEIGHT_DTYPES
- ):
- return "mxfp8" if getattr(state_dict[key], "dtype", None) in _MXFP8_SCALE_DTYPES else "scaled fp8"
- return "scaled fp8" if key == "scaled_fp8" else f"an unsupported scheme (it carries '{key}')"
- return None
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
index 215118b131..e7b43b20aa 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py
@@ -23,6 +23,12 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader, _model
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel
+from invokeai.backend.quantization.int8_convrot import (
+ drop_unconsumed_quantization_sidecars,
+ extract_int8_convrot_markers,
+ install_int8_convrot_layers,
+ reject_unmarked_int8_weights,
+)
from invokeai.backend.quantization.load_plan import reserve_for_load
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.state_dict_loading import log_unexpected_keys, reject_incomplete_load
@@ -68,7 +74,9 @@ def load_qwen3_5_text_encoder(
) -> "Qwen35Encoder":
"""Build a `Qwen35Encoder` from the language-model tensors of a safetensors file or of a model's shards.
- Nothing else is read, so a multimodal export's vision tower never reaches RAM.
+ Nothing else is read, so a multimodal export's vision tower, an LM head and a multi-token-prediction
+ head never reach RAM. A ComfyUI `int8_tensorwise` build keeps its marked Linears int8, dequantizing
+ per forward; the embedding, which is not a Linear, is widened on load.
Args:
loader: The calling loader; the load reserves room in its RAM cache.
@@ -90,10 +98,6 @@ def load_qwen3_5_text_encoder(
with safe_open(path, framework="pt", device="cpu") as f:
keys_by_file[path] = list(f.keys())
all_keys = dict.fromkeys(key for keys in keys_by_file.values() for key in keys)
- # Anima-3.8B's encoder ships raw fp8 projections (no scale), which the cast below handles
- # exactly. A scaled, int8 or nvfp4 build would load *wrong* here rather than fail, so refuse it
- # until one exists to support.
- reject_quantized_side_channel(all_keys, what)
prefix = qwen3_5_key_prefix(all_keys)
if prefix is None:
raise ValueError(f"{what} is not a Qwen3.5 language model checkpoint.")
@@ -122,17 +126,40 @@ def load_qwen3_5_text_encoder(
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
skip_patterns = _model_declared_skip_patterns(model)
- reserve_for_load(
- loader.ram_cache.make_room,
- sd,
- model_dtype,
- keep_fp8=keep_fp8,
- model=model,
- skip_patterns=skip_patterns,
- fp8_layers={},
- nvfp4_payloads={},
- )
- kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ markers = extract_int8_convrot_markers(sd)
+ # Outside the int8 branch, so an int8 weight whose marker is missing is refused, not cast as codes.
+ reject_unmarked_int8_weights(sd, markers, "Qwen3.5", model)
+ kept = 0
+ if markers:
+ sd = drop_unconsumed_quantization_sidecars(sd)
+ int8_layers = install_int8_convrot_layers(
+ model,
+ sd,
+ markers,
+ model_dtype,
+ architecture="Qwen3.5",
+ reserve=loader.ram_cache.make_room,
+ skip_patterns=skip_patterns,
+ )
+ loader._logger.info(
+ f"{what}: kept {len(int8_layers)} of {len(markers)} layer(s) in int8 (int8_tensorwise checkpoint, "
+ "dequantized per forward); the embedding is widened on load."
+ )
+ else:
+ # Anima-3.8B's encoder ships raw fp8 projections (no scale), which the cast below handles
+ # exactly. A scaled or nvfp4 build would load *wrong* here rather than fail, so refuse it.
+ reject_quantized_side_channel(sd, what)
+ reserve_for_load(
+ loader.ram_cache.make_room,
+ sd,
+ model_dtype,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ fp8_layers={},
+ nvfp4_payloads={},
+ )
+ kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
result = model.load_state_dict(sd, strict=False, assign=True)
log_unexpected_keys(what, result.unexpected_keys)
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 5989306602..a224537987 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -226,6 +226,7 @@ from invokeai.backend.model_manager.starter_models.minimax_h3 import (
from invokeai.backend.model_manager.starter_models.moss_image import (
moss_image_base,
moss_image_prompt_enhancer,
+ moss_image_qwen3_5_encoder_int8,
moss_image_sft,
)
from invokeai.backend.model_manager.starter_models.qwen_image import (
@@ -568,6 +569,7 @@ STARTER_MODELS: list[StarterModel] = [
moss_image_base,
moss_image_sft,
moss_image_prompt_enhancer,
+ moss_image_qwen3_5_encoder_int8,
wan_22_t5_encoder,
wan_22_a14b_vae,
wan_22_5b_vae,
diff --git a/invokeai/backend/model_manager/starter_models/moss_image.py b/invokeai/backend/model_manager/starter_models/moss_image.py
index e654f407bc..03742f9280 100644
--- a/invokeai/backend/model_manager/starter_models/moss_image.py
+++ b/invokeai/backend/model_manager/starter_models/moss_image.py
@@ -1,7 +1,7 @@
"""MOSS-Image starter models."""
from invokeai.backend.model_manager.starter_models.types import StarterModel
-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, Qwen35VariantType
# Both are complete diffusers pipelines. Their text encoder and VAE are byte-identical, but each install keeps its own
# copy, so the descriptions say what installing both costs.
@@ -45,3 +45,22 @@ moss_image_prompt_enhancer = StarterModel(
),
type=ModelType.TextLLM,
)
+
+# The file has the key set of the FLUX.3 prompt upsampler (a Text LLM), so only its source tells identification what it
+# is (`is_moss_image_encoder_source`); the starter names the type as well. Pinned to the Comfy repository commit the
+# int8 layout was checked against: the file's `comfy_quant` markers drive the decode, so a re-upload at the same path
+# could change how it loads, and the pinned URL still matches the source check.
+moss_image_qwen3_5_encoder_int8 = StarterModel(
+ name="Qwen3.5 9B Encoder (int8)",
+ base=BaseModelType.Any,
+ source="https://huggingface.co/Comfy-Org/MOSS-Image/resolve/"
+ "2929efe3cdd506c0a430bcfca70a9a8d805cc095/text_encoders/qwen3.5_9b_int8_convrot.safetensors",
+ description=(
+ "ComfyUI's int8 build of the Qwen3.5-9B text encoder that MOSS-Image reads, about half the size of the bf16 "
+ "encoder. Select it as the Qwen3.5 encoder of a MOSS-Image model. The file also holds a vision tower and an LM "
+ "head, which are not loaded. Apache-2.0. ~9.8GB"
+ ),
+ type=ModelType.Qwen35Encoder,
+ format=ModelFormat.Checkpoint,
+ variant=Qwen35VariantType.Qwen35_9B,
+)
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index ba39225a43..d3236f23f2 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -114683,7 +114683,7 @@
"supports_images"
],
"title": "TextLLM_Checkpoint_Config",
- "description": "Model config for a single-file Qwen3.5 vision-language model, run as a text LLM.\n\nThe layout is transformers' own `Qwen3_5ForConditionalGeneration` state dict, as ComfyUI exports the FLUX.3\nprompt upsampler (bf16, or `int8_tensorwise` with a multi-token-prediction head the loader drops). The file\ncarries weights only; the loader supplies config, tokenizer and processor from the vendored Qwen3.5 assets,\nwhich exist for the 9B. Its LM head sets it apart from the Qwen3.5 text-encoder exports, which have none and\nare `Qwen35Encoder_Checkpoint_Config`'s."
+ "description": "Model config for a single-file Qwen3.5 vision-language model, run as a text LLM.\n\nThe layout is transformers' own `Qwen3_5ForConditionalGeneration` state dict, as ComfyUI exports the FLUX.3\nprompt upsampler (bf16, or `int8_tensorwise` with a multi-token-prediction head the loader drops). The file\ncarries weights only; the loader supplies config, tokenizer and processor from the vendored Qwen3.5 assets,\nwhich exist for the 9B. Comfy-Org's MOSS-Image encoders have the same tensors and are\n`Qwen35Encoder_Checkpoint_Config`'s; they are told apart by their install source."
},
"TextLLM_Diffusers_Config": {
"properties": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 6f6d93f1e5..1721848dfd 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -50611,8 +50611,8 @@ export type components = {
* The layout is transformers' own `Qwen3_5ForConditionalGeneration` state dict, as ComfyUI exports the FLUX.3
* prompt upsampler (bf16, or `int8_tensorwise` with a multi-token-prediction head the loader drops). The file
* carries weights only; the loader supplies config, tokenizer and processor from the vendored Qwen3.5 assets,
- * which exist for the 9B. Its LM head sets it apart from the Qwen3.5 text-encoder exports, which have none and
- * are `Qwen35Encoder_Checkpoint_Config`'s.
+ * which exist for the 9B. Comfy-Org's MOSS-Image encoders have the same tensors and are
+ * `Qwen35Encoder_Checkpoint_Config`'s; they are told apart by their install source.
*/
TextLLM_Checkpoint_Config: {
/**
diff --git a/tests/app/services/model_manager/test_model_record_changes.py b/tests/app/services/model_manager/test_model_record_changes.py
index 6a086a44da..206555aa56 100644
--- a/tests/app/services/model_manager/test_model_record_changes.py
+++ b/tests/app/services/model_manager/test_model_record_changes.py
@@ -29,7 +29,9 @@ from invokeai.backend.model_manager.configs.default_settings import MainModelDef
from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
from invokeai.backend.model_manager.configs.ip_adapter import IPAdapter_InvokeAI_SD1_Config
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config, Main_Checkpoint_SDXL_Config
+from invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Config
from invokeai.backend.model_manager.configs.spandrel import Spandrel_Checkpoint_Config
+from invokeai.backend.model_manager.configs.text_llm import TextLLM_Checkpoint_Config
from invokeai.backend.model_manager.load import LoadedModel, ModelCache, ModelLoader
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.model_manager.starter_models import STARTER_MODELS, StarterModel
@@ -39,11 +41,16 @@ from invokeai.backend.model_manager.taxonomy import (
ModelSourceType,
ModelType,
ModelVariantType,
+ Qwen35VariantType,
SubModelType,
)
from invokeai.backend.tiny_autoencoder.checkpoint import TaesdLayout
from invokeai.backend.util.logging import InvokeAILogger
-from tests.backend.model_manager.load.state_dicts import clip_g_comfy_keys, clip_l_comfy_keys
+from tests.backend.model_manager.load.state_dicts import (
+ clip_g_comfy_keys,
+ clip_l_comfy_keys,
+ flux3_pup_int8_convrot_keys,
+)
from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors
from tests.fixtures.spandrel_models import write_compact_upscaler
from tests.fixtures.sqlite_database import create_mock_sqlite_database
@@ -385,6 +392,50 @@ def test_reidentify_keeps_a_cpu_only_choice_held_on_the_config_itself(harness: _
assert updated.cpu_only is cpu_only
+_COMFY_MOSS_INT8_URL = (
+ "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/text_encoders/qwen3.5_9b_int8_convrot.safetensors"
+)
+
+
+def _write_moss_int8_encoder(path: Path) -> Path:
+ """Comfy-Org's int8 MOSS-Image encoder: the key set of the FLUX.3 prompt upsampler, a Text LLM by its weights."""
+ return write_header_only_safetensors(
+ path, flux3_pup_int8_convrot_keys.state_dict_keys, flux3_pup_int8_convrot_keys.markers
+ )
+
+
+def test_reidentify_keeps_a_local_qwen3_5_encoder_an_encoder(harness: _Harness) -> None:
+ """A local copy has no source to tell the encoder from the upsampler, so the type it was installed with stays."""
+ path = _write_moss_int8_encoder(harness.models_path / "encoder.safetensors")
+ installed = _identify(
+ path,
+ {"type": ModelType.Qwen35Encoder, "variant": Qwen35VariantType.Qwen35_9B},
+ key=KEY,
+ path="encoder.safetensors",
+ name="Qwen3.5 9B (int8)",
+ )
+ assert isinstance(installed, Qwen35Encoder_Checkpoint_Config)
+ harness.store.add_model(installed)
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, Qwen35Encoder_Checkpoint_Config)
+ assert updated.variant is Qwen35VariantType.Qwen35_9B
+
+
+def test_reidentify_repairs_a_text_llm_record_installed_from_comfy_orgs_encoder_url(harness: _Harness) -> None:
+ path = _write_moss_int8_encoder(harness.models_path / "encoder.safetensors")
+ installed = _identify(path, key=KEY, path="encoder.safetensors", name="encoder")
+ assert isinstance(installed, TextLLM_Checkpoint_Config)
+ installed.source, installed.source_type = _COMFY_MOSS_INT8_URL, ModelSourceType.Url
+ harness.store.add_model(installed)
+
+ updated = harness.manager.reidentify_model(KEY)
+
+ assert isinstance(updated, Qwen35Encoder_Checkpoint_Config)
+ assert updated.source == _COMFY_MOSS_INT8_URL
+
+
def test_reidentify_keeps_an_ip_adapter_encoder_override_its_files_leave_blank(harness: _Harness) -> None:
model_path = harness.models_path / "ip-adapter"
model_path.mkdir()
diff --git a/tests/backend/model_manager/configs/test_text_llm_qwen3_5_config.py b/tests/backend/model_manager/configs/test_text_llm_qwen3_5_config.py
index f6dae9760b..a891a3aef2 100644
--- a/tests/backend/model_manager/configs/test_text_llm_qwen3_5_config.py
+++ b/tests/backend/model_manager/configs/test_text_llm_qwen3_5_config.py
@@ -19,7 +19,8 @@ from invokeai.backend.model_manager.configs.identification_utils import InvalidM
from invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Config
from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_Checkpoint_Config
from invokeai.backend.model_manager.configs.text_llm import TextLLM_Checkpoint_Config, TextLLM_Diffusers_Config
-from invokeai.backend.model_manager.taxonomy import ModelFormat, ModelType, Qwen35VariantType
+from invokeai.backend.model_manager.starter_models import STARTER_MODELS
+from invokeai.backend.model_manager.taxonomy import ModelFormat, ModelSourceType, ModelType, Qwen35VariantType
from tests.backend.model_manager.load.state_dicts import (
flux3_pup_bf16_keys,
flux3_pup_int8_convrot_keys,
@@ -182,3 +183,120 @@ class TestTheLineBetweenTheUpsamplerAndAQwen3_5Encoder:
result = _identify(write_header_only_safetensors(path, qwen3_vl_4b_comfy_keys.state_dict_keys))
assert _matches(result) == [Qwen3VLEncoder_Checkpoint_Config.__name__]
+
+
+class TestQuantizedQwen3_5Encoders:
+ """ComfyUI's int8 build of the Qwen3.5-9B text encoder has the key set of the FLUX.3 upsampler's, so only an explicit
+ type (the starter model's) tells the two apart; the quantization schemes the encoder loader cannot build are refused
+ at install, as the Text LLM config refuses them."""
+
+ @staticmethod
+ def _starter_fields() -> dict[str, Any]:
+ """What the install dialog sends for the starter model, from the starter as registered."""
+ starter = next(m for m in STARTER_MODELS if m.name == "Qwen3.5 9B Encoder (int8)")
+ return {
+ "base": starter.base,
+ "description": starter.description,
+ "name": starter.name,
+ "type": starter.type,
+ "format": starter.format,
+ "variant": starter.variant,
+ "source": starter.source,
+ "source_type": ModelSourceType.Url,
+ }
+
+ def _int8_file(self, tmp_path: Path) -> Path:
+ return write_header_only_safetensors(
+ tmp_path / "qwen3.5_9b_int8_convrot.safetensors", _INT8, flux3_pup_int8_convrot_keys.markers
+ )
+
+ def test_the_starter_installs_the_int8_build_as_a_9b_encoder(self, tmp_path: Path) -> None:
+ result = _identify(self._int8_file(tmp_path), self._starter_fields())
+
+ assert _matches(result) == [Qwen35Encoder_Checkpoint_Config.__name__]
+ assert isinstance(result.config, Qwen35Encoder_Checkpoint_Config)
+ assert result.config.variant is Qwen35VariantType.Qwen35_9B
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/text_encoders/qwen3.5_9b_int8_convrot.safetensors",
+ "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/2929efe3/text_encoders/qwen3.5_9b_bf16.safetensors?download=true",
+ "Comfy-Org/MOSS-Image::text_encoders/qwen3.5_9b_int8_convrot.safetensors",
+ ],
+ ids=["main", "pinned bf16", "repo id"],
+ )
+ def test_comfy_orgs_source_alone_makes_its_file_an_encoder_and_never_a_text_llm(
+ self, tmp_path: Path, source: str
+ ) -> None:
+ result = _identify(self._int8_file(tmp_path), {"source": source, "source_type": ModelSourceType.Url})
+
+ assert _matches(result) == [Qwen35Encoder_Checkpoint_Config.__name__]
+
+ @pytest.mark.parametrize(
+ ("source", "source_type"),
+ [
+ # A local copy and another repository's identical file carry no such evidence.
+ ("D:/models/Comfy-Org/MOSS-Image/text_encoders/qwen3.5_9b_int8_convrot.safetensors", ModelSourceType.Path),
+ (
+ "https://huggingface.co/black-forest-labs/flux-3-image-klein-comfy/resolve/main/text_encoders/"
+ "qwen3.5_9b_flux3_prompt_upsampler_int8_convrot.safetensors",
+ ModelSourceType.Url,
+ ),
+ (
+ "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/diffusion_models/moss.safetensors",
+ ModelSourceType.Url,
+ ),
+ ],
+ ids=["local path", "flux3 upsampler", "other folder of the repo"],
+ )
+ def test_any_other_source_leaves_the_file_a_text_llm(
+ self, tmp_path: Path, source: str, source_type: ModelSourceType
+ ) -> None:
+ result = _identify(self._int8_file(tmp_path), {"source": source, "source_type": source_type})
+
+ assert _matches(result) == [TextLLM_Checkpoint_Config.__name__]
+
+ def test_the_int8_build_without_an_lm_head_is_an_encoder_unprompted(self, tmp_path: Path) -> None:
+ keys = {key: value for key, value in _INT8.items() if not key.startswith("lm_head.")}
+ markers = {path: marker for path, marker in flux3_pup_int8_convrot_keys.markers.items() if path != "lm_head"}
+
+ result = _identify(write_header_only_safetensors(tmp_path / "encoder.safetensors", keys, markers))
+
+ assert _matches(result) == [Qwen35Encoder_Checkpoint_Config.__name__]
+
+ @pytest.mark.parametrize(
+ ("keys", "scheme"),
+ [
+ (flux3_pup_w4a8_keys.state_dict_keys, "asym_w4a8_int8"),
+ (_with_layer(_BF16, weight=([12288, 4096], "F8_E4M3"), weight_scale=([], "F32")), "scaled fp8"),
+ (
+ _with_layer(
+ _BF16,
+ weight=([12288, 2048], "U8"),
+ weight_scale=([12288, 256], "F8_E4M3"),
+ weight_scale_2=([], "F32"),
+ input_scale=([], "F32"),
+ ),
+ "nvfp4",
+ ),
+ (
+ {key: value for key, value in _INT8.items() if not key.endswith(".comfy_quant")},
+ "int8 without an int8_tensorwise marker",
+ ),
+ ],
+ ids=["w4a8", "scaled fp8", "nvfp4", "unmarked int8"],
+ )
+ def test_a_build_the_loader_cannot_decode_is_refused_naming_its_scheme(
+ self, tmp_path: Path, keys: Keys, scheme: str
+ ) -> None:
+ result = ModelConfigFactory.from_model_on_disk(
+ write_header_only_safetensors(tmp_path / "encoder.safetensors", keys),
+ self._starter_fields(),
+ allow_unknown=True,
+ )
+
+ assert result.config is None
+ refusal = result.details[Qwen35Encoder_Checkpoint_Config.__name__]
+ assert isinstance(refusal, InvalidMatchError)
+ assert scheme in str(refusal)
diff --git a/tests/backend/qwen3_5/test_qwen3_5_loading.py b/tests/backend/qwen3_5/test_qwen3_5_loading.py
index fcd3c3cc1a..2ae0901f01 100644
--- a/tests/backend/qwen3_5/test_qwen3_5_loading.py
+++ b/tests/backend/qwen3_5/test_qwen3_5_loading.py
@@ -23,7 +23,9 @@ from invokeai.backend.model_manager.load.model_loaders.qwen3_5_encoder import (
load_qwen3_5_text_encoder,
)
from invokeai.backend.model_manager.taxonomy import Qwen35VariantType, SubModelType
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.qwen3_5.qwen3_5_encoder import Qwen35Encoder, qwen3_5_text_config_from_config_json
+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrot
_LAST = 3
_PROJECTION_HEAD = {"norm.0.weight": [8, 32], "norm.0.bias": [8], "norm.1.weight": [8], "norm.3.weight": [8, 8]}
@@ -212,3 +214,137 @@ def test_the_variant_decides_whether_a_single_file_loads_the_final_norm(
assert isinstance(model, Qwen35Encoder)
assert ("norm.weight" in model.state_dict()) is loads_the_norm
+
+
+# -- ComfyUI's int8_tensorwise build: the whole vision-language model, of which the encoder reads the language model. --
+
+_PREFIX = "model.language_model."
+_GROUP = 16
+# What the build quantizes in the language model: every decoder Linear but the Gated DeltaNet's `in_proj_a/b`, and the
+# embedding, which is not a Linear.
+_DENSE_LINEARS = ("in_proj_a", "in_proj_b")
+
+
+def _quantizable(reference: Qwen35Encoder) -> list[str]:
+ return ["embed_tokens"] + [
+ name
+ for name, module in reference.named_modules()
+ if name.startswith("layers.") and isinstance(module, torch.nn.Linear) and not name.endswith(_DENSE_LINEARS)
+ ]
+
+
+def _int8_whole_model_file(reference: Qwen35Encoder) -> dict[str, torch.Tensor]:
+ """The reference as the int8 build stores it, with the vision tower, LM head and MTP head beside it.
+
+ The reference is left holding the round trip, which is what a correct load computes.
+ """
+ sd = {f"{_PREFIX}{key}": value.detach().clone() for key, value in reference.state_dict().items()}
+ for path in _quantizable(reference):
+ payload = quantize_convrot(sd[f"{_PREFIX}{path}.weight"], group_size=_GROUP)
+ sd[f"{_PREFIX}{path}.weight"], sd[f"{_PREFIX}{path}.weight_scale"] = payload.codes, payload.scale
+ sd[f"{_PREFIX}{path}.comfy_quant"] = _marker()
+ # W8A8 builds ship an activation scale the dequantizing layers have nothing to apply to.
+ sd[f"{_PREFIX}{path}.input_scale"] = torch.tensor(0.5)
+ with torch.no_grad():
+ reference.get_submodule(path).weight.copy_(payload.dequantized)
+ for path, shape in {"model.visual.blocks.0.attn.qkv": (48, 16), "lm_head": (64, 32), "mtp.fc": (32, 64)}.items():
+ payload = quantize_convrot(torch.randn(shape), group_size=_GROUP)
+ sd[f"{path}.weight"], sd[f"{path}.weight_scale"] = payload.codes, payload.scale
+ sd[f"{path}.comfy_quant"] = _marker()
+ return sd
+
+
+def _marker() -> torch.Tensor:
+ return comfy_quant_marker({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": _GROUP})
+
+
[email protected]("final_norm", [True, False], ids=["9b, final norm", "4b, intermediate layers"])
+def test_an_int8_whole_model_file_computes_what_its_dequantized_weights_compute(
+ tmp_path: Path, loader, tensors_read: list[str], final_norm: bool
+) -> None:
+ reference = _reference(final_norm=final_norm)
+ path = tmp_path / "qwen3.5_int8_convrot.safetensors"
+ save_file(_int8_whole_model_file(reference), path)
+
+ model = load_qwen3_5_text_encoder(loader, [path], _config(), final_norm=final_norm, keep_fp8=False, what="test")
+
+ kept = {name for name, module in model.named_modules() if isinstance(module, Int8ConvrotLinear)}
+ assert kept == set(_quantizable(reference)) - {"embed_tokens"}
+ # The embedding is widened: `Qwen35Encoder.dtype` reads it, and an int8 table would hand out codes.
+ assert model.dtype is torch.float32 and not isinstance(model.embed_tokens, Int8ConvrotLinear)
+ # Dense where the file is dense.
+ assert type(model.layers[0].linear_attn.in_proj_a) is torch.nn.Linear
+ assert model.layers[0].linear_attn.conv1d.weight.dtype is torch.float32
+ # Neither the vision tower, the LM head nor the MTP head is read.
+ assert all(key.startswith(_PREFIX) for key in tensors_read)
+
+ input_ids = torch.randint(0, 64, (1, 9))
+ if final_norm:
+ expected = reference.last_hidden_state(input_ids)
+ output = model.last_hidden_state(input_ids)
+ else:
+ (expected,) = reference(input_ids, (_LAST,))
+ (output,) = model(input_ids, (_LAST,))
+ assert expected.abs().max() > 0.1
+ torch.testing.assert_close(output, expected, rtol=1e-4, atol=1e-5)
+ # One reservation, for what the load ends with: marked Linears stay one byte per weight, and the activation
+ # scales are not loaded.
+ loader._ram_cache.make_room.assert_called_once_with(
+ sum(t.nelement() * t.element_size() for t in model.state_dict().values())
+ )
+
+
+def test_a_dense_whole_model_file_loads_the_same_language_model_as_an_encoder_export(
+ tmp_path: Path, loader, tensors_read: list[str]
+) -> None:
+ weights = _reference(final_norm=True).state_dict()
+ path = tmp_path / "qwen3.5_9b_bf16.safetensors"
+ save_file(
+ {f"{_PREFIX}{k}": v for k, v in weights.items()}
+ | _random(
+ {"lm_head.weight": [64, 32], "mtp.fc.weight": [32, 64], "model.visual.blocks.0.attn.qkv.weight": [48, 16]}
+ ),
+ path,
+ )
+
+ model = load_qwen3_5_text_encoder(loader, [path], _config(), final_norm=True, keep_fp8=False, what="test")
+
+ _assert_loaded(model, weights)
+ assert all(key.startswith(_PREFIX) for key in tensors_read)
+
+
+def test_an_int8_layer_without_an_int8_tensorwise_marker_is_refused(tmp_path: Path, loader) -> None:
+ reference = _reference(final_norm=True)
+ file = _int8_whole_model_file(reference)
+ del file[f"{_PREFIX}layers.0.mlp.gate_proj.comfy_quant"]
+ path = tmp_path / "qwen3.5_9b_int8_convrot.safetensors"
+ save_file(file, path)
+
+ with pytest.raises(ValueError, match="no `comfy_quant` marker"):
+ load_qwen3_5_text_encoder(loader, [path], _config(), final_norm=True, keep_fp8=False, what="test")
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_a_w4a8_layer_is_refused_naming_its_format(tmp_path: Path, loader) -> None:
+ reference = _reference(final_norm=True)
+ file = _int8_whole_model_file(reference)
+ file[f"{_PREFIX}layers.0.mlp.gate_proj.comfy_quant"] = comfy_quant_marker({"format": "asym_w4a8_int8"})
+ path = tmp_path / "qwen3.5_9b_w4a8.safetensors"
+ save_file(file, path)
+
+ with pytest.raises(ValueError, match="asym_w4a8_int8"):
+ load_qwen3_5_text_encoder(loader, [path], _config(), final_norm=True, keep_fp8=False, what="test")
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_a_scaled_fp8_layer_is_refused_before_room_is_reserved(tmp_path: Path, loader) -> None:
+ weights = {f"{_PREFIX}{k}": v for k, v in _reference(final_norm=True).state_dict().items()}
+ gate = f"{_PREFIX}layers.0.mlp.gate_proj"
+ weights[f"{gate}.weight"] = weights[f"{gate}.weight"].to(torch.float8_e4m3fn)
+ weights[f"{gate}.weight_scale"] = torch.tensor(0.01)
+ path = tmp_path / "qwen3.5_9b_fp8_scaled.safetensors"
+ save_file(weights, path)
+
+ with pytest.raises(ValueError, match="quantization side channel"):
+ load_qwen3_5_text_encoder(loader, [path], _config(), final_norm=True, keep_fp8=False, what="test")
+ loader._ram_cache.make_room.assert_not_called()