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 unsloth's torchao fp8 transformers (#10181)

Alexander Eichhornb457968187a0
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 3dd0329e72..de426f9e26 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
@@ -47,7 +47,7 @@ reader's error; if the file is incomplete or corrupt, download it again.
| [Krea-2](/users-guide/models/local-models/krea-2/) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ |
| [Ideogram 4](/users-guide/models/local-models/ideogram4/) | ✓ | ✓ | ✓ | ✓ | R | R | ✓ | ✓ | ✗ | inside the Diffusers folder |
| [ERNIE-Image](/users-guide/models/local-models/ernie-image/) | ✓ | ✓ | L | L | L | L | ✗ | ✓ | ✗ | ✗ |
-| [MOSS-Image](/users-guide/models/local-models/moss-image/) | ✓ | ✓ | R | ✓ | R | R | R | ✓ | ✗ | ✗ |
+| [MOSS-Image](/users-guide/models/local-models/moss-image/) | ✓ | ✓ | unsloth torchao build ✓, others R | ✓ | R | R | R | ✓ | ✗ | ✗ |
| [Wan 2.2](/users-guide/video-generation/wan-22/) | ✓ | ✓ | ✓ | ✓ | R | L | ✓ | ✓ | ✗ | ✗ |
| [LTX-2](/users-guide/video-generation/ltx-2/) (2.5 only) | official layout ✓, Diffusers layout ✗ | ✓ | L | ✓ | L | ✓ | ✗ | ✓ | ✗ | ✗ |
| [MiniMax H3](/users-guide/video-generation/minimax-h3/) | ✓ | ✓ | L | ✓ | L | L | ✗ | ✗ | ✗ | ✗ |
@@ -57,12 +57,12 @@ reader's error; if the file is incomplete or corrupt, download it again.
`int4_tensorwise`, which most builds mix with int8 layers. **nvfp4** and **fp8 scaled** mean ComfyUI's checkpoint
layouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. FLUX.3 also loads Black Forest
Labs' own builds: the nvfp4 export in NVIDIA ModelOpt's layout and `fp8r` (fp8 with one scale per row). It refuses
- AWQ and other producers' nvfp4 at install. For Qwen-Image-2.1 and FLUX.3, unsloth's torchao FP8 builds (fp8 weights
- with one scale per output row; FLUX.3's under diffusers' key names) load as fp8 scaled; other torchao layouts, such
- as per-tensor or block-wise fp8 and INT8 builds, are refused at install. Ideogram 4 refuses the torchao exports it
- recognizes; one that also quantized the projections Ideogram 4 is recognized by does not install as Ideogram 4 at
- all. MOSS-Image loads Comfy-Org's int8 build and GGUFs; its fp8, nvfp4 and w4a8 transformers, and unsloth's torchao
- builds, are refused at install, unscaled fp8 included. ComfyUI's other low-bit layouts (`w4a8`, `w6a8`, SVDQuant)
+ AWQ and other producers' nvfp4 at install. For Qwen-Image-2.1, MOSS-Image and FLUX.3, unsloth's torchao FP8 builds
+ (fp8 weights with one scale per output row; FLUX.3's under diffusers' key names) load as fp8 scaled; other torchao
+ layouts, such as per-tensor or block-wise fp8 and INT8 builds, are refused at install. Apart from that, MOSS-Image
+ loads Comfy-Org's int8 build and GGUFs; its raw and ComfyUI scaled fp8, nvfp4 and w4a8 transformers are refused at
+ install. Ideogram 4 refuses the torchao exports it recognizes; one that also quantized the projections Ideogram 4 is
+ recognized by does not install as Ideogram 4 at all. ComfyUI's other low-bit layouts (`w4a8`, `w6a8`, SVDQuant)
are not supported; Krea-2, Qwen-Image and Wan 2.2 refuse them at install.
- **GGUF** covers the llama.cpp types (Q4_0 through Q8_0, the K-quants, BF16). ComfyUI-GGUF's `Q8_CR` (int8) and
`Q4_CR` (int4) files load for Krea-2 only; for every other model with GGUF support the install fails, as it does
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 09bcd7d02f..876308be9f 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
@@ -106,6 +106,7 @@ A single-file transformer comes in these forms; the model type, not the file nam
| ---- | -------- | ----- |
| bf16 safetensors | `moss-image-dit.safetensors`, Comfy-Org's `moss_image_base_bf16.safetensors` | Either key layout (see below). |
| int8 convrot safetensors | Comfy-Org's `moss_image_base_int8_convrot.safetensors` | `int8_tensorwise` with convrot. The attention, output and feed-forward projections stay int8 in memory and are dequantized for each step. |
+| fp8 safetensors | unsloth's `MOSS-Image-Base-FP8.safetensors` and `MOSS-Image-SFT-FP8.safetensors` | torchao fp8 with one scale per output row. On a GPU with fp8 support, the attention, output and feed-forward projections stay fp8 in memory when FP8 Storage is on (the default for these files) or [`fp8_compute`](/configuration/optimization/fp8-compute/) is on. They are then dequantized for each step, or, with `fp8_compute` on a GPU with fp8 hardware, multiplied directly in fp8. Otherwise they are widened to the compute dtype when the model loads. |
| GGUF | `unsloth/MOSS-Image-Base-GGUF`, `leejet/MOSS-Image-SFT-GGUF` | The K-quants and `Q8_0` and the other llama.cpp types. The packed weights are dequantized for each step. |
The community files come in two key layouts, and both install and load:
@@ -121,12 +122,12 @@ layers, the text projection and the `q` projection of every block. For a quantiz
dequantized when the model loads. The 42 `q` projections alone occupy about 0.74 GiB dense (bf16), so a Q4 GGUF takes
more memory than its file size suggests.
-Not supported, and refused at install with a message saying so: fp8 transformers (scaled or not), torchao exports
-such as unsloth's FP8 and INT8 builds (`_weight_qdata`), nvfp4 and w4a8 builds, and the ComfyUI-GGUF `Q8_CR` and `Q4_CR`
-files. Install the
-bf16 file, the int8 build or a GGUF instead. To save VRAM with a bf16 file, turn on **FP8 Storage** in the model's
-**Default Settings**. FP8 Storage does nothing for a GGUF, and for the int8 build it applies only to the layers
-that are not already int8.
+Not supported, and refused at install with a message saying so: ComfyUI's scaled fp8 and unscaled fp8 transformers,
+torchao exports other than the fp8 layout above (INT8 builds, per-tensor or block-wise fp8), files that mix torchao fp8
+with ComfyUI-quantized layers, nvfp4 and w4a8 builds, and the ComfyUI-GGUF `Q8_CR` and `Q4_CR` files. Install the bf16
+file, the fp8 or int8 build above, or a GGUF instead. To save VRAM with a bf16 file, turn on **FP8 Storage** in the
+model's **Default Settings**. FP8 Storage does nothing for a GGUF; for the fp8 build it only keeps the file's fp8 layers
+packed, and for the int8 build it applies only to the layers that are not already int8.
The int8 build and the GGUFs save memory; they are not faster. In InvokeAI's measurements on an RTX 4090 they took
3-15 % longer per image than bf16. Int8 and Q8_0 keep the scene of a bf16 image and shift its details.
@@ -328,7 +329,7 @@ weights instead of being merged into them.
## Limitations
-- fp8, nvfp4, w4a8 and ComfyUI-GGUF `Q8_CR`/`Q4_CR` transformers are refused at install (see [Installing](#installing)).
+- ComfyUI scaled and unscaled fp8, other torchao layouts, torchao fp8 mixed with ComfyUI-quantized layers, nvfp4, w4a8 and ComfyUI-GGUF `Q8_CR`/`Q4_CR` transformers are refused at install (see [Installing](#installing)).
- ControlNet, reference images and seamless tiling are not available.
- Regional guidance places boxes in a layout; it has no regional negative prompts or regional reference images.
- MOSS-Image is not offered in the [Upscale panel](/users-guide/image-generation/upscale/).
diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.py
index 384f501647..69184066e3 100644
--- a/invokeai/backend/model_manager/configs/main.py
+++ b/invokeai/backend/model_manager/configs/main.py
@@ -81,6 +81,7 @@ from invokeai.backend.patches.lora_conversions.sd3_lora_constants import sd3_var
from invokeai.backend.quantization.fp8_scaled import (
COMFY_QUANT_SUFFIX,
FP8_WEIGHT_DTYPES,
+ STRAY_METADATA_KEYS,
TORCHAO_QDATA_SUFFIX,
find_torchao_fp8_problem,
is_scale_metadata_key,
@@ -1790,8 +1791,8 @@ def _raise_for_unsupported_comfy_quantization(
f"this {family} transformer is saved as torchao-quantized tensors that InvokeAI cannot load: "
f"{problem}. Only torchao float8_e4m3fn weights with one scale per output row load, such as "
"unsloth's FP8 builds; other layouts, including INT8 builds, are not supported. A file that is "
- "missing one half of a weight/scale pair is probably incomplete: download it again. Otherwise "
- "install the bf16, fp8_scaled or int8_convrot build, or a GGUF."
+ "missing one half of a weight/scale pair is probably incomplete: download it again. "
+ f"{supported or 'Otherwise install the bf16, fp8_scaled or int8_convrot build, or a GGUF.'}"
)
elif any(isinstance(key, str) and key.endswith(TORCHAO_QDATA_SUFFIX) for key in state_dict):
raise InvalidMatchError(
@@ -4772,21 +4773,35 @@ def _has_moss_image_keys(state_dict: dict[str | int, Any]) -> bool:
)
-_MOSS_IMAGE_SUPPORTED = "Install the bf16 or Comfy-Org int8_convrot build, or a GGUF (Q8_0, Q4_K, ...), instead."
+_MOSS_IMAGE_SUPPORTED = (
+ "Install the bf16, unsloth torchao FP8 or Comfy-Org int8_convrot build, or a GGUF (Q8_0, Q4_K, ...), instead."
+)
def _raise_for_unsupported_moss_image_quantization(mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:
- """Refuse every quantization a MOSS-Image safetensors loader cannot build; Comfy-Org's int8 convrot passes.
+ """Refuse every quantization a MOSS-Image safetensors loader cannot build; Comfy-Org's int8 convrot and unsloth's
+ torchao fp8 pass.
`InvalidMatchError`, not `NotAMatchError`: the file *is* a MOSS-Image transformer, so the installer shows the
- reason instead of registering it as an unknown model nothing can load. What the loader builds is dense weights and
- `int8_tensorwise` layers, nothing else. The shared helper names torchao builds, nvfp4 and int8 weights whose marker
+ reason instead of registering it as an unknown model nothing can load. What the loader builds is dense weights,
+ `int8_tensorwise` layers and torchao fp8 layers, nothing else. The shared helper names torchao layouts the loader
+ cannot translate (INT8 builds, per-tensor or block-wise scales), nvfp4 and int8 weights whose marker
is missing or of another scheme (W4A8 stores I8 weights with a codebook); the checks here cover what it does not:
- packed `uint8` and fp8 weights, and a scale or marker on a weight that is not int8.
+ packed `uint8` and fp8 weights, a scale or marker on a weight that is not int8, and torchao fp8 layers beside
+ ComfyUI-quantized (`.comfy_quant`) ones in one file.
"""
- _raise_for_unsupported_comfy_quantization(mod, state_dict, "MOSS-Image", supported=_MOSS_IMAGE_SUPPORTED)
+ _raise_for_unsupported_comfy_quantization(
+ mod, state_dict, "MOSS-Image", supported=_MOSS_IMAGE_SUPPORTED, accepts_torchao_fp8=True
+ )
keys = [key for key in state_dict if isinstance(key, str)]
+ # One quantization per file, as the loader enforces with `_reject_other_quantization_beside_torchao`, its
+ # twin on the loader side.
+ if any(key.endswith(TORCHAO_QDATA_SUFFIX) for key in keys) and any(key.endswith(".comfy_quant") for key in keys):
+ raise InvalidMatchError(
+ "this MOSS-Image transformer mixes torchao fp8 layers with ComfyUI-quantized (`.comfy_quant`) layers, "
+ f"and only one quantization per file loads. {_MOSS_IMAGE_SUPPORTED}"
+ )
for key in keys:
dtype = getattr(state_dict[key], "dtype", None)
if key.endswith(".weight") and dtype is torch.uint8:
@@ -4796,7 +4811,8 @@ def _raise_for_unsupported_moss_image_quantization(mod: ModelOnDisk, state_dict:
)
if key.endswith(".weight") and dtype in FP8_WEIGHT_DTYPES:
raise InvalidMatchError(
- f"fp8-quantized MOSS-Image transformers are not supported yet (found '{key}'). {_MOSS_IMAGE_SUPPORTED}"
+ f"this MOSS-Image transformer stores a plain or ComfyUI scaled fp8 weight (found '{key}'), which is not "
+ f"supported; only unsloth's torchao fp8 layout loads. {_MOSS_IMAGE_SUPPORTED}"
)
# A scale or marker on a weight that is not int8 belongs to a scheme the loader would drop without applying.
int8_layers = {
@@ -4805,7 +4821,9 @@ def _raise_for_unsupported_moss_image_quantization(mod: ModelOnDisk, state_dict:
if key.endswith(".weight") and getattr(state_dict[key], "dtype", None) is torch.int8
}
for key in keys:
- if is_scale_metadata_key(key) and key.rsplit(".", 1)[0] not in int8_layers:
+ # The loader judges keys after stripping the checkpoint prefix, so a stray marker counts under any prefix.
+ is_side_channel = is_scale_metadata_key(key) or key.rsplit(".", 1)[-1] in STRAY_METADATA_KEYS
+ if is_side_channel and key.rsplit(".", 1)[0] not in int8_layers:
raise InvalidMatchError(
f"this MOSS-Image transformer carries a quantization side channel on a weight that is not int8 "
f"(found '{key}'), which is not supported yet. {_MOSS_IMAGE_SUPPORTED}"
@@ -4816,9 +4834,10 @@ class Main_Checkpoint_MossImage_Config(Checkpoint_Config_Base, Main_Config_Base,
"""Model config for MOSS-Image single-file transformers (safetensors), such as the ComfyUI export.
The file holds the transformer alone; the Qwen3.5-9B encoder and the FLUX.2 VAE are separate models, selected on
- the loader node. Dense (bf16/fp16/fp32) files load, and so does Comfy-Org's `int8_tensorwise` convrot export; both
- may fuse each block's `q`, `k`, `v` into `proj.qkv`. Any other quantization is refused at install with
- `InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead.
+ the loader node. Dense (bf16/fp16/fp32) files load, and so do Comfy-Org's `int8_tensorwise` convrot export and
+ unsloth's torchao fp8 export (fp8 weights with one scale per output row). The dense and int8 files may fuse each
+ block's `q`, `k`, `v` into `proj.qkv`; the fp8 export keeps them split. Any other quantization is refused at
+ install with `InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead.
"""
base: Literal[BaseModelType.MossImage] = Field(default=BaseModelType.MossImage)
diff --git a/invokeai/backend/model_manager/load/model_loaders/moss_image.py b/invokeai/backend/model_manager/load/model_loaders/moss_image.py
index 0f28e83c12..f699e925e2 100644
--- a/invokeai/backend/model_manager/load/model_loaders/moss_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/moss_image.py
@@ -11,7 +11,7 @@ and scheduler, so `GenericDiffusersLoader` cannot resolve them. The transformer
The scheduler is never loaded: `moss_image_denoise` builds the schedule itself.
-A single-file transformer is bf16, ComfyUI's `int8_tensorwise` convrot export, or a GGUF. Comfy-Org's export and
+A single-file transformer is bf16, ComfyUI's `int8_tensorwise` convrot export, unsloth's torchao fp8 export, or a GGUF. Comfy-Org's export and
leejet's GGUFs fuse each block's `q`, `k` and `v` into `proj.qkv`; `split_fused_qkv` unfuses them before anything else
reads the state dict. A few Linears stay dense (`MOSS_IMAGE_FP8_SKIP_PATTERNS`), whichever quantization
the file uses, because the vendored forward reads their weight dtype.
@@ -45,7 +45,20 @@ from invokeai.backend.model_manager.load.model_loaders.qwen3_5_encoder import lo
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.moss_image.checkpoint_layout import drop_comfy_attention_config, split_fused_qkv
from invokeai.backend.moss_image.pipeline_moss_image import MOSSImageTransformer
-from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
+ TORCHAO_QDATA_SUFFIX,
+ attach_fp8_scales,
+ cast_state_dict,
+ clone_unreplaced_tensors,
+ dequantize_fp8_scaled,
+ extract_fp8_scaled_layers,
+ is_scale_metadata_key,
+ reject_quantized_side_channel,
+ split_fp8_scaled_layers,
+ translate_torchao_fp8_layers,
+ warn_on_unattached_scales,
+)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load
from invokeai.backend.quantization.int8_convrot import (
drop_unconsumed_quantization_sidecars,
@@ -161,12 +174,44 @@ def _read_component_state_dict(directory: Path) -> dict[str, torch.Tensor]:
return sd
+def _reject_other_quantization_beside_torchao(sd: Mapping[str, Any], what: str) -> None:
+ """Refuse a torchao fp8 file that also carries any scale or `.comfy_quant` key, or a plain fp8 `.weight`.
+
+ torchao's own `._weight_scale` is not one of them. The loader applies one quantization per file, as the installer
+ enforces. Some of these files would load wrongly: a stray `X.weight_scale` beside a torchao pair is overwritten by
+ the translation, and int8 markers leave the translated scales behind. A ComfyUI scaled-fp8 layer would load
+ correctly, and is refused only to keep to one quantization. Runs before anything is reserved, for a record that
+ predates the installer's refusal.
+ """
+ if not any(isinstance(key, str) and key.endswith(TORCHAO_QDATA_SUFFIX) for key in sd):
+ return
+ other = sorted(
+ key
+ for key, tensor in sd.items()
+ if is_scale_metadata_key(key)
+ or (key.endswith(".weight") and getattr(tensor, "dtype", None) in FP8_WEIGHT_DTYPES)
+ )
+ if other:
+ raise ValueError(
+ f"{what} mixes torchao fp8 layers with other quantization keys ({len(other)}, e.g. {other[:3]}), and only "
+ "one quantization per file loads. Use another build of this model."
+ )
+
+
class _MossImageTransformerLoading(ModelLoader):
"""The transformer load both MOSS-Image formats share, once each has a state dict and a geometry."""
def _load_transformer(
- self, config: AnyModelConfig, sd: dict[str, torch.Tensor], geometry: dict[str, Any], what: str
+ self,
+ config: AnyModelConfig,
+ sd: dict[str, torch.Tensor],
+ geometry: dict[str, Any],
+ what: str,
+ *,
+ torchao_fp8: bool = False,
) -> AnyModel:
+ """Build the transformer from `sd`. `torchao_fp8` says `translate_torchao_fp8_layers` renamed layers to
+ `.weight` + `.weight_scale`; that is the only source of fp8 scales accepted, any other is refused below."""
drop_comfy_attention_config(sd)
markers = extract_int8_convrot_markers(sd)
# Outside the int8 branch, so an int8 weight whose marker is missing or unreadable is refused, not cast as codes.
@@ -181,6 +226,8 @@ class _MossImageTransformerLoading(ModelLoader):
sd.setdefault("rope.bands", model.rope.bands)
skip_patterns = _model_declared_skip_patterns(model)
+ fp8_layers: dict[str, Any] = {}
+ keep_fp8 = False
if markers:
# In place: a rebound dict would keep the originals alive and overshoot the reservation.
kept_sd = drop_unconsumed_quantization_sidecars(sd)
@@ -201,24 +248,56 @@ class _MossImageTransformerLoading(ModelLoader):
"dequantized per forward)"
)
else:
- # Strict below would name an orphaned scale key; this names the cause before anything is reserved.
- reject_quantized_side_channel(sd, what)
+ if torchao_fp8:
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints={})
+ keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)
+ else:
+ # Strict below would name an orphaned scale key; this names the cause before anything is reserved.
+ reject_quantized_side_channel(sd, what)
reserve_for_load(
self._ram_cache.make_room,
sd,
dtype,
- keep_fp8=False,
+ keep_fp8=keep_fp8,
model=model,
skip_patterns=skip_patterns,
- fp8_layers={},
+ fp8_layers=fp8_layers,
nvfp4_payloads={},
)
- cast_state_dict(sd, dtype, keep_fp8=False, model=model, skip_patterns=skip_patterns)
+ mapped = dict(sd) if fp8_layers and not keep_fp8 else None
+ if fp8_layers and not keep_fp8:
+ dequantize_fp8_scaled(sd, fp8_layers, dtype)
+ fp8_layers = {}
+ # Folds the layers a skip pattern holds dense (`.proj.q` among them) with their scale applied.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ if mapped is not None:
+ # Dense tensors the fold and cast left as they were are slices of the file mapping and would pin it,
+ # uncounted. The kept path skips this step altogether: copying its fp8 codes costs ~4.4 GB at load, and
+ # the mapping plus the copies are alive together for a moment.
+ clone_unreplaced_tensors(sd, mapped)
+ mapped.clear()
model.load_state_dict(sd, strict=True, assign=True)
# `assign=True` aliases every parameter to its state dict tensor; the dict would keep the whole model alive
# through the cast below.
sd.clear()
reject_incomplete_load(model, what=what)
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ self._logger.info(
+ f"{what}: kept {attached} layer(s) in fp8 (torchao fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
+ warn_on_unattached_scales(self._logger, "MOSS-Image", attached, fp8_layers)
+ # The remainder stays dense on purpose: the build ships those layers in bf16, and re-encoding them as
+ # unscaled fp8 zeroes most of `time_embedding.2` and changed the image in a 4090 A/B. FP8 Storage on an
+ # fp8 file keeps the file's fp8 layers packed, nothing more (as Qwen-Image-2.1 and FLUX.3 do).
+ #
+ # Memory: the clone step above is skipped on this path. The kept codes and their scales, and every dense
+ # tensor already at the compute dtype, are views of the file mapping. On a bf16 device the folded `.proj.q`
+ # codes (~396 MB) leave `sd` but stay mapped and uncounted, because those views pin the mapping; on fp16
+ # the dense remainder is cast to new tensors and its bf16 bytes stay pinned and uncounted too. On Windows
+ # that is committed memory while the model is cached.
+ return model.eval()
return self._apply_fp8_layerwise_casting(model.eval(), config, SubModelType.Transformer)
@@ -298,9 +377,17 @@ class MossImageCheckpointModel(_MossImageTransformerLoading):
model_path = Path(config.path)
sd = load_file(model_path)
sd = CheckpointPrefix.detect(sd).strip(sd)
+ # unsloth's torchao fp8 build, renamed to the scaled-fp8 form. Before the split and the geometry read, which
+ # look for `.weight`.
+ _reject_other_quantization_beside_torchao(sd, f"MOSS-Image checkpoint {model_path.name}")
+ torchao_fp8 = translate_torchao_fp8_layers(sd) > 0
sd = split_fused_qkv(sd)
return self._load_transformer(
- config, sd, moss_image_transformer_config(sd), f"MOSS-Image checkpoint {model_path.name}"
+ config,
+ sd,
+ moss_image_transformer_config(sd),
+ f"MOSS-Image checkpoint {model_path.name}",
+ torchao_fp8=torchao_fp8,
)
diff --git a/invokeai/backend/moss_image/working_memory.py b/invokeai/backend/moss_image/working_memory.py
index 9281f410a5..ed2927d12f 100644
--- a/invokeai/backend/moss_image/working_memory.py
+++ b/invokeai/backend/moss_image/working_memory.py
@@ -16,8 +16,9 @@ from invokeai.backend.patches.lora_conversions.moss_image_lora_constants import
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
+from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytes
from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
-from invokeai.backend.working_memory.fit import Line
+from invokeai.backend.working_memory.fit import Line, off_line_reasons
from invokeai.backend.working_memory.spec import EstimatorSpec, register
# One transformer token per 2x2 patch of the FLUX.2 VAE's 8x latent.
@@ -40,13 +41,9 @@ def _line(features: Mapping[str, FeatureValue]) -> Optional[Line]:
fit leaves it out (`fit.hand_set_values`): the slope is hand-set until a fitted base ships with it."""
if not all(isinstance(features.get(name), int) for name in ("height", "width", "text_tokens")):
return None
- on_top = [
- f"{name}={features[name]}"
- for name in ("score_matrix_bytes", "dequant_bytes", "lora_sidecar_bytes")
- if features.get(name)
- ]
+ off_line = off_line_reasons(_denoise_terms, features, ("k_token",))
shape = f"{features['height']}x{features['width']}-text{features['text_tokens']}"
- return Line("token", _tokens(features), not on_top, "-".join((shape, *on_top)))
+ return Line("token", _tokens(features), not off_line, "-".join((shape, *off_line)))
def _denoise_terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) -> tuple[WorkingMemoryTerm, ...]:
@@ -57,6 +54,10 @@ def _denoise_terms(features: Mapping[str, FeatureValue], values: Mapping[str, fl
WorkingMemoryTerm("attention_scores", cast(int, features["score_matrix_bytes"]), True),
# Analytic: the dequantized copy of the largest packed Linear of a quantized build, zero for a dense one.
WorkingMemoryTerm("dequant_transient", cast(int, features["dequant_bytes"]), True),
+ # Analytic: the compute-dtype copies of the largest float8-stored layer that FP8 Storage widens per forward, or
+ # that a kept fp8 checkpoint dequantizes with its scale (two copies); zero for a build with no float8 weight.
+ # Absent from the points measured before it was priced, all of them bf16 forwards without one.
+ WorkingMemoryTerm("fp8_cast_transient", cast(int, features.get("fp8_cast_bytes", 0)), True),
# Analytic: the LoRAs' tensors and the update their sidecars form per forward. Absent from the points measured
# before LoRAs ran on MOSS-Image, all of them forwards without one.
WorkingMemoryTerm("lora_sidecar", cast(int, features.get("lora_sidecar_bytes", 0)), True),
@@ -109,6 +110,7 @@ def estimate_moss_image_denoise_working_memory(
seq_len=image_tokens + text_tokens,
),
"dequant_bytes": peak_dequant_transient_bytes(transformer, dtype),
+ "fp8_cast_bytes": peak_fp8_cast_transient_bytes(transformer, dtype),
"lora_sidecar_bytes": _lora_sidecar_bytes(transformer, loras, model_format, image_tokens + text_tokens, dtype),
}
return MOSS_IMAGE_DENOISE_SPEC.estimate(features, device)
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index c18657ee70..363f3244d1 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -80524,7 +80524,7 @@
"format"
],
"title": "Main_Checkpoint_MossImage_Config",
- "description": "Model config for MOSS-Image single-file transformers (safetensors), such as the ComfyUI export.\n\nThe file holds the transformer alone; the Qwen3.5-9B encoder and the FLUX.2 VAE are separate models, selected on\nthe loader node. Dense (bf16/fp16/fp32) files load, and so does Comfy-Org's `int8_tensorwise` convrot export; both\nmay fuse each block's `q`, `k`, `v` into `proj.qkv`. Any other quantization is refused at install with\n`InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead."
+ "description": "Model config for MOSS-Image single-file transformers (safetensors), such as the ComfyUI export.\n\nThe file holds the transformer alone; the Qwen3.5-9B encoder and the FLUX.2 VAE are separate models, selected on\nthe loader node. Dense (bf16/fp16/fp32) files load, and so do Comfy-Org's `int8_tensorwise` convrot export and\nunsloth's torchao fp8 export (fp8 weights with one scale per output row). The dense and int8 files may fuse each\nblock's `q`, `k`, `v` into `proj.qkv`; the fp8 export keeps them split. Any other quantization is refused at\ninstall with `InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead."
},
"Main_Checkpoint_QwenImage21_Config": {
"properties": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 22ce87fdf6..27bbfb3bec 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -33445,9 +33445,10 @@ export type components = {
* @description Model config for MOSS-Image single-file transformers (safetensors), such as the ComfyUI export.
*
* The file holds the transformer alone; the Qwen3.5-9B encoder and the FLUX.2 VAE are separate models, selected on
- * the loader node. Dense (bf16/fp16/fp32) files load, and so does Comfy-Org's `int8_tensorwise` convrot export; both
- * may fuse each block's `q`, `k`, `v` into `proj.qkv`. Any other quantization is refused at install with
- * `InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead.
+ * the loader node. Dense (bf16/fp16/fp32) files load, and so do Comfy-Org's `int8_tensorwise` convrot export and
+ * unsloth's torchao fp8 export (fp8 weights with one scale per output row). The dense and int8 files may fuse each
+ * block's `q`, `k`, `v` into `proj.qkv`; the fp8 export keeps them split. Any other quantization is refused at
+ * install with `InvalidMatchError`, and `NotAMatchError` would let it register as an unknown model instead.
*/
Main_Checkpoint_MossImage_Config: {
/**
diff --git a/tests/backend/model_manager/configs/test_moss_image_identification.py b/tests/backend/model_manager/configs/test_moss_image_identification.py
index 7007edf382..8da61881a6 100644
--- a/tests/backend/model_manager/configs/test_moss_image_identification.py
+++ b/tests/backend/model_manager/configs/test_moss_image_identification.py
@@ -6,6 +6,7 @@ config claiming the file shows up as a second match.
"""
import json
+import re
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
@@ -26,7 +27,7 @@ from invokeai.backend.model_manager.configs.main import (
from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Flux2_Config
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-from tests.backend.model_manager.load.moss_image_fixtures import fuse_qkv_keys, int8_convrot_keys
+from tests.backend.model_manager.load.moss_image_fixtures import CONVROT_MARKER, fuse_qkv_keys, int8_convrot_keys
from tests.backend.model_manager.load.state_dicts import moss_image_dit_keys, moss_image_vae_keys
from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors
from tests.fixtures.quantized_payloads import q8_cr_marker, quantize_convrot, write_gguf
@@ -179,6 +180,37 @@ def test_a_lora_for_the_transformer_is_a_moss_image_lora_not_a_main_model(tmp_pa
assert isinstance(result.details[LoRA_LyCORIS_MossImage_Config.__name__], InvalidMatchError)
+def _torchao_fp8(
+ keys: Keys, *, scale_shape: list[int] | None = None, zero_point: bool = False, drop_scale_of: str | None = None
+) -> None:
+ """Store every block projection as unsloth's torchao build does: `_weight_qdata` plus a per-row `_weight_scale`
+ in place of `.weight`. `zero_point` makes the payload int8 with a zero point, as the INT8 build is."""
+ for key in [k for k in keys if re.fullmatch(r"layers\.\d+\.proj\.(q|k|v|o|ffn_up_gate|ffn_down)\.weight", k)]:
+ shape, _ = keys.pop(key)
+ layer = key.removesuffix(".weight")
+ keys[f"{layer}._weight_qdata"] = (shape, "I8" if zero_point else "F8_E4M3")
+ keys[f"{layer}._weight_scale"] = (scale_shape or [shape[0], 1], "F32")
+ if layer == drop_scale_of:
+ del keys[f"{layer}._weight_scale"]
+ if zero_point:
+ keys[f"{layer}._weight_zero_point"] = ([shape[0], 1], "I8")
+
+
+def test_unsloths_torchao_fp8_build_installs_with_fp8_storage_on(tmp_path: Path) -> None:
+ keys = _dit()
+ _torchao_fp8(keys)
+ # Header facts of MOSS-Image-Base-FP8.safetensors: 252 quantized layers, the embedders and heads dense bf16.
+ assert sum(k.endswith("._weight_qdata") for k in keys) == 252
+
+ result = _identify(write_header_only_safetensors(tmp_path / "MOSS-Image-Base-FP8.safetensors", keys))
+
+ assert type(result.config) is Main_Checkpoint_MossImage_Config
+ assert result.match_count == 1
+ # Identification turns FP8 Storage on for a float8 denoiser, and the loader keeps the file's fp8 layers for it.
+ assert result.config.default_settings is not None
+ assert result.config.default_settings.fp8_storage is True
+
+
@pytest.mark.parametrize(
("quantize", "message"),
[
@@ -189,9 +221,24 @@ def test_a_lora_for_the_transformer_is_a_moss_image_lora_not_a_main_model(tmp_pa
),
pytest.param(
lambda keys: keys.update({"layers.0.proj.q.weight": ([3072, 3072], "F8_E4M3")}),
- "fp8-quantized MOSS-Image transformers are not supported yet",
+ "plain or ComfyUI scaled fp8 weight",
id="raw-fp8",
),
+ pytest.param(
+ lambda keys: keys.update(
+ {
+ "layers.0.proj.q.weight": ([3072, 3072], "F8_E4M3"),
+ "layers.0.proj.q.weight_scale": ([3072, 1], "F32"),
+ }
+ ),
+ "plain or ComfyUI scaled fp8 weight",
+ id="comfy-scaled-fp8",
+ ),
+ pytest.param(
+ lambda keys: (_torchao_fp8(keys), keys.update({"layers.0.proj.k.weight_scale": ([3072], "F32")})),
+ "side channel on a weight that is not int8",
+ id="torchao-with-stray-scale",
+ ),
pytest.param(
lambda keys: keys.update({"layers.0.proj.q.comfy_quant": ([32], "U8")}),
"side channel on a weight that is not int8",
@@ -210,9 +257,19 @@ def test_a_lora_for_the_transformer_is_a_moss_image_lora_not_a_main_model(tmp_pa
id="packed-uint8-weights",
),
pytest.param(
- lambda keys: keys.update({"layers.0.proj.q._weight_qdata": ([3072, 3072], "F8_E4M3")}),
- "torchao",
- id="unsloth-fp8-torchao",
+ lambda keys: _torchao_fp8(keys, zero_point=True),
+ "carries a zero point",
+ id="unsloth-int8-torchao",
+ ),
+ pytest.param(
+ lambda keys: _torchao_fp8(keys, scale_shape=[3072, 24]),
+ "block-wise scales",
+ id="torchao-fp8-blockwise-scale",
+ ),
+ pytest.param(
+ lambda keys: _torchao_fp8(keys, drop_scale_of="layers.0.proj.q"),
+ "'layers.0.proj.q' has a quantized weight but no torchao scale",
+ id="torchao-half-pair",
),
pytest.param(
lambda keys: keys.update(
@@ -240,6 +297,45 @@ def test_an_unsupported_quantized_transformer_is_refused_not_registered(
assert message in str(refusal)
+def test_a_prefixed_stray_scaled_fp8_marker_beside_torchao_layers_is_refused_like_an_unprefixed_one(
+ tmp_path: Path,
+) -> None:
+ """The loader judges keys after stripping the ComfyUI prefix, so the installer must not let the marker through."""
+ keys = _dit()
+ _torchao_fp8(keys)
+ keys = {f"model.diffusion_model.{key}": value for key, value in keys.items()}
+ keys["model.diffusion_model.scaled_fp8"] = ([0], "F8_E4M3")
+
+ result = ModelConfigFactory.from_model_on_disk(
+ write_header_only_safetensors(tmp_path / "moss-prefixed.safetensors", keys), allow_unknown=True
+ )
+
+ assert result.config is None
+ refusal = result.details[Main_Checkpoint_MossImage_Config.__name__]
+ assert isinstance(refusal, InvalidMatchError)
+ assert "side channel on a weight that is not int8" in str(refusal)
+
+
+def test_a_file_mixing_torchao_fp8_and_int8_convrot_layers_is_refused_at_install(tmp_path: Path) -> None:
+ """The loader takes the int8 path or the fp8 path, so the other half of such a file could never be applied."""
+ keys = _dit()
+ _torchao_fp8(keys)
+ keys["text_embedder.blocks.0.qkv.weight"] = ([192, 4096], "I8")
+ keys["text_embedder.blocks.0.qkv.weight_scale"] = ([192, 1], "F32")
+
+ result = ModelConfigFactory.from_model_on_disk(
+ write_header_only_safetensors(
+ tmp_path / "moss-mixed.safetensors", keys, {"text_embedder.blocks.0.qkv": dict(CONVROT_MARKER)}
+ ),
+ allow_unknown=True,
+ )
+
+ assert result.config is None
+ refusal = result.details[Main_Checkpoint_MossImage_Config.__name__]
+ assert isinstance(refusal, InvalidMatchError)
+ assert "mixes torchao fp8 layers with ComfyUI-quantized" in str(refusal)
+
+
def test_a_w4a8_build_is_refused_naming_what_does_load(tmp_path: Path) -> None:
"""Comfy's W4A8 stores I8 codes beside a codebook and marks each layer `w4a8`: int8 weights, but not ours."""
keys = _dit()
@@ -261,7 +357,7 @@ def test_a_w4a8_build_is_refused_naming_what_does_load(tmp_path: Path) -> None:
assert result.config is None
refusal = str(result.details[Main_Checkpoint_MossImage_Config.__name__])
assert "'w4a8'" in refusal
- assert "bf16 or Comfy-Org int8_convrot build, or a GGUF" in refusal
+ assert "bf16, unsloth torchao FP8 or Comfy-Org int8_convrot build, or a GGUF" in refusal
assert "Only Comfy-Org" not in refusal
diff --git a/tests/backend/model_manager/load/test_moss_image_loader.py b/tests/backend/model_manager/load/test_moss_image_loader.py
index 5c92986f1f..48b38c5184 100644
--- a/tests/backend/model_manager/load/test_moss_image_loader.py
+++ b/tests/backend/model_manager/load/test_moss_image_loader.py
@@ -16,7 +16,7 @@ from unittest.mock import MagicMock
import accelerate
import pytest
import torch
-from safetensors.torch import save_file
+from safetensors.torch import load_file, save_file
from invokeai.backend.model_manager.configs.main import (
Main_Checkpoint_MossImage_Config,
@@ -42,6 +42,7 @@ from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.qwen3_5.qwen3_5_encoder import Qwen35Encoder
from tests.backend.model_manager.load.moss_image_fixtures import (
+ CONVROT_MARKER,
TINY_GEOMETRY,
forward,
fuse_qkv,
@@ -52,6 +53,7 @@ from tests.backend.model_manager.load.moss_image_fixtures import (
)
from tests.backend.model_manager.load.state_dicts.moss_image_dit_keys import state_dict_keys as moss_dit_keys
from tests.backend.model_manager.load.state_dicts.moss_image_vae_keys import state_dict_keys as moss_vae_keys
+from tests.fixtures.quantized_payloads import comfy_quant_marker
# `OpenMOSS-Team/MOSS-Image-Base`'s `transformer/config.json` at 1ceede80badddd6a7812069619edaa5633587192, verbatim
# but for `rope_base`, which no tensor records. A literal, so this fails when the detection drifts rather than agreeing
@@ -66,6 +68,8 @@ RELEASED_GEOMETRY = {
"text_dim": 4096,
}
+_TEXT_BLOCK_LINEARS = ("qkv", "proj", "ffn_gate", "ffn_up", "ffn_down")
+
_SAFETENSORS_DTYPES = {"BF16": torch.bfloat16, "F32": torch.float32, "I64": torch.int64}
@@ -538,6 +542,232 @@ class TestFusedAndInt8Checkpoints:
assert (forward(model) - expected).norm() / expected.norm() < 0.1
+class TestTorchaoFp8Checkpoint:
+ """unsloth's fp8 build: the block projections as `<layer>._weight_qdata` (float8_e4m3fn) plus a `[out, 1]` float32
+ scale, everything else dense. Real tiny tensors through the loader; compute is float32 on the CPU."""
+
+ QUANTIZED = ("q", "k", "v", "o", "ffn_up_gate", "ffn_down")
+
+ def _file(self, tmp_path: Path, prefix: str = "") -> tuple[Path, dict[str, torch.Tensor], dict[str, Any]]:
+ """The written file, the dense weights it keeps, and what each quantized layer means: (codes, scale)."""
+ dense = _tiny_state_dict(tiny_reference())
+ stored = dict(dense)
+ generator = torch.Generator().manual_seed(7)
+ quantized: dict[str, Any] = {}
+ for index in range(TINY_GEOMETRY["num_layers"]):
+ for name in self.QUANTIZED:
+ layer = f"layers.{index}.proj.{name}"
+ weight = dense.pop(f"{layer}.weight")
+ del stored[f"{layer}.weight"]
+ # Per-row and far from uniform, so a scale applied to the wrong rows or dropped shows in a forward.
+ scale = torch.rand(weight.shape[0], 1, generator=generator) * 3 + 0.25
+ codes = (weight / scale).to(torch.float8_e4m3fn)
+ stored[f"{layer}._weight_qdata"] = codes
+ stored[f"{layer}._weight_scale"] = scale
+ quantized[layer] = (codes, scale)
+ path = tmp_path / "MOSS-Image-Base-FP8.safetensors"
+ save_file({f"{prefix}{key}": value for key, value in stored.items()}, str(path))
+ return path, dense, quantized
+
+ def _load(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ path: Path,
+ *,
+ keep_fp8: bool,
+ fp8_compute_only: bool = False,
+ dtype: torch.dtype = torch.float32,
+ ) -> tuple[Any, Any, dict[str, torch.Tensor]]:
+ """The model, its loader, and the tensors `load_file` returned for the real file.
+
+ `keep_fp8` is FP8 Storage on. `fp8_compute_only` keeps the file's fp8 layers for the fp8 matmul with FP8
+ Storage off."""
+ loaded: dict[str, torch.Tensor] = {}
+ real_load_file = loader_module.load_file
+
+ def recording_load_file(path: Any) -> dict[str, torch.Tensor]:
+ tensors = real_load_file(path)
+ loaded.update(tensors)
+ return tensors
+
+ monkeypatch.setattr(loader_module, "load_file", recording_load_file)
+ loader = _loader(MossImageCheckpointModel, monkeypatch)
+ monkeypatch.setattr(
+ loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: dtype)
+ )
+ loader._should_use_fp8 = lambda _config, _submodel=None: keep_fp8
+ if fp8_compute_only:
+ loader._keep_fp8_weights = lambda _config, _submodel=None: True
+ config = Main_Checkpoint_MossImage_Config.model_construct(path=str(path), name="moss")
+ return loader._load_model(config, SubModelType.Transformer), loader, loaded
+
+ @pytest.mark.parametrize("prefix", ["", "model.diffusion_model."])
+ def test_with_fp8_storage_the_file_keeps_its_fp8_layers_and_the_dense_remainder_stays_dense(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, prefix: str
+ ) -> None:
+ path, dense, quantized = self._file(tmp_path, prefix)
+
+ model, loader, _ = self._load(monkeypatch, path, keep_fp8=True)
+
+ for layer in ("layers.0.proj.k", "layers.2.proj.ffn_down"):
+ codes, scale = quantized[layer]
+ module = model.get_submodule(layer)
+ assert module.weight.dtype is torch.float8_e4m3fn, layer
+ assert torch.equal(module.weight.view(torch.uint8), codes.view(torch.uint8)), layer
+ # Flat per-row, the form the fp8 matmul reads.
+ assert module.weight_scale.shape == (codes.shape[0],), layer
+ assert torch.equal(module.weight_scale, scale.reshape(-1)), layer
+ # `.proj.q` is a skip pattern: the forward reads its dtype, so it is folded with its scale applied.
+ for index in range(TINY_GEOMETRY["num_layers"]):
+ codes, scale = quantized[f"layers.{index}.proj.q"]
+ q = model.layers[index].proj["q"]
+ assert torch.equal(q.weight, codes.float() * scale), index
+ assert not hasattr(q, "weight_scale")
+ # What the forward reads the dtype of stays dense, bit for bit: the skip patterns' layers.
+ for key in (
+ "video_embedder.weight",
+ "text_embedder.proj.weight",
+ "time_embedding.0.weight",
+ "shared_block_modulation.weight",
+ "video_head_modulation.weight",
+ "final_linear_video.weight",
+ ):
+ assert torch.equal(model.state_dict()[key], dense[key]), key
+ # The rest of the dense layers stay dense too, even with FP8 Storage on: re-encoded as unscaled fp8 they
+ # underflow (`time_embedding.2` lost most of its weights), and the build ships them dense on purpose.
+ for key in (
+ "time_embedding.2.weight",
+ "time_embedding.2.bias",
+ *(
+ f"text_embedder.blocks.{i}.{part}.{name}"
+ for i in range(2)
+ for part in _TEXT_BLOCK_LINEARS
+ for name in ("weight", "bias")
+ ),
+ ):
+ assert torch.equal(model.state_dict()[key], dense[key]), key
+ meant = dict(dense)
+ loader._ram_cache.make_room.assert_called_once()
+
+ # The kept layers dequantize with their own per-row scale in the forward, as the cache runs them. The scales
+ # are far from uniform, so a dropped one or one paired with the wrong rows moves the output.
+ for layer, (codes, scale) in quantized.items():
+ meant[f"{layer}.weight"] = codes.float() * scale
+ apply_custom_layers_to_model(model)
+ torch.testing.assert_close(forward(model), forward(with_state_dict(meant)), rtol=1e-4, atol=1e-5)
+
+ @pytest.mark.parametrize(
+ ("kwargs", "kept"),
+ [
+ pytest.param({"keep_fp8": True}, True, id="kept-for-fp8-storage"),
+ pytest.param({"keep_fp8": False, "fp8_compute_only": True}, True, id="kept-for-fp8-compute"),
+ pytest.param({"keep_fp8": False}, False, id="folded"),
+ ],
+ )
+ def test_the_reservation_is_the_resident_size_plus_the_scales_the_load_holds(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, kwargs: dict[str, Any], kept: bool
+ ) -> None:
+ """The reservation the load asks for, counted from the fixture's shapes: the fp8 layers a file keeps at one byte per
+ element, `.proj.q` (read by dtype, so widened) and everything dense at the compute dtype, plus the scales held
+ on the side while the load runs (also on the folded path, where they are consumed afterwards)."""
+ path, dense, quantized = self._file(tmp_path)
+ compute = torch.bfloat16
+
+ _, loader, _ = self._load(monkeypatch, path, dtype=compute, **kwargs)
+
+ expected = sum(tensor.numel() * compute.itemsize for tensor in dense.values())
+ for layer, (codes, scale) in quantized.items():
+ stays_fp8 = kept and not layer.endswith(".proj.q")
+ expected += codes.numel() * (1 if stays_fp8 else compute.itemsize) + scale.numel() * scale.element_size()
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert reserved == expected
+
+ def test_without_anything_asking_for_fp8_every_layer_is_folded_to_the_codes_times_the_scale(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ path, dense, quantized = self._file(tmp_path)
+
+ model, _, _ = self._load(monkeypatch, path, keep_fp8=False)
+
+ assert [name for name, p in model.named_parameters() if p.dtype is not torch.float32] == []
+ for layer, (codes, scale) in quantized.items():
+ assert torch.equal(model.get_submodule(layer).weight, codes.float() * scale), layer
+
+ def test_a_folded_load_does_not_leave_parameters_pinning_the_file_mapping(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ """The dense tensors are stored in the compute dtype, so neither the fold nor the cast replaces them; assigned
+ as parameters they would be slices of the file's mapping, which the cache's size calculation cannot see."""
+ path, dense, _ = self._file(tmp_path)
+
+ model, _, loaded = self._load(monkeypatch, path, keep_fp8=False)
+
+ for name in ("video_embedder.weight", "layers.0.norm1.weight"):
+ parameter = model.get_parameter(name)
+ assert parameter.data_ptr() != loaded[name].data_ptr(), name
+ assert torch.equal(parameter, dense[name])
+
+ def test_a_kept_fp8_load_does_not_copy_the_codes(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ path, _, _ = self._file(tmp_path)
+
+ model, _, loaded = self._load(monkeypatch, path, keep_fp8=True)
+
+ codes = model.get_parameter("layers.0.proj.k.weight")
+ assert codes.data_ptr() == loaded["layers.0.proj.k._weight_qdata"].data_ptr()
+
+ def _refused(self, monkeypatch: pytest.MonkeyPatch, path: Path) -> Any:
+ loader = _loader(MossImageCheckpointModel, monkeypatch)
+ config = Main_Checkpoint_MossImage_Config.model_construct(path=str(path), name="moss")
+ with pytest.raises(ValueError, match="mixes torchao fp8 layers with other quantization keys") as raised:
+ loader._load_model(config, SubModelType.Transformer)
+ loader._ram_cache.make_room.assert_not_called()
+ return raised
+
+ def test_a_file_mixing_torchao_and_int8_layers_is_refused_before_anything_is_reserved(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ """The installer's twin: an I8 weight with its scale and marker beside the torchao pairs."""
+ path, _, _ = self._file(tmp_path)
+ stored = load_file(path)
+ stored["text_embedder.blocks.0.qkv.weight"] = torch.zeros(192, 64, dtype=torch.int8)
+ stored["text_embedder.blocks.0.qkv.weight_scale"] = torch.ones(192, 1)
+ stored["text_embedder.blocks.0.qkv.comfy_quant"] = comfy_quant_marker(CONVROT_MARKER)
+ save_file(stored, str(path))
+
+ self._refused(monkeypatch, path)
+
+ def test_a_stray_scale_beside_a_torchao_pair_is_refused_not_overwritten(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ path, _, _ = self._file(tmp_path)
+ stored = load_file(path)
+ stored["layers.0.proj.k.weight_scale"] = torch.ones(64)
+ save_file(stored, str(path))
+
+ self._refused(monkeypatch, path)
+
+ def test_a_plain_fp8_weight_without_a_scale_inside_a_torchao_file_is_refused(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ path, _, _ = self._file(tmp_path)
+ stored = load_file(path)
+ stored["text_embedder.blocks.0.qkv.weight"] = torch.zeros(192, 64).to(torch.float8_e4m3fn)
+ save_file(stored, str(path))
+
+ self._refused(monkeypatch, path)
+
+ def test_a_comfyui_scaled_fp8_layer_inside_a_torchao_file_is_refused(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ path, _, _ = self._file(tmp_path)
+ stored = load_file(path)
+ stored["text_embedder.blocks.0.qkv.weight"] = torch.zeros(192, 64).to(torch.float8_e4m3fn)
+ stored["text_embedder.blocks.0.qkv.weight_scale"] = torch.ones(192)
+ save_file(stored, str(path))
+
+ self._refused(monkeypatch, path)
+
+
class TestGGUFLoader:
"""unsloth's split layout and leejet's fused, metadata-free one, as real tiny GGUF files."""
diff --git a/tests/backend/moss_image/test_working_memory.py b/tests/backend/moss_image/test_working_memory.py
index a95f862787..394d85bf6d 100644
--- a/tests/backend/moss_image/test_working_memory.py
+++ b/tests/backend/moss_image/test_working_memory.py
@@ -61,14 +61,22 @@ def test_the_score_matrix_is_priced_for_the_whole_attended_sequence(monkeypatch:
"text_tokens": 7,
"score_matrix_bytes": 12345,
"dequant_bytes": 0,
+ "fp8_cast_bytes": 0,
"lora_sidecar_bytes": 0,
}
assert estimate.reservation_bytes == int(31 * k_token + 12345)
-def test_a_quantized_build_adds_its_dequant_transient() -> None:
+def test_a_quantized_build_adds_its_dequant_and_fp8_cast_transients() -> None:
values = {"k_token": 1000.0}
- features = {"height": 32, "width": 32, "text_tokens": 4, "score_matrix_bytes": 0, "dequant_bytes": 5000}
+ features = {
+ "height": 32,
+ "width": 32,
+ "text_tokens": 4,
+ "score_matrix_bytes": 0,
+ "dequant_bytes": 5000,
+ "fp8_cast_bytes": 7000,
+ }
terms = MOSS_IMAGE_DENOISE_SPEC.terms(features, values)
@@ -76,10 +84,42 @@ def test_a_quantized_build_adds_its_dequant_transient() -> None:
"activations": 8 * 1000.0,
"attention_scores": 0,
"dequant_transient": 5000,
+ "fp8_cast_transient": 7000,
"lora_sidecar": 0,
}
+def test_the_estimator_records_the_fp8_cast_transient_at_the_forwards_dtype() -> None:
+ transformer = _transformer()
+ layer = transformer.layers[0].proj["ffn_up_gate"]
+ layer.weight = torch.nn.Parameter(layer.weight.detach().to(torch.float8_e4m3fn), requires_grad=False)
+ layer.register_buffer("weight_scale", torch.ones(layer.weight.shape[0]), persistent=False)
+
+ estimate = estimate_moss_image_denoise_working_memory(
+ transformer,
+ height=32,
+ width=32,
+ text_tokens=4,
+ model_format=ModelFormat.Checkpoint,
+ device=torch.device("cpu"),
+ dtype=torch.bfloat16,
+ )
+
+ # ffn_up_gate is [2 * 96, 64]: its codes widen once, and again when the scale is applied.
+ assert estimate.features["fp8_cast_bytes"] == 2 * (2 * 96 * 64) * 2
+
+
+def test_a_forward_with_an_fp8_cast_transient_is_off_the_token_line() -> None:
+ features = {"height": 32, "width": 32, "text_tokens": 4, "score_matrix_bytes": 0, "dequant_bytes": 0}
+
+ on_line = module._line({**features, "fp8_cast_bytes": 0})
+ off_line = module._line({**features, "fp8_cast_bytes": 7000})
+
+ assert on_line is not None and on_line.fits
+ assert off_line is not None and not off_line.fits
+ assert "fp8_cast_transient=7000" in off_line.label
+
+
def test_points_measured_without_loras_have_no_lora_term() -> None:
"""The shipped points carry no `lora_sidecar_bytes`: a point without it prices no LoRA."""
features = {"height": 32, "width": 32, "text_tokens": 4, "score_matrix_bytes": 0, "dequant_bytes": 0}
@@ -133,4 +173,4 @@ def test_a_forward_with_a_lora_is_off_the_plain_line_the_fit_reads() -> None:
assert plain is not None and plain.fits
assert with_lora is not None and not with_lora.fits
- assert with_lora.label.endswith("lora_sidecar_bytes=4096")
+ assert with_lora.label.endswith("lora_sidecar=4096")