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.

fix(fp8): make the RAM prediction split-aware, pin the two unpinned folds

Alexander Eichhorn9cd24e03b09b
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index 5cb9e08ce7..9af0d2c24c 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -208,10 +208,18 @@ class AnimaCheckpointModel(ModelLoader):
# strips a scale that can no longer be put back.
# Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
# subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. The prediction is unaffected by the split -- it applies the same
- # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ predict_cast_state_dict_size(
+ sd,
+ model_dtype,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ scaled_layers=fp8_layers,
+ )
)
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 6a51db4e7c..7e1dfc9a8a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -776,11 +776,17 @@ class FluxCheckpointModel(ModelLoader):
# `cast_state_dict` never strips a scale that can no longer be put back.
# Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
# subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. The prediction is unaffected by the split -- it applies the same
- # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
predict_cast_state_dict_size(
- sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns
+ sd,
+ torch.bfloat16,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ scaled_layers=fp8_layers,
)
)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index c2e67acab0..b82e514a43 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -411,10 +411,18 @@ class Krea2CheckpointModel(ModelLoader):
# ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.
# Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
# subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. The prediction is unaffected by the split -- it applies the same
- # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ predict_cast_state_dict_size(
+ sd,
+ model_dtype,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ scaled_layers=fp8_layers,
+ )
)
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
@@ -712,7 +720,12 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
source_is_fp8 = bool(fp8_layers) or any(
getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
)
- if fp8_layers and not should_keep_fp8_weights(target_device):
+ # Resolved once. `device_supports_fp8_matmul` deliberately does not cache an inconclusive
+ # probe, so two calls can disagree: a transient failure here followed by a success below
+ # would leave the scales already folded while the raw Linears stay quantized, i.e. the
+ # encoder silently on the storage path with the matmul log line never printed.
+ keep_matmul_fp8 = should_keep_fp8_weights(target_device)
+ if fp8_layers and not keep_matmul_fp8:
# Legacy behavior: fold the scales into the weights. Without the fp8 matmul, staying
# quantized would save VRAM but cost speed, so the two are tied to the same setting.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
@@ -734,11 +747,18 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
#
# `split_fp8_scaled_layers` applies exactly those filters and dequantizes the affected
# layers *with* their scale, so what remains is what the matmul can actually consume.
- keep_fp8 = should_keep_fp8_weights(target_device)
+ # The storage path below re-quantizes to fp8 anyway, so casting the raw fp8 Linears to
+ # `model_dtype` here would double both this reservation and the host-RAM peak (~4.4 -> ~8.9
+ # GiB on the 4B encoder) for a round trip that ends where it started -- e4m3fn is a subset
+ # of bf16, so it is value-exact. Keep them for either consumer.
+ use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)
+ keep_fp8 = keep_matmul_fp8 or use_fp8_storage
# Reserve before the split: it dequantizes its unusable subset through fp32, so reserving
- # afterwards lets that transient peak land on an unreserved cache. The prediction is
- # unaffected -- it applies the same `can_stay_quantized` predicate.
- self._ram_cache.make_room(predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model))
+ # afterwards lets that transient peak land on an unreserved cache. `scaled_layers` keeps the
+ # prediction in step with the split's own scale-layout filter.
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)
+ )
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)
cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)
@@ -785,7 +805,7 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# excludes text encoders (and the config has no fp8_storage toggle), so apply the hook-based
# casting directly here. This roughly halves the encoder's resident VRAM (~8.9GB bf16 ->
# ~4.4GB), which avoids partial-load thrashing when it shares the GPU with a large transformer.
- if source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger):
+ if use_fp8_storage:
# `model.dtype` now reports the float8 storage dtype; `_apply_fp8_to_nn_module` records
# the real compute dtype so callers can recover it via `get_model_compute_dtype`.
self._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=model_dtype)
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 95c3d663e8..62f175f0e5 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -558,10 +558,18 @@ class ZImageCheckpointModel(ModelLoader):
# `cast_state_dict` never strips a scale it cannot put back.
# Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
# subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. The prediction is unaffected by the split -- it applies the same
- # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
+ # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
- predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ predict_cast_state_dict_size(
+ sd,
+ model_dtype,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ scaled_layers=fp8_layers,
+ )
)
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
@@ -1018,6 +1026,37 @@ class ZImageControlCheckpointModel(ModelLoader):
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.Checkpoint)
+def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:
+ """Fold every ComfyUI-style ``weight_scale`` into its weight, in place. Returns how many.
+
+ ComfyUI stores quantized weights with accompanying scale factors (``layer.weight`` quantized,
+ ``layer.weight_scale`` the factor, both spellings), so ``dequantized = weight * weight_scale``.
+ See https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md.
+
+ A named function rather than a loop inside the loader so the scale-axis contract below is
+ reachable from a test. `expand_weight_scale` handles all three layouts (per-tensor,
+ per-output-channel, block-wise); the local loop this replaced left a 1-D per-channel scale
+ untouched, and ``(out, in) * (out,)`` then broadcasts on the *last* axis — scaling input
+ channels instead of output channels, which is a shape error on a non-square weight and a
+ silently wrong weight on a square one.
+
+ The multiply runs in float32 for precision but each result is stored as ``dtype`` immediately,
+ so the whole model is never materialized in float32: holding every dequantized weight at fp32
+ until the caller's later cast quadruples the per-parameter cost (4 bytes vs 1 on disk) and
+ dominates the cold-load RAM peak — enough to swap a 32 GB machine. Same fix as in the FLUX.2
+ and Krea-2 loaders.
+ """
+ folded = 0
+ for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):
+ # Float8 needs `.float()`; torch has no direct type promotion for it.
+ weight_float = sd[weight_key].float()
+ scale = expand_weight_scale(weight_float, sd[scale_key].float())
+ sd[weight_key] = (weight_float * scale).to(dtype)
+ del weight_float
+ folded += 1
+ return folded
+
+
class Qwen3EncoderCheckpointLoader(ModelLoader):
"""Class to load single-file Qwen3 Encoder models for Z-Image (safetensors format)."""
@@ -1082,32 +1121,7 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# Dequantization formula: dequantized = weight.to(dtype) * weight_scale
# Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md
original_key_count = len(sd)
- dequantized_count = 0
-
- # Both spellings, because the metadata strip below removes both.
- for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):
- weight = sd[weight_key]
- scale = sd[scale_key]
- # Dequantize: convert to float and multiply by scale
- # Handle block-wise quantization (e.g., FP4 with block_size=8)
- # where scale has shape [weight_dim / block_size, ...]
- # Note: Float8 types (e.g., float8_e4m3fn) require .float() instead of .to(torch.float32)
- # as PyTorch doesn't support direct type promotion for Float8 types
- weight_float = weight.float()
- # `expand_weight_scale` handles all three layouts (per-tensor, per-output-channel,
- # block-wise). The local loop it replaces left a 1-D per-channel scale untouched, and
- # `(out, in) * (out,)` then broadcasts on the *last* axis -- scaling input channels
- # instead of output channels, which is wrong on a square weight and a shape error on
- # any other.
- scale = expand_weight_scale(weight_float, scale.float())
- # Multiply in float32 for precision, but store the compute dtype immediately so the
- # *whole model* is never materialized in float32. Keeping every dequantized weight as
- # float32 until the caller's later cast quadruples the per-parameter cost (4 bytes vs
- # 1 on disk) and dominates the cold-load RAM peak — enough to swap a 32 GB machine.
- # Same fix as in the FLUX.2 and Krea-2 loaders.
- sd[weight_key] = (weight_float * scale).to(model_dtype)
- del weight_float
- dequantized_count += 1
+ dequantized_count = _fold_comfy_scaled_weights(sd, model_dtype)
if dequantized_count > 0:
logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index d9e3a32991..c14340fc88 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -409,6 +409,17 @@ def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tens
if scale.numel() == 1:
return scale
if scale.dim() <= 1:
+ if scale.numel() != weight.shape[0]:
+ # A 1-D scale is per-output-channel by definition, so any other length means the file
+ # does not describe this weight — most likely a block-wise scale flattened by the
+ # producer, whose block structure is not recoverable from the tensor alone. Say so:
+ # left to broadcast, torch raises "size of tensor a (32) must match tensor b (7)" from
+ # inside the multiply, which names neither the layer nor the file.
+ raise ValueError(
+ f"fp8 weight_scale has {scale.numel()} entries but the weight has {weight.shape[0]} output "
+ "channels; the scale is neither per-tensor nor per-output-channel and cannot be applied. "
+ "The checkpoint's quantization metadata appears to be malformed."
+ )
return scale.reshape(-1, *([1] * (weight.dim() - 1)))
for dim in range(weight.dim()):
if dim < scale.dim() and scale.shape[dim] != weight.shape[dim]:
@@ -779,6 +790,38 @@ def can_stay_quantized(
)
+def scaled_layer_for(key: Any, scaled_layers: Mapping[str, "Fp8ScaledLayer"] | None) -> "Fp8ScaledLayer | None":
+ """The recovered scale for the module whose ``.weight`` this key is, if there is one."""
+ if not scaled_layers or not isinstance(key, str) or not key.endswith(".weight"):
+ return None
+ return scaled_layers.get(key[: -len(".weight")])
+
+
+def survives_split_and_cast(
+ key: str,
+ tensor: Any,
+ model: torch.nn.Module | None,
+ skip_patterns: Iterable[str] = (),
+ layer: "Fp8ScaledLayer | None" = None,
+) -> bool:
+ """Whether this entry is *still* fp8 after both :func:`split_fp8_scaled_layers` and
+ :func:`cast_state_dict` have run over it.
+
+ :func:`can_stay_quantized` answers only for the cast. The split applies one filter more — a
+ scale layout :func:`scaled_mm_linear` cannot use — so a block-wise-scaled 2-D Linear weight
+ passes ``can_stay_quantized`` and is nonetheless widened to ``dtype``. Predicting RAM with the
+ weaker predicate therefore charges 1 byte/element for a tensor that ends up at 2, and the loaders
+ reserve half of what they need. This is the predicate both the split and the prediction use, so
+ the two cannot drift.
+
+ ``layer`` is None for a raw fp8 weight (no ``weight_scale`` at all); there is no layout to
+ reject, and the tensor-core path takes it with unit scaling.
+ """
+ if not can_stay_quantized(key, tensor, model, skip_patterns):
+ return False
+ return layer is None or is_matmul_usable_scale(tensor, layer.weight_scale)
+
+
def _is_castable_float(tensor: Any) -> bool:
"""Whether ``tensor`` is a floating-point payload that may be cast to the compute dtype."""
is_floating_point = getattr(tensor, "is_floating_point", None)
@@ -834,19 +877,27 @@ def predict_cast_state_dict_size(
keep_fp8: bool,
model: torch.nn.Module | None = None,
skip_patterns: Iterable[str] = (),
+ scaled_layers: Mapping[str, Fp8ScaledLayer] | None = None,
) -> int:
- """Bytes the state dict will occupy once :func:`cast_state_dict` has run over it.
+ """Bytes the state dict will occupy once the split and :func:`cast_state_dict` have run over it.
Loaders call this to size their ``make_room()`` reservation. Charging 1 byte/element for every
fp8 tensor is wrong in the direction that hurts: only 2-D ``nn.Linear`` weights outside the skip
patterns stay quantized, and everything else — biases, norms, learned pad tokens, the
deliberately-dequantized precision-sensitive Linears — lands at ``dtype.itemsize``. On a
checkpoint that quantized all 453 of its tensors that under-count is most of the difference.
+
+ ``scaled_layers`` is the mapping the caller is about to hand :func:`split_fp8_scaled_layers`.
+ Pass it: the reservation is made *before* the split (so the split's own fp32 transient lands on
+ a reserved cache), and the split widens every layer whose scale layout ``scaled_mm`` cannot
+ apply. Without the mapping those layers are predicted at 1 byte/element and arrive at 2 — on a
+ block-wise-scaled checkpoint that is the entire quantized-Linear set.
"""
patterns = tuple(skip_patterns)
total = 0
for key, tensor in sd.items():
- if (keep_fp8 and can_stay_quantized(key, tensor, model, patterns)) or not _is_castable_float(tensor):
+ stays = keep_fp8 and survives_split_and_cast(key, tensor, model, patterns, scaled_layer_for(key, scaled_layers))
+ if stays or not _is_castable_float(tensor):
total += tensor.nelement() * tensor.element_size()
else:
total += tensor.nelement() * dtype.itemsize
@@ -877,9 +928,10 @@ def split_fp8_scaled_layers(
A scale layout :func:`scaled_mm_linear` cannot apply — block-wise, or a vector that does not
match the weight's row count — is dequantized here too. Left quantized it would fail inside the
- kernel mid-generation instead. Doing it here rather than in :func:`can_stay_quantized` keeps the
- RAM accounting honest: every caller runs this before
- :func:`predict_cast_state_dict_size`, so the prediction sees the already-widened tensor.
+ kernel mid-generation instead. That filter lives here rather than in :func:`can_stay_quantized`
+ because it needs the recovered scale, which the cast never sees. The RAM prediction runs
+ *before* this function, so it has to account for the same widening — it does, via the shared
+ :func:`survives_split_and_cast`, provided the caller passes it ``scaled_layers``.
``float8_e5m2`` layers land here by way of :func:`can_stay_quantized`, which admits only
``float8_e4m3fn`` — they are dequantized *with* their scale applied rather than losing it.
@@ -890,11 +942,7 @@ def split_fp8_scaled_layers(
for path, layer in layers.items():
key = f"{path}.weight"
tensor = sd.get(key)
- if (
- tensor is not None
- and can_stay_quantized(key, tensor, model, patterns)
- and is_matmul_usable_scale(tensor, layer.weight_scale)
- ):
+ if tensor is not None and survives_split_and_cast(key, tensor, model, patterns, layer):
usable[path] = layer
else:
unusable[path] = layer
diff --git a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
new file mode 100644
index 0000000000..2f08cb7a9e
--- /dev/null
+++ b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
@@ -0,0 +1,92 @@
+"""Per-call-site guards for the scale axis used when folding a scaled-fp8 weight.
+
+A per-output-channel `weight_scale` is 1-D of length `out_features`, and `(out, in) * (out,)`
+broadcasts on the *last* axis — so a bare multiply scales input channels instead of output
+channels. That is a shape error on a non-square weight (loud) and a silently wrong weight on a
+square one (not loud at all). Both loaders below used to do the bare multiply; they now go through
+`expand_weight_scale`.
+
+`test_fp8_scaled.py` covers the helper itself. These pin the two call sites, so reverting either
+one back to its local loop fails a test rather than passing CI.
+"""
+
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import _drop_quantization_metadata
+from invokeai.backend.model_manager.load.model_loaders.z_image import _fold_comfy_scaled_weights
+
+
+def _per_channel_case(out_features: int = 4, in_features: int = 2):
+ """A non-square weight with a per-output-channel scale: rows 0..n-1 scaled by 1..n."""
+ weight = torch.ones(out_features, in_features).to(torch.float8_e4m3fn)
+ scale = torch.arange(1, out_features + 1, dtype=torch.float32)
+ expected = torch.arange(1, out_features + 1, dtype=torch.bfloat16).reshape(-1, 1).expand(-1, in_features)
+ return weight, scale, expected
+
+
+class TestMistralEncoderFold:
+ def test_per_channel_scale_multiplies_rows(self) -> None:
+ weight, scale, expected = _per_channel_case()
+ sd = {"layer.weight": weight, "layer.weight_scale": scale}
+
+ _drop_quantization_metadata(sd, MagicMock(), target_dtype=torch.bfloat16)
+
+ assert torch.equal(sd["layer.weight"], expected)
+ assert "layer.weight_scale" not in sd
+
+ def test_square_weight_is_not_silently_transposed(self) -> None:
+ """The dangerous case: a square weight broadcasts happily on the wrong axis."""
+ sd = {
+ "layer.weight": torch.ones(3, 3).to(torch.float8_e4m3fn),
+ "layer.weight_scale": torch.tensor([1.0, 2.0, 3.0]),
+ }
+
+ _drop_quantization_metadata(sd, MagicMock(), target_dtype=torch.bfloat16)
+
+ rows = torch.tensor([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]], dtype=torch.bfloat16)
+ assert torch.equal(sd["layer.weight"], rows), "scale must vary down the rows, not across them"
+
+
+class TestZImageQwen3EncoderFold:
+ """The Z-Image Qwen3 encoder's single-file loader folds the same way."""
+
+ def _fold(self, sd: dict, dtype: torch.dtype = torch.bfloat16) -> dict:
+ # The real call site. It was a loop inside `_load_from_singlefile` -- unreachable without a
+ # checkpoint and a transformers model -- so it was extracted; re-inlining it as a local
+ # multiply fails these tests instead of passing CI.
+ _fold_comfy_scaled_weights(sd, dtype)
+ return sd
+
+ def test_per_channel_scale_multiplies_rows(self) -> None:
+ weight, scale, expected = _per_channel_case()
+ sd = self._fold({"layer.weight": weight, "layer.weight_scale": scale})
+ assert torch.equal(sd["layer.weight"], expected)
+
+ def test_non_square_weight_does_not_raise(self) -> None:
+ weight, scale, _ = _per_channel_case(out_features=6, in_features=2)
+ sd = self._fold({"layer.weight": weight, "layer.weight_scale": scale})
+ assert sd["layer.weight"].shape == (6, 2)
+
+ def test_block_wise_scale_is_expanded_rather_than_rejected(self) -> None:
+ sd = self._fold(
+ {
+ "layer.weight": torch.ones(4, 2).to(torch.float8_e4m3fn),
+ "layer.weight_scale": torch.tensor([[1.0], [2.0]]), # one entry per 2-row block
+ }
+ )
+ assert torch.equal(
+ sd["layer.weight"],
+ torch.tensor([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.0, 2.0]], dtype=torch.bfloat16),
+ )
+
+ def test_a_scale_matching_neither_layout_is_reported(self) -> None:
+ with pytest.raises(ValueError, match="neither per-tensor nor per-output-channel"):
+ self._fold(
+ {
+ "layer.weight": torch.ones(4, 2).to(torch.float8_e4m3fn),
+ "layer.weight_scale": torch.full((3,), 2.0),
+ }
+ )
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index fe2d92acc8..13a5a43250 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -1170,3 +1170,123 @@ class TestExpandWeightScaleAxis:
# Without the expansion this is a broadcast error, not merely a wrong number.
assert (weight * expand_weight_scale(weight, torch.arange(4, dtype=torch.float32))).shape == (4, 2)
+
+
+class TestPredictionIsSplitAware:
+ """`make_room` runs before `split_fp8_scaled_layers`, so the prediction has to account for what
+ the split widens — not just for what the cast keeps.
+
+ `can_stay_quantized` knows nothing about the scale *layout*. A block-wise-scaled 2-D
+ `nn.Linear.weight` passes it, gets predicted at 1 byte/element, and is then dequantized to
+ `dtype` by the split at 2 — the reservation is half the truth, and on a real checkpoint using
+ that layout the shortfall is the whole quantized-Linear set.
+ """
+
+ def _model(self):
+ model = torch.nn.Sequential()
+ model.add_module("lin", torch.nn.Linear(16, 32))
+ return model
+
+ @pytest.mark.parametrize(
+ "label, scale, stays_fp8",
+ [
+ ("per-tensor", torch.tensor(2.0), True),
+ ("per-output-channel", torch.full((32,), 2.0), True),
+ ("block-wise", torch.full((8, 2), 2.0), False),
+ ],
+ )
+ def test_prediction_matches_the_bytes_left_after_split_and_cast(self, label, scale, stays_fp8):
+ model = self._model()
+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE), "lin.weight_scale": scale}
+ layers = extract_fp8_scaled_layers(sd)
+
+ predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)
+ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)
+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model)
+ actual = sum(t.nelement() * t.element_size() for t in sd.values())
+
+ assert predicted == actual, f"{label}: reserved {predicted}, needed {actual}"
+ assert bool(remaining) is stays_fp8
+ assert (sd["lin.weight"].dtype is FP8_DTYPE) is stays_fp8
+
+ def test_without_the_mapping_the_block_wise_layer_is_under_counted(self):
+ """The regression itself: omitting `scaled_layers` reverts to the weaker predicate."""
+ model = self._model()
+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE), "lin.weight_scale": torch.full((8, 2), 2.0)}
+ layers = extract_fp8_scaled_layers(sd)
+
+ blind = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model)
+ aware = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)
+ assert aware == 2 * blind
+
+ def test_raw_fp8_without_any_scale_is_unaffected(self):
+ """A weight with no `weight_scale` has no layout to reject; it stays fp8 either way."""
+ model = self._model()
+ sd = {"lin.weight": torch.zeros(32, 16).to(FP8_DTYPE)}
+ with_map = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers={})
+ without = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model)
+ assert with_map == without == 32 * 16
+
+
+class TestQwen3VlStyleSplit:
+ """Pins the helper contract the Qwen3-VL encoder switched to.
+
+ Its old per-key `if dtype is not FP8_DTYPE` loop kept *every* fp8 tensor quantized. The three
+ things that got wrong are all visible without any `transformers` dependency, against a stub
+ module tree.
+ """
+
+ def _model(self):
+ model = torch.nn.Module()
+ model.add_module("norm", torch.nn.LayerNorm(32))
+ model.add_module("lin", torch.nn.Linear(16, 32))
+ model.add_module("plain", torch.nn.Linear(16, 32))
+ return model
+
+ def test_scaled_norm_is_folded_and_block_wise_linear_is_dropped(self):
+ model = self._model()
+ norm_scale = torch.tensor(4.0)
+ sd = {
+ # A 1-D fp8 norm carrying a scale: not a matmul weight, so it must be folded, not kept.
+ "norm.weight": torch.ones(32).to(FP8_DTYPE),
+ "norm.weight_scale": norm_scale,
+ # A Linear whose scale layout `scaled_mm` cannot apply: folded too.
+ "lin.weight": torch.ones(32, 16).to(FP8_DTYPE),
+ "lin.weight_scale": torch.full((8, 2), 2.0),
+ # A Linear the matmul can take: survives, and is what `attach_fp8_scales` gets.
+ "plain.weight": torch.ones(32, 16).to(FP8_DTYPE),
+ "plain.weight_scale": torch.tensor(3.0),
+ }
+ layers = extract_fp8_scaled_layers(sd)
+ assert set(layers) == {"norm", "lin", "plain"}
+
+ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)
+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model)
+
+ assert set(remaining) == {"plain"}, "only the matmul-usable Linear may keep its scale"
+ # The norm was dequantized *with* its scale applied — the old loop left it as raw fp8 codes.
+ assert sd["norm.weight"].dtype is torch.bfloat16
+ assert torch.allclose(sd["norm.weight"], torch.full((32,), 4.0, dtype=torch.bfloat16))
+ assert sd["lin.weight"].dtype is torch.bfloat16
+ assert sd["plain.weight"].dtype is FP8_DTYPE
+
+ def test_e5m2_scaled_weight_keeps_its_scale_on_the_way_down(self):
+ """Only e4m3fn may stay quantized, so an e5m2 weight must be folded rather than cast bare."""
+ model = self._model()
+ sd = {
+ "plain.weight": torch.ones(32, 16).to(torch.float8_e5m2),
+ "plain.weight_scale": torch.tensor(3.0),
+ }
+ layers = extract_fp8_scaled_layers(sd)
+ remaining = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)
+
+ assert remaining == {}
+ assert torch.allclose(sd["plain.weight"], torch.full((32, 16), 3.0, dtype=torch.bfloat16))
+
+
+class TestMalformedWeightScale:
+ def test_a_1d_scale_of_the_wrong_length_is_reported_not_broadcast(self):
+ """Neither per-tensor nor per-output-channel. Left to torch, the multiply raises "size of
+ tensor a (32) must match tensor b (7)" from inside the fold, naming neither layer nor file."""
+ with pytest.raises(ValueError, match="neither per-tensor nor per-output-channel"):
+ expand_weight_scale(torch.ones(32, 16), torch.full((7,), 2.0))