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.

25.6 KB
Raw Blame
"""Unit tests for the Krea-2 loader state-dict helpers.

These cover the pure key/tensor transforms that the single-file, GGUF and Qwen3-VL encoder loaders
run before ``load_state_dict`` (prefix stripping, native<->diffusers key conversion, scaled-fp8
dequantization, encoder key remapping) plus the shared ``_reject_incomplete_load`` guard that turns a
silent partial load into an actionable error. They exercise the conversion logic without needing the
real (diffusers ``Krea2Transformer2DModel`` / transformers ``Qwen3VLModel``) architectures or weights.
"""

import re
from types import SimpleNamespace

import accelerate
import pytest
import torch

from invokeai.backend.model_manager.load.model_loaders.krea2 import (
    KREA2_TRANSFORMER_CONFIG,
    _convert_krea2_native_to_diffusers,
    _drop_discarded_native_final_layers,
    _is_native_krea2_format,
    _normalize_qwen3vl_rope_config,
    _reject_incomplete_load,
    _remap_native_layer_paths,
    _remap_qwen3vl_singlefile_keys,
)
from invokeai.backend.quantization.fp8_scaled import (
    FP8_DTYPE,
    detach_layer_sidechannel,
    extract_fp8_scaled_layers,
    reattach_layer_sidechannel,
)
from invokeai.backend.quantization.int8_convrot import (
    CONVROT_GROUP_SIZE,
    build_regular_hadamard,
    drop_unconsumed_quantization_sidecars,
    extract_int8_convrot_markers,
    resolve_quantized_module_paths,
)


class TestNormalizeQwen3vlRopeConfig:
    def test_copies_rope_parameters_when_rope_scaling_is_missing(self) -> None:
        rope_parameters = {"rope_type": "default", "rope_theta": 1000000.0}
        text_config = SimpleNamespace(rope_parameters=rope_parameters, rope_scaling=None)
        config = SimpleNamespace(text_config=text_config)

        assert _normalize_qwen3vl_rope_config(config) is config
        assert text_config.rope_scaling == rope_parameters

    def test_preserves_existing_rope_scaling(self) -> None:
        existing = {"rope_type": "existing"}
        text_config = SimpleNamespace(rope_parameters={"rope_type": "new"}, rope_scaling=existing)
        config = SimpleNamespace(text_config=text_config)

        _normalize_qwen3vl_rope_config(config)

        assert text_config.rope_scaling is existing

    def test_accepts_config_without_a_text_config(self) -> None:
        config = SimpleNamespace()
        assert _normalize_qwen3vl_rope_config(config) is config


class TestIsNativeKrea2Format:
    @pytest.mark.parametrize(
        "key",
        ["blocks.0.attn.wq.weight", "txtfusion.0.mlp.up.weight", "first.weight", "blocks.0.mod.lin"],
    )
    def test_true_for_native_keys(self, key: str) -> None:
        assert _is_native_krea2_format({key: torch.zeros(1)}) is True

    @pytest.mark.parametrize(
        "key",
        ["transformer_blocks.0.attn.to_q.weight", "img_in.weight", "text_fusion.0.ff.up.weight"],
    )
    def test_false_for_diffusers_keys(self, key: str) -> None:
        assert _is_native_krea2_format({key: torch.zeros(1)}) is False


class TestConvertKrea2NativeToDiffusers:
    def test_top_level_module_renames(self) -> None:
        sd = {
            "first.weight": torch.zeros(1),
            "tmlp.0.weight": torch.zeros(1),
            "tmlp.2.weight": torch.zeros(1),
            "tproj.1.weight": torch.zeros(1),
            "txtmlp.0.scale": torch.zeros(1),
            "txtmlp.1.weight": torch.zeros(1),
            "txtmlp.3.weight": torch.zeros(1),
            "last.linear.weight": torch.zeros(1),
            "last.norm.scale": torch.zeros(1),
        }
        out = _convert_krea2_native_to_diffusers(sd)
        assert "img_in.weight" in out
        assert "time_embed.linear_1.weight" in out
        assert "time_embed.linear_2.weight" in out
        assert "time_mod_proj.weight" in out
        assert "txt_in.norm.weight" in out
        assert "txt_in.linear_1.weight" in out
        assert "txt_in.linear_2.weight" in out
        assert "final_layer.linear.weight" in out
        assert "final_layer.norm.weight" in out

    def test_within_block_renames(self) -> None:
        sd = {
            "blocks.0.attn.wq.weight": torch.zeros(1),
            "blocks.0.attn.wk.weight": torch.zeros(1),
            "blocks.0.attn.wv.weight": torch.zeros(1),
            "blocks.0.attn.wo.weight": torch.zeros(1),
            "blocks.0.attn.gate.weight": torch.zeros(1),
            "blocks.0.attn.qknorm.qnorm.scale": torch.zeros(1),
            "blocks.0.attn.qknorm.knorm.scale": torch.zeros(1),
            "blocks.0.mlp.gate.weight": torch.zeros(1),
            "blocks.0.mlp.up.weight": torch.zeros(1),
            "blocks.0.mlp.down.weight": torch.zeros(1),
            "blocks.0.prenorm.scale": torch.zeros(1),
            "blocks.0.postnorm.scale": torch.zeros(1),
            "txtfusion.1.attn.wq.weight": torch.zeros(1),
        }
        out = _convert_krea2_native_to_diffusers(sd)
        assert "transformer_blocks.0.attn.to_q.weight" in out
        assert "transformer_blocks.0.attn.to_k.weight" in out
        assert "transformer_blocks.0.attn.to_v.weight" in out
        assert "transformer_blocks.0.attn.to_out.0.weight" in out
        assert "transformer_blocks.0.attn.to_gate.weight" in out
        assert "transformer_blocks.0.attn.norm_q.weight" in out
        assert "transformer_blocks.0.attn.norm_k.weight" in out
        assert "transformer_blocks.0.ff.gate.weight" in out
        assert "transformer_blocks.0.ff.up.weight" in out
        assert "transformer_blocks.0.ff.down.weight" in out
        assert "transformer_blocks.0.norm1.weight" in out
        assert "transformer_blocks.0.norm2.weight" in out
        # text_fusion tower renamed the same way.
        assert "text_fusion.1.attn.to_q.weight" in out
        # No native names survive.
        assert not any(".wq." in k or ".qknorm." in k or ".mlp." in k or "prenorm" in k for k in out)

    def test_final_block_projections_are_dropped(self) -> None:
        sd = {"last.down.weight": torch.zeros(2, 2), "last.up.weight": torch.zeros(2, 2)}
        out = _convert_krea2_native_to_diffusers(sd)
        assert out == {}

    def test_mod_lin_is_reshaped_to_scale_shift_table(self) -> None:
        # A flat (6*H,) per-block modulation vector becomes a (6, H) scale_shift_table.
        sd = {"blocks.0.mod.lin": torch.arange(12, dtype=torch.float32)}
        out = _convert_krea2_native_to_diffusers(sd)
        assert "transformer_blocks.0.scale_shift_table" in out
        table = out["transformer_blocks.0.scale_shift_table"]
        assert table.shape == (6, 2)
        assert torch.equal(table, torch.arange(12, dtype=torch.float32).reshape(6, 2))

    def test_final_layer_modulation_is_reshaped_to_two_by_hidden(self) -> None:
        # Krea2FinalLayer.scale_shift_table is (2, hidden) (scale, shift). The flat native
        # last.modulation.lin must be reshaped (not merely renamed), otherwise load_state_dict(assign=True)
        # installs a wrong-shaped 1-D parameter that the meta-only completeness guard cannot catch and the
        # final layer fails at inference.
        sd = {"last.modulation.lin": torch.arange(8, dtype=torch.float32)}  # 2 * hidden, hidden=4
        out = _convert_krea2_native_to_diffusers(sd)
        assert "final_layer.scale_shift_table" in out
        table = out["final_layer.scale_shift_table"]
        assert table.shape == (2, 4)
        assert torch.equal(table, torch.arange(8, dtype=torch.float32).reshape(2, 4))

    def test_non_string_keys_pass_through(self) -> None:
        sentinel = object()
        out = _convert_krea2_native_to_diffusers({sentinel: torch.zeros(1)})  # type: ignore[dict-item]
        assert sentinel in out

    @pytest.mark.parametrize(
        "keys",
        [
            ("blocks.0.attn.wq.weight", "transformer_blocks.0.attn.to_q.weight"),
            ("transformer_blocks.0.attn.to_q.weight", "blocks.0.attn.wq.weight"),
        ],
    )
    def test_rejects_mixed_layout_alias_collision(self, keys: tuple[str, str]) -> None:
        # A malformed mixed-layout checkpoint carries a native key and its already-diffusers alias, both
        # normalizing to transformer_blocks.0.attn.to_q.weight. Distinct tensors under colliding aliases
        # must be rejected in either insertion order rather than silently dropping one.
        first, second = keys
        sd = {first: torch.zeros(1), second: torch.ones(1)}
        with pytest.raises(RuntimeError, match="both normalize to"):
            _convert_krea2_native_to_diffusers(sd)


class TestRemapQwen3vlSinglefileKeys:
    def test_routes_towers_and_prefixes_bare_language_model_keys(self) -> None:
        sd = {
            "model.visual.blocks.0.weight": torch.zeros(1),
            "model.language_model.layers.0.weight": torch.zeros(1),
            "model.layers.1.weight": torch.zeros(1),  # bare LM key under a model. prefix
            "model.embed_tokens.weight": torch.zeros(1),
            "model.norm.weight": torch.zeros(1),
            "visual.blocks.1.weight": torch.zeros(1),  # already un-prefixed
            "layers.2.weight": torch.zeros(1),  # bare, no model. prefix
        }
        out = _remap_qwen3vl_singlefile_keys(sd)
        assert "visual.blocks.0.weight" in out
        assert "language_model.layers.0.weight" in out
        assert "language_model.layers.1.weight" in out
        assert "language_model.embed_tokens.weight" in out
        assert "language_model.norm.weight" in out
        assert "visual.blocks.1.weight" in out
        assert "language_model.layers.2.weight" in out
        # No key retains the leading model. prefix.
        assert not any(k.startswith("model.") for k in out)

    @pytest.mark.parametrize(
        "keys",
        [
            ("model.layers.1.weight", "layers.1.weight"),
            ("layers.1.weight", "model.layers.1.weight"),
        ],
    )
    def test_rejects_mixed_layout_alias_collision(self, keys: tuple[str, str]) -> None:
        # A bare LM key and its model.-prefixed alias both route to language_model.layers.1.weight.
        # Distinct tensors under colliding aliases must be rejected in either order, not silently merged.
        first, second = keys
        sd = {first: torch.zeros(1), second: torch.ones(1)}
        with pytest.raises(RuntimeError, match="both normalize to"):
            _remap_qwen3vl_singlefile_keys(sd)


class TestRejectIncompleteLoad:
    @pytest.mark.parametrize(
        "what",
        ["Krea-2 single-file checkpoint", "Krea-2 GGUF checkpoint", "Qwen3-VL encoder checkpoint"],
    )
    def test_raises_when_parameters_remain_on_meta_device(self, what: str) -> None:
        # accelerate.init_empty_weights() leaves every parameter on the meta device — the exact state a
        # strict=False load produces for a checkpoint that omits required weights. All three Krea-2 loaders
        # feed their `what` label through this guard, so parametrize over the real call-site messages.
        with accelerate.init_empty_weights():
            model = torch.nn.Linear(4, 4)
        with pytest.raises(RuntimeError, match=re.escape(f"{what} is incomplete")):
            _reject_incomplete_load(model, what=what)

    def test_does_not_raise_for_a_fully_materialized_model(self) -> None:
        model = torch.nn.Linear(4, 4)  # normal construction — no meta tensors
        _reject_incomplete_load(model, what="Krea-2 single-file checkpoint")

    def test_names_the_missing_parameters(self) -> None:
        # Materialize only the weight; the bias stays on meta and must be named in the error.
        with accelerate.init_empty_weights():
            model = torch.nn.Linear(4, 4)
        model.load_state_dict({"weight": torch.zeros(4, 4)}, strict=False, assign=True)
        with pytest.raises(RuntimeError, match="bias") as exc_info:
            _reject_incomplete_load(model, what="Krea-2 single-file checkpoint")
        assert "1 tensor(s)" in str(exc_info.value)

    def test_raises_for_a_persistent_buffer_left_on_meta(self) -> None:
        # Buffers land on the meta device too; a native/GGUF checkpoint that omits a persistent buffer
        # must be rejected. The parameter here is fully materialized, so a parameters-only guard would
        # wrongly pass - only the buffer check catches it.
        class _ModuleWithMetaBuffer(torch.nn.Module):
            def __init__(self) -> None:
                super().__init__()
                self.weight = torch.nn.Parameter(torch.zeros(2, 2))
                self.register_buffer("cached_stat", torch.empty(4, device="meta"))

        model = _ModuleWithMetaBuffer()
        with pytest.raises(RuntimeError, match="cached_stat"):
            _reject_incomplete_load(model, what="Krea-2 GGUF checkpoint")


def _native_key_for_scale_shift_table(diffusers_key: str) -> str:
    """Inverse of the converter's ``.mod.lin``/``last.modulation.lin`` -> ``.scale_shift_table`` mapping.

    Only the modulation tables are reshaped by ``_convert_krea2_native_to_diffusers`` (every other
    conversion is a pure, shape-preserving rename), so these are the only keys whose converted shape can
    silently disagree with the real ``Krea2Transformer2DModel`` module dims.
    """
    stem = diffusers_key[: -len(".scale_shift_table")]
    if stem == "final_layer":
        return "last.modulation.lin"
    if stem.startswith("transformer_blocks."):
        return "blocks." + stem[len("transformer_blocks.") :] + ".mod.lin"
    if stem.startswith("text_fusion."):
        return "txtfusion." + stem[len("text_fusion.") :] + ".mod.lin"
    raise AssertionError(f"unmapped scale_shift_table key: {diffusers_key}")


class TestConvertedShapesMatchRealKrea2Transformer:
    """Validate the native->diffusers converter against the REAL ``Krea2Transformer2DModel`` module.

    The loader boundary tests use a tiny stub transformer, so they cannot detect a converted tensor whose
    shape disagrees with the real module: ``load_state_dict(assign=True)`` installs whatever shape the
    converter produced (no shape check) and ``_reject_incomplete_load`` only inspects the meta device, not
    shapes, so a wrong-shaped tensor survives load and fails only at inference. The concrete instance is
    ``last.modulation.lin`` -> ``final_layer.scale_shift_table``: the real table is ``(2, hidden)`` and the
    flat native vector must be reshaped, not merely renamed.
    """

    def test_scale_shift_tables_match_real_module_dims(self) -> None:
        pytest.importorskip("diffusers")
        from diffusers import Krea2Transformer2DModel

        with accelerate.init_empty_weights():
            model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)

        # Meta-device state dict still carries real shapes for every parameter/buffer.
        expected = {name: tuple(t.shape) for name, t in model.state_dict().items()}
        table_keys = [name for name in expected if name.endswith(".scale_shift_table")]
        assert table_keys, "real Krea2Transformer2DModel exposes no scale_shift_table params"
        assert "final_layer.scale_shift_table" in table_keys
        assert any(k.startswith("transformer_blocks.") for k in table_keys)

        # Build a native state dict covering every modulation-table site, sized (as a flat vector) from the
        # real module dims, then convert and assert the reshaped result matches the real parameter shape.
        native_sd = {}
        for name in table_keys:
            rows, hidden = expected[name]
            native_sd[_native_key_for_scale_shift_table(name)] = torch.arange(rows * hidden, dtype=torch.float32)

        out = _convert_krea2_native_to_diffusers(native_sd)

        for name in table_keys:
            assert name in out, f"converter did not produce {name}"
            assert tuple(out[name].shape) == expected[name], (
                f"{name}: converted shape {tuple(out[name].shape)} != real module shape {expected[name]}"
            )

        # The two named layouts from the review: final layer AdaLN table is (2, hidden); every per-block
        # (transformer + text-fusion) table is (6, hidden). A regression that dropped the reshape would leave
        # these 1-D and this would fail.
        assert expected["final_layer.scale_shift_table"][0] == 2
        for name in table_keys:
            if name.startswith(("transformer_blocks.", "text_fusion.")):
                assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"


def _quantized_int8_layer(path: str, weight: torch.Tensor) -> dict:
    """A convrot-rotated int8 layer in the native key spelling, as Comfy-Org ships it."""
    import json

    out_f, in_f = weight.shape
    h = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)
    rotated = (weight.view(out_f, in_f // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ h.T).view(out_f, in_f)
    scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0
    marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})
    return {
        f"{path}.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),
        f"{path}.weight_scale": scale.to(torch.float32),
        f"{path}.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8),
    }


class TestInt8LayersSurviveTheLoaderPipeline:
    """Two steps between the file and the model would quietly ruin an int8 layer.

    Neither fails loudly if it is broken - both produce a state dict that loads cleanly and
    generates noise - so each is pinned by a test that shows the damage.
    """

    def test_the_key_conversion_renames_the_scale_but_orphans_the_marker(self) -> None:
        """Why the module paths are resolved by following the weight's own rename rather than the
        marker's key: the within-block renames are substring replacements of `.attn.wq.weight`,
        which `.weight_scale` contains and `.comfy_quant` does not."""
        torch.manual_seed(1)
        sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))

        converted = _convert_krea2_native_to_diffusers(sd)

        assert "transformer_blocks.0.attn.to_q.weight" in converted
        assert "transformer_blocks.0.attn.to_q.weight_scale" in converted
        assert "transformer_blocks.0.attn.wq.comfy_quant" in converted
        assert "transformer_blocks.0.attn.to_q.comfy_quant" not in converted

    def test_the_marker_is_re_keyed_onto_the_module_the_weight_landed_on(self) -> None:
        torch.manual_seed(2)
        sd = _quantized_int8_layer("blocks.0.attn.wq", torch.randn(32, CONVROT_GROUP_SIZE))
        markers = extract_int8_convrot_markers(sd)

        key_map: dict[str, str] = {}
        _convert_krea2_native_to_diffusers(sd, key_map=key_map)

        assert resolve_quantized_module_paths(markers, key_map) == {
            "transformer_blocks.0.attn.to_q": markers["blocks.0.attn.wq"]
        }

    def test_a_diffusers_named_checkpoint_needs_no_re_keying(self) -> None:
        """No conversion runs, so the empty map has to resolve to the paths as they are."""
        markers = {"transformer_blocks.0.attn.to_q": {"format": "int8_tensorwise"}}
        assert resolve_quantized_module_paths(markers, {}) == markers


class TestUnconsumedQuantizationSidecars:
    def test_markers_and_activation_scales_are_dropped(self) -> None:
        """`input_scale` is an activation scale for W8A8 inference; this code dequantizes the
        weight and computes in bf16, so there is nothing to apply it to. One Qwen3-VL repack
        ships 337 of them, under a spelling the previous filter did not match."""
        sd = {
            "layer.weight": torch.ones(2, 2),
            "layer.comfy_quant": torch.zeros(4, dtype=torch.uint8),
            "layer.input_scale": torch.ones(1),
            "other.scale_input": torch.ones(1),
        }
        assert set(drop_unconsumed_quantization_sidecars(sd)) == {"layer.weight"}

    def test_a_clean_state_dict_is_unchanged(self) -> None:
        sd = {"layer.weight": torch.ones(2, 2), "layer.bias": torch.zeros(2)}
        assert set(drop_unconsumed_quantization_sidecars(sd)) == set(sd)


class TestDiscardedFinalProjections:
    def test_the_dropped_projections_take_their_quantization_metadata_with_them(self) -> None:
        """`last.down`/`last.up` have no diffusers counterpart, and one real repack quantizes
        `last.up` with a scale layout the decode refuses. Dropping them before the decode keeps a
        tensor that is on its way to the bin from failing the load."""
        sd = {
            "last.up.weight": torch.zeros(4, 4, dtype=torch.int8),
            "last.up.weight_scale": torch.ones(2, 2),
            "last.up.comfy_quant": torch.zeros(8, dtype=torch.uint8),
            "last.down.weight": torch.zeros(4, 4),
            "last.linear.weight": torch.ones(4, 4),
        }
        out = _drop_discarded_native_final_layers(sd)
        assert set(out) == {"last.linear.weight"}

    def test_a_state_dict_without_them_is_returned_unchanged(self) -> None:
        sd = {"last.linear.weight": torch.ones(2, 2)}
        assert _drop_discarded_native_final_layers(sd) is sd


class TestEverySuffixSurvivesTheKeyConversion:
    """A quantized layer travels as three keys, and the converter has to move all of them.

    The within-block renames are substring replacements of `.attn.wq.weight`, so `.weight_scale`
    rides along by construction. The top-level renames are prefix slices, so they carry any
    suffix. `last.linear` used to be neither -- an exact match per suffix, which silently left
    `last.linear.weight_scale` under its old name.
    """

    @pytest.mark.parametrize(
        ("native", "diffusers"),
        [
            ("blocks.0.attn.wq", "transformer_blocks.0.attn.to_q"),
            ("blocks.3.mlp.down", "transformer_blocks.3.ff.down"),
            ("txtfusion.refiner_blocks.1.attn.wv", "text_fusion.refiner_blocks.1.attn.to_v"),
            ("first", "img_in"),
            ("tmlp.0", "time_embed.linear_1"),
            ("tmlp.2", "time_embed.linear_2"),
            ("tproj.1", "time_mod_proj"),
            ("txtmlp.1", "txt_in.linear_1"),
            ("txtmlp.3", "txt_in.linear_2"),
            ("last.linear", "final_layer.linear"),
        ],
    )
    def test_the_weight_and_its_scale_land_on_the_same_module(self, native: str, diffusers: str) -> None:
        sd = {f"{native}.weight": torch.zeros(4, 4, dtype=torch.int8), f"{native}.weight_scale": torch.ones(4, 1)}
        key_map: dict[str, str] = {}
        out = _convert_krea2_native_to_diffusers(sd, key_map=key_map)

        assert f"{diffusers}.weight" in out
        assert f"{diffusers}.weight_scale" in out, "the scale was left behind under its old name"
        assert key_map[f"{native}.weight"] == f"{diffusers}.weight"


class TestNativeConversionCarriesTheQuantizationSideChannel:
    """Regression guard for scales orphaned by the native -> diffusers rename.

    `_convert_krea2_native_to_diffusers` renames `.weight` keys by substring *and* renames five
    more by whole-key equality. Neither carries a sibling scale: `.scale_weight` and `.input_scale`
    do not contain `.weight`, and `last.linear.weight_scale` is not equal to `last.linear.weight`.
    An orphaned scale is then dropped by `extract_fp8_scaled_layers` (no fp8 weight sits at the old
    path any more) and the weight is left quantized but unscaled - off by exactly 1/weight_scale,
    with nothing logged, because the layer never enters `fp8_layers` for
    `warn_on_unattached_scales` to see.
    """

    @staticmethod
    def _convert(sd: dict) -> dict:
        detached = detach_layer_sidechannel(sd)
        converted = _convert_krea2_native_to_diffusers(sd)
        orphaned = reattach_layer_sidechannel(converted, detached, _remap_native_layer_paths(set(detached)))
        return converted, orphaned

    def test_every_spelling_and_rename_style_survives(self) -> None:
        fp8 = torch.ones(4, 4).to(FP8_DTYPE)
        sd = {
            # substring rename, `.weight_scale` spelling
            "blocks.0.attn.wq.weight": fp8.clone(),
            "blocks.0.attn.wq.weight_scale": torch.tensor(0.5),
            "blocks.0.attn.wq.input_scale": torch.tensor(0.25),
            # substring rename, `.scale_weight` spelling
            "blocks.0.attn.wk.weight": fp8.clone(),
            "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),
            # whole-key-equality rename
            "last.linear.weight": fp8.clone(),
            "last.linear.weight_scale": torch.tensor(0.5),
        }

        converted, orphaned = self._convert(sd)
        layers = extract_fp8_scaled_layers(converted)

        assert set(layers) == {
            "transformer_blocks.0.attn.to_q",
            "transformer_blocks.0.attn.to_k",
            "final_layer.linear",
        }
        assert orphaned == []
        # The calibrated activation scale must come across too, or every forward pays an amax pass.
        assert layers["transformer_blocks.0.attn.to_q"].input_scale is not None

    def test_no_fp8_weight_is_left_without_its_scale(self) -> None:
        """The property that actually matters, stated directly."""
        fp8 = torch.ones(4, 4).to(FP8_DTYPE)
        sd = {
            "blocks.0.attn.wk.weight": fp8.clone(),
            "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),
            "last.linear.weight": fp8.clone(),
            "last.linear.weight_scale": torch.tensor(0.5),
        }

        converted, _ = self._convert(sd)
        layers = extract_fp8_scaled_layers(converted)

        unscaled = [
            key
            for key, value in converted.items()
            if key.endswith(".weight")
            and getattr(value, "dtype", None) is FP8_DTYPE
            and key[: -len(".weight")] not in layers
        ]
        assert unscaled == []

    def test_a_scale_on_a_dropped_module_is_reported(self) -> None:
        """`last.down`/`last.up` have no diffusers counterpart, so their scales go too - loudly."""
        sd = {
            "last.down.weight": torch.ones(4, 4).to(FP8_DTYPE),
            "last.down.weight_scale": torch.tensor(0.5),
        }

        _, orphaned = self._convert(sd)

        assert orphaned == ["last.down"]