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.

62.3 KB
Raw Blame
"""Tests for `ModelLoader` FP8 helpers.

Covers:
- `_should_use_fp8` excludes ControlLoRA (the LoRA loader never runs the layerwise
  casting helper, and a LoRA isn't a standalone forward module — so a persisted
  `fp8_storage=true` must be a no-op).
- `_wrap_forward_with_fp8_cast` uses pre/post hooks with `always_call=True`, so it is
  exception-safe AND survives `apply_custom_layers_to_model`'s instance swap. Without
  hooks, an instance-level `forward` override would be carried into the new CustomLinear
  via the shared `__dict__` and silently bypass `CustomLinear.forward` — breaking LoRA
  patch dispatch for FP8 checkpoint models.
- `_apply_fp8_to_nn_module` skips precision-sensitive layers (norm, pos_embed, etc.)
  so FLUX RMSNorm.scale and friends aren't crushed to FP8.
"""

import copy
from contextlib import contextmanager
from logging import getLogger
from types import SimpleNamespace
from unittest.mock import patch

import pytest
import torch

from invokeai.backend.model_manager.load.load_default import (
    _FP8_PROBE_FAILURE_REPORTED,
    _FP8_STORAGE_SUPPORTED,
    ModelLoader,
    _device_supports_fp8_storage,
    _model_declared_skip_patterns,
)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (
    CustomLinear,
)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
    apply_custom_layers_to_model,
)
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR
from tests.fixtures.loader_seams import FP8_STORAGE_SKIPPED
from tests.fixtures.quantized_payloads import nvfp4_codes, nvfp4_tensors

_MISSING = object()

# `WanTransformer3DModel` at a size that builds in milliseconds; the structure is the real one.
WAN_TINY_KWARGS = {
    "patch_size": (1, 2, 2),
    "in_channels": 16,
    "out_channels": 16,
    "num_layers": 2,
    "attention_head_dim": 128,
    "num_attention_heads": 1,
    "ffn_dim": 64,
    "text_dim": 32,
}


def _make_loader(device: str = "cuda") -> ModelLoader:
    """Build a ModelLoader without going through dependency injection.

    `_should_use_fp8` and `_wrap_forward_with_fp8_cast` only depend on `_torch_device`,
    so we instantiate via __new__ and set the minimum state directly.
    """
    loader = ModelLoader.__new__(ModelLoader)
    loader._torch_device = torch.device(device)
    loader._torch_dtype = torch.float16
    loader._logger = getLogger("test")
    return loader


def _make_config(
    model_type: ModelType,
    fp8: bool,
    base: BaseModelType = BaseModelType.Flux,
    fmt: ModelFormat = ModelFormat.Diffusers,
):
    """A stand-in for a model record.

    `format` is not optional here, as it is not optional on a real config: `Config_Base` refuses a
    concrete class that does not declare base, type and format, and the gate now asks all three --
    whether the loader for that key implements the cast is part of the answer
    (`load/fp8_capability.py`). A double without a format would be a shape production never sees.
    """
    return SimpleNamespace(
        type=model_type,
        base=base,
        format=fmt,
        name="test",
        default_settings=SimpleNamespace(fp8_storage=fp8),
    )


def _make_quantized_config(fmt: ModelFormat = ModelFormat.GGUFQuantized):
    """A config whose `format` is one of the already-quantized ones."""
    return _make_config(ModelType.Main, fp8=True, fmt=fmt)


_STORAGE_PROBE = "invokeai.backend.model_manager.load.load_default._device_supports_fp8_storage"


@contextmanager
def _device_holds_fp8():
    """Answer the storage probe True.

    For the tests that ask *which* models opt into fp8, or what the cast does to a model that did.
    Neither question is about whether a device can hold float8, and the answer has to be supplied
    because the probe is real now: the CUDA branch used to be answered True without asking, which is
    why these tests used to pass on a runner with no driver. One that has none rightly fails it.
    """
    with patch(_STORAGE_PROBE, return_value=True):
        yield


@pytest.mark.parametrize(
    "config,submodel",
    [
        (_make_config(ModelType.VAE, fp8=True), None),
        (_make_config(ModelType.LoRA, fp8=True), None),
        # Z-Image used to be listed here. It is no longer excluded — see
        # `test_should_use_fp8_allows_z_image` for why the exclusion became obsolete.
        # A quantized model takes its place: its guard must also sit ahead of the device probe.
        (_make_quantized_config(), None),
        (_make_config(ModelType.Main, fp8=True), SubModelType.Tokenizer),
        (_make_config(ModelType.Main, fp8=False), None),
    ],
)
def test_should_use_fp8_does_not_probe_the_device_for_excluded_models(config, submodel):
    """The device probe must run only for a model that actually wants FP8.

    It allocates on the GPU, so probing before the exclusions fires it on the very first load of
    any kind -- a tokenizer, a VAE, a scheduler -- and on API/install threads it forces XPU lazy
    SYCL init on a thread that never generates.
    """
    loader = _make_loader("xpu")
    with patch(_STORAGE_PROBE) as mock_probe:
        assert loader._should_use_fp8(config, submodel) is False
    mock_probe.assert_not_called()


def test_should_use_fp8_probes_the_device_when_fp8_is_requested():
    loader = _make_loader("xpu")
    config = _make_config(ModelType.Main, fp8=True)
    with patch(_STORAGE_PROBE, return_value=True) as mock_probe:
        assert loader._should_use_fp8(config, None) is True
    mock_probe.assert_called_once()
    # The key/build answer stays frozen. A fresh load can observe a new capability verdict.
    with patch(_STORAGE_PROBE, return_value=False):
        assert loader._should_use_fp8(config, None) is True
        assert _make_loader("xpu")._should_use_fp8(config, None) is False


def test_should_use_fp8_excludes_control_lora():
    """ControlLoRA gets the FP8 toggle in the UI history but the LoRA loader never applies
    layerwise casting (the model isn't run as a standalone forward pass — it patches into a
    base model). The loader must silently ignore a persisted `fp8_storage=true` to avoid
    misleading users who toggled it under a prior version.
    """
    loader = _make_loader(device="cuda")
    with patch("torch.cuda.is_available", return_value=True):
        assert loader._should_use_fp8(_make_config(ModelType.ControlLoRa, fp8=True)) is False


def test_should_use_fp8_excludes_lora():
    loader = _make_loader(device="cuda")
    assert loader._should_use_fp8(_make_config(ModelType.LoRA, fp8=True)) is False


def test_should_use_fp8_returns_true_for_main_with_fp8():
    loader = _make_loader(device="cuda")
    with _device_holds_fp8():
        assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True)) is True


def test_should_use_fp8_returns_false_for_main_without_fp8():
    loader = _make_loader(device="cuda")
    assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=False)) is False


def test_should_use_fp8_returns_false_on_cpu():
    loader = _make_loader(device="cpu")
    assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True)) is False


@pytest.mark.parametrize(
    "submodel_type",
    [SubModelType.PromptEnhancer, SubModelType.PromptEnhancerTokenizer],
)
def test_should_use_fp8_excludes_prompt_enhancer(submodel_type: SubModelType):
    """The ERNIE-Image prompt enhancer is a causal LM driven by `generate()` — one full forward per
    generated token, so layerwise casting pays the bf16<->fp8 round trip on every token of the
    rewritten prompt, on top of fp8 rounding a model whose whole job is text quality. It must be
    excluded like the text encoders, even though the parent Main config has `fp8_storage=true`.
    """
    loader = _make_loader(device="cuda")
    config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.ErnieImage)
    with _device_holds_fp8():
        assert loader._should_use_fp8(config, submodel_type) is False
        # Sanity: the same config *does* opt the transformer in, so the assertion above is about the
        # submodel exclusion and not about the config failing to enable fp8 at all.
        assert loader._should_use_fp8(config, SubModelType.Transformer) is True


class _RaisingModule(torch.nn.Module):
    """A module whose forward unconditionally raises — used to test that the FP8 wrapper's
    storage-dtype cleanup runs even when forward fails."""

    def __init__(self):
        super().__init__()
        self.weight = torch.nn.Parameter(torch.zeros(4))
        self.bias = torch.nn.Parameter(torch.zeros(4))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        raise RuntimeError("boom")


def _fp8_supported() -> bool:
    return hasattr(torch, "float8_e4m3fn")


@pytest.mark.skipif(not _fp8_supported(), reason="torch.float8_e4m3fn not available")
def test_wrap_forward_restores_storage_dtype_on_exception():
    """When forward raises, params must be returned to storage dtype. Otherwise FP8 storage
    savings silently revert to fp16/bf16 and the cache's size accounting becomes stale.
    """
    storage_dtype = torch.float8_e4m3fn
    compute_dtype = torch.bfloat16

    module = _RaisingModule()
    for p in module.parameters(recurse=False):
        p.data = p.data.to(storage_dtype)

    ModelLoader._wrap_forward_with_fp8_cast(module, compute_dtype)

    # Sanity: params start in storage dtype.
    assert module.weight.dtype == storage_dtype
    assert module.bias.dtype == storage_dtype

    with pytest.raises(RuntimeError, match="boom"):
        module(torch.zeros(4, dtype=compute_dtype))

    # Critical assertion: cleanup ran despite the exception.
    assert module.weight.dtype == storage_dtype
    assert module.bias.dtype == storage_dtype


@pytest.mark.skipif(not _fp8_supported(), reason="torch.float8_e4m3fn not available")
def test_wrap_forward_casts_to_compute_then_back_on_success():
    """Happy-path sanity check: params are in compute dtype during forward, storage dtype after."""
    storage_dtype = torch.float8_e4m3fn
    compute_dtype = torch.bfloat16

    seen_dtypes: list[torch.dtype] = []

    class _CaptureModule(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.weight = torch.nn.Parameter(torch.zeros(4))

        def forward(self, x: torch.Tensor) -> torch.Tensor:
            seen_dtypes.append(self.weight.dtype)
            return x + self.weight

    module = _CaptureModule()
    for p in module.parameters(recurse=False):
        p.data = p.data.to(storage_dtype)

    ModelLoader._wrap_forward_with_fp8_cast(module, compute_dtype)

    module(torch.zeros(4, dtype=compute_dtype))

    assert seen_dtypes == [compute_dtype]
    assert module.weight.dtype == storage_dtype


@pytest.mark.skipif(not _fp8_supported(), reason="torch.float8_e4m3fn not available")
def test_the_forward_puts_the_stored_weights_back_rather_than_re_quantizing():
    """The exit must restore the same tensors, or the cache's RAM copy is orphaned.

    `CachedModelWithPartialLoad` snapshots `model.state_dict()` at `put()` and charges the RAM
    budget from it. A post-hook that re-derived the storage dtype with `.to()` allocated new
    storage, so from the first forward on, every CPU-resident param pointed at a private copy
    while that snapshot pinned the original: both live, 2 bytes per element against a budget that
    still said 1, for as long as the weights stayed in RAM.
    """
    model = torch.nn.Sequential(*[torch.nn.Linear(64, 64, bias=False) for _ in range(4)]).to(torch.bfloat16)
    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
    cached = model.state_dict()

    model(torch.randn(1, 64, dtype=torch.bfloat16))

    for name, snapshot in cached.items():
        param = model.get_parameter(name)
        assert param.dtype is torch.float8_e4m3fn, name
        assert param.data_ptr() == snapshot.data_ptr(), f"{name}: the RAM snapshot now pins a second copy"


@pytest.mark.skipif(not _fp8_supported(), reason="torch.float8_e4m3fn not available")
def test_a_doubly_wrapped_module_still_ends_with_the_weights_stored():
    """Only the outermost hook pair may restore, which is what the depth counter is for.

    `_apply_fp8_to_nn_module` carries no idempotency guard of its own — the marker check lives in
    its caller — so a second pass over the same tree registers a second hook pair. Without the
    counter the inner pre-hook records the *widened* weight as the stored one and the module stays
    in compute dtype for good: fp8 storage silently off, and the cache under-counting it by half.
    """
    model = torch.nn.Sequential(torch.nn.Linear(8, 8, bias=False)).to(torch.bfloat16)
    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
    cached = model.state_dict()
    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
    assert len(model[0]._forward_pre_hooks) == 2, "the premise is a module wrapped twice"

    model(torch.randn(1, 8, dtype=torch.bfloat16))

    assert model[0].weight.dtype is torch.float8_e4m3fn
    assert model[0].weight.data_ptr() == cached["0.weight"].data_ptr()


@pytest.mark.skipif(not _fp8_supported(), reason="torch.float8_e4m3fn not available")
def test_a_widening_that_runs_out_of_memory_leaves_the_weights_stored():
    """The widening is the likeliest allocation here to fail, and it must not strand the module.

    It asks for twice the param's storage on a device the cache deliberately drives to its ceiling.
    `always_call=True` runs the post-hook when it raises, so the record of what the params held has
    to be in place before the first cast — otherwise the already-widened ones stay widened, and the
    next forward records *those* as the stored ones, which makes it permanent.
    """
    module = torch.nn.Linear(8, 8).to(torch.bfloat16)
    for p in module.parameters(recurse=False):
        p.data = p.data.to(torch.float8_e4m3fn)
    cached = {name: p.data for name, p in module.named_parameters()}
    ModelLoader._wrap_forward_with_fp8_cast(module, torch.bfloat16)

    real_to = torch.Tensor.to
    calls = {"n": 0}

    def failing_to(self, *args, **kwargs):
        # Fail on the second widening, so one param is already widened when it raises.
        if args and args[0] is torch.bfloat16:
            calls["n"] += 1
            if calls["n"] == 2:
                raise torch.OutOfMemoryError("probe")
        return real_to(self, *args, **kwargs)

    with patch.object(torch.Tensor, "to", failing_to), pytest.raises(torch.OutOfMemoryError):
        module(torch.randn(1, 8, dtype=torch.bfloat16))

    for name, param in module.named_parameters():
        assert param.dtype is torch.float8_e4m3fn, name
        assert param.data_ptr() == cached[name].data_ptr(), f"{name}: restored a copy, not the stored tensor"


def test_apply_fp8_to_nn_module_uses_wrapper():
    """`_apply_fp8_to_nn_module` should delegate per-module wrapping to
    `_wrap_forward_with_fp8_cast`, which encapsulates the hook registration.
    """
    module = torch.nn.Linear(4, 4)
    with patch.object(ModelLoader, "_wrap_forward_with_fp8_cast") as mock_wrap:
        ModelLoader._apply_fp8_to_nn_module(module, torch.float16, torch.float32)
    mock_wrap.assert_called_once_with(module, torch.float32)


def test_apply_fp8_to_nn_module_skips_norm_modules():
    """Modules whose path matches `norm` must not be cast — diffusers' `enable_layerwise_casting`
    does the same. FLUX RMSNorm.scale is the canonical example: a tiny learned scalar that
    breaks badly in FP8.
    """

    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.norm1 = torch.nn.LayerNorm(4)
            self.linear = torch.nn.Linear(4, 4)

    storage_dtype = torch.float16
    compute_dtype = torch.float32
    model = _Model()
    for p in model.parameters():
        p.data = p.data.to(compute_dtype)

    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)

    # Linear params get cast to storage dtype.
    assert model.linear.weight.dtype == storage_dtype
    # Norm params stay in compute dtype — they must not be cast.
    assert model.norm1.weight.dtype == compute_dtype
    assert model.norm1.bias.dtype == compute_dtype


def test_apply_fp8_to_nn_module_skips_pos_embed_and_proj_in_out():
    """Position embeddings and the in/out projection of transformer blocks are also on the
    diffusers default skip list — they're precision-sensitive.
    """

    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.pos_embed = torch.nn.Linear(4, 4)
            self.proj_in = torch.nn.Linear(4, 4)
            self.proj_out = torch.nn.Linear(4, 4)
            self.attn = torch.nn.Linear(4, 4)

    storage_dtype = torch.float16
    compute_dtype = torch.float32
    model = _Model()
    for p in model.parameters():
        p.data = p.data.to(compute_dtype)

    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)

    assert model.attn.weight.dtype == storage_dtype
    assert model.pos_embed.weight.dtype == compute_dtype
    assert model.proj_in.weight.dtype == compute_dtype
    assert model.proj_out.weight.dtype == compute_dtype


def test_apply_fp8_to_nn_module_skips_unsupported_layer_types():
    """Only the layer classes in `_FP8_SUPPORTED_PYTORCH_LAYERS` are cast — matches diffusers'
    behavior. A custom RMSNorm-style module with a raw Parameter must be left alone, otherwise
    its learned scalar gets clobbered.
    """

    class _ScaleModule(torch.nn.Module):
        """Mimics FLUX RMSNorm — a tiny learned scalar that must not be cast to FP8."""

        def __init__(self):
            super().__init__()
            self.scale = torch.nn.Parameter(torch.ones(4))

        def forward(self, x: torch.Tensor) -> torch.Tensor:
            return x * self.scale

    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.rms = _ScaleModule()
            self.linear = torch.nn.Linear(4, 4)

    storage_dtype = torch.float16
    compute_dtype = torch.float32
    model = _Model()
    for p in model.parameters():
        p.data = p.data.to(compute_dtype)

    ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)

    assert model.linear.weight.dtype == storage_dtype
    # Critical: the RMS-style scalar lives on a custom module type, not in the supported list.
    assert model.rms.scale.dtype == compute_dtype


def test_apply_fp8_to_nn_module_honors_extra_skip_patterns():
    """A model's own `_skip_layerwise_casting_patterns` must be applied on top of our defaults."""

    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.t_embedder = torch.nn.Linear(4, 4)
            self.attn = torch.nn.Linear(4, 4)

    storage_dtype = torch.float16
    compute_dtype = torch.float32
    model = _Model()
    for p in model.parameters():
        p.data = p.data.to(compute_dtype)

    ModelLoader._apply_fp8_to_nn_module(
        model, storage_dtype, compute_dtype, extra_skip_patterns=("t_embedder", "cap_embedder")
    )

    assert model.attn.weight.dtype == storage_dtype
    assert model.t_embedder.weight.dtype == compute_dtype


def test_apply_fp8_layerwise_casting_passes_model_declared_skip_patterns():
    """Regression test for Z-Image + fp8 crashing with
    `RuntimeError: "addmm_cuda" not implemented for 'Float8_e4m3fn'`.

    Diffusers models declare precision-sensitive modules in `_skip_layerwise_casting_patterns`, and
    `enable_layerwise_casting()` honors them. Our hook-based replacement must read that list too —
    it is not redundant with `_FP8_DEFAULT_SKIP_PATTERNS`. `ZImageTransformer2DModel` declares
    `['t_embedder', 'cap_embedder']` because `TimestepEmbedder.forward` reads
    `self.mlp[0].weight.dtype` and casts its *input* to it: with an fp8 weight the input becomes
    float8 before the pre-hook restores the weight, and `F.linear` has no float8 kernel.
    """

    class _FakeZImage(torch.nn.Module):
        _skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]

        def __init__(self):
            super().__init__()
            self.t_embedder = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 4))
            self.cap_embedder = torch.nn.Linear(4, 4)
            self.layers = torch.nn.Linear(4, 4)

    loader = _make_loader(device="cuda")
    model = _FakeZImage().to(torch.bfloat16)

    with patch.object(ModelLoader, "_should_use_fp8", return_value=True):
        loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage))

    # The declared modules keep their compute dtype...
    assert model.t_embedder[0].weight.dtype == torch.bfloat16
    assert model.cap_embedder.weight.dtype == torch.bfloat16
    # ...while everything else is stored in fp8, so the toggle still saves VRAM.
    assert model.layers.weight.dtype == torch.float8_e4m3fn


def test_anima_transformer_declares_t_embedder_skip():
    """Regression guard for Anima + FP8 rendering a heavily dithered image.

    `AnimaTransformer.t_embedder` produces the `adaln_lora` conditioning consumed by every block,
    so casting it to FP8 corrupts every token of every block — verified against a bf16 run at the
    same seed/steps/CFG. None of the generic `_FP8_DEFAULT_SKIP_PATTERNS` match it (this
    architecture doesn't use diffusers' module names), so the model has to declare it itself.
    """
    from invokeai.backend.anima.anima_transformer import AnimaTransformer

    assert "t_embedder" in AnimaTransformer._skip_layerwise_casting_patterns

    # And the declared patterns actually reach the cast, matched against dotted module paths.
    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.t_embedder = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 4))
            self.blocks = torch.nn.Linear(4, 4)

    model = _Model().to(torch.float32)
    ModelLoader._apply_fp8_to_nn_module(
        model,
        storage_dtype=torch.float16,
        compute_dtype=torch.float32,
        extra_skip_patterns=tuple(AnimaTransformer._skip_layerwise_casting_patterns),
    )

    assert model.t_embedder[0].weight.dtype == torch.float32
    assert model.blocks.weight.dtype == torch.float16


@pytest.mark.parametrize(
    "fmt",
    [
        ModelFormat.GGUFQuantized,
        ModelFormat.BnbQuantizednf4b,
        ModelFormat.BnbQuantizedLlmInt8b,
        ModelFormat.SDNQQuantized,
    ],
)
def test_should_use_fp8_excludes_quantized_formats(fmt: ModelFormat):
    """Already-quantized weights must never be re-encoded as FP8.

    Casting them is not a no-op: GGUF raises `Operation changed the dtype of GGMLTensor
    unexpectedly`, and bnb NF4 corrupts silently (`bnb.nn.LinearNF4` subclasses `nn.Linear`, so its
    packed uint8 payload is cast to float8 and inference then returns finite garbage).

    """
    loader = _make_loader(device="cuda")
    config = _make_config(ModelType.Main, fp8=True)
    config.format = fmt
    assert loader._should_use_fp8(config) is False


def test_apply_fp8_skips_quantized_params_regardless_of_format():
    """Backstop behind the format check, for quantization the model's format does not reveal
    (e.g. a `diffusers`-format checkpoint quantized by an external tool).

    Both signals are covered: a non-floating-point payload (bnb's packed uint8) and a
    `torch.Tensor` subclass (GGUF's `GGMLTensor`).
    """

    class _FakeQuantTensor(torch.Tensor):
        """Stands in for GGMLTensor: a Tensor subclass carrying a quantized payload."""

    class _Model(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.packed = torch.nn.Linear(4, 4, bias=False)  # bnb-style uint8 payload
            self.subclassed = torch.nn.Linear(4, 4, bias=False)  # GGUF-style tensor subclass
            # NB: not `normal` — that would be caught by the `norm` skip pattern.
            self.attn = torch.nn.Linear(4, 4, bias=False)

    model = _Model().to(torch.bfloat16)
    model.packed.weight = torch.nn.Parameter(torch.zeros(8, 1, dtype=torch.uint8), requires_grad=False)
    model.subclassed.weight = torch.nn.Parameter(
        torch.zeros(4, 4, dtype=torch.bfloat16).as_subclass(_FakeQuantTensor), requires_grad=False
    )

    ModelLoader._apply_fp8_to_nn_module(model, torch.float8_e4m3fn, torch.bfloat16)

    assert model.packed.weight.dtype == torch.uint8
    assert not model.packed._forward_pre_hooks, "a quantized layer must not get cast hooks either"
    assert model.subclassed.weight.dtype == torch.bfloat16
    assert not model.subclassed._forward_pre_hooks
    # Control: an ordinary layer in the same model is still cast.
    assert model.attn.weight.dtype == torch.float8_e4m3fn


def test_should_use_fp8_allows_z_image():
    """Z-Image was excluded while we used diffusers' `enable_layerwise_casting()` with the global
    torch dtype (fp16) as compute dtype, which clashed with the model's bf16 weights. The compute
    dtype now comes from the model itself, so the exclusion is obsolete.
    """
    loader = _make_loader(device="cuda")
    with _device_holds_fp8():
        assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage)) is True


def test_should_use_fp8_refuses_a_loader_that_declared_it_does_not_implement_the_cast():
    """A Z-Image ControlNet asks for fp8 and its loader does not implement the cast, so the gate must say no.

    Not the same question as the one above: Z-Image *main* implements the cast. Both are
    `base=z-image`, which is why the answer cannot live on the architecture -- it lives on the
    loader key, and `ZImageFunControlNetLoader` declares `Unimplemented` there.

    The device probe must not run for it either: an inert request is no reason to touch the GPU.
    """
    loader = _make_loader(device="cuda")
    config = _make_config(ModelType.ControlNet, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)
    with patch(_STORAGE_PROBE) as mock_probe:
        assert loader._should_use_fp8(config) is False
    mock_probe.assert_not_called()


def test_an_inert_fp8_request_is_reported_rather_than_ignored(caplog):
    """The setting survives on records that predate the declarations -- identification used to set it
    itself for any float8 denoiser -- and such a loader never reaches `_should_use_fp8` at all. So the
    load says once why nothing happened, which is the one thing the silent version never did.
    """
    loader = _make_loader(device="cuda")
    config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.MiniMaxH3, fmt=ModelFormat.Checkpoint)

    with caplog.at_level("INFO", logger="test"):
        loader._report_inert_fp8_request(config, SubModelType.Transformer)
    assert "does nothing here" in caplog.text
    assert "mixed-precision islands" in caplog.text

    caplog.clear()
    # Not for the components that were never going to be cast, or a Main model would repeat itself
    # once per submodel, nor for a model that asked for nothing.
    with caplog.at_level("INFO", logger="test"):
        loader._report_inert_fp8_request(config, SubModelType.Tokenizer)
        loader._report_inert_fp8_request(_make_config(ModelType.Main, fp8=False), SubModelType.Transformer)
        loader._report_inert_fp8_request(_make_config(ModelType.Main, fp8=True), SubModelType.Transformer)
    assert caplog.text == ""


def test_wrap_forward_reaches_custom_linear_after_apply_custom_layers():
    """Production order: `_load_model` applies FP8 wrapping, THEN `ModelCache.put()` calls
    `apply_custom_layers_to_model` which constructs a NEW `CustomLinear` object via
    `CustomLinear.__new__` and points its `__dict__` at the original `Linear.__dict__`
    (see `wrap_custom_layer`). The new object is installed on the parent in place of the
    original Linear.

    An instance-level `forward` override would be carried into the new CustomLinear via the
    shared dict but would close over the OLD Linear instance — so calls to the new
    CustomLinear would silently route to `Linear.forward(old_instance, ...)` and bypass
    `CustomLinear.forward`, where LoRA/ControlLoRA patches are applied. This is the bug a
    reviewer reproduced on a fresh worktree.

    Hooks fix this because `nn.Module._call_impl` dispatches them with the *actual* called
    instance, and `self.forward(...)` is resolved by normal class lookup — reaching
    `CustomLinear.forward`. This test exercises the production wrapping path (real
    `apply_custom_layers_to_model`) and asserts CustomLinear.forward is reached by attaching
    a sentinel patch list and observing that the patch-aware branch runs.
    """

    class Parent(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.child = torch.nn.Linear(4, 4, bias=False)

    parent = Parent()
    original_linear = parent.child

    ModelLoader._wrap_forward_with_fp8_cast(original_linear, torch.float32)

    apply_custom_layers_to_model(parent)
    new_child = parent.child

    # Sanity: production wrapping replaced the child with a NEW CustomLinear instance.
    assert isinstance(new_child, CustomLinear)
    assert new_child is not original_linear

    # Attach a sentinel patch so CustomLinear.forward routes through the LoRA-aware branch
    # (see custom_linear.py: `if len(self._patches_and_weights) > 0`). If that branch fires,
    # our FP8 wrapping is correctly dispatched through CustomLinear.forward.
    patch_was_invoked = {"hit": False}

    class _SentinelPatch:
        def __init__(self):
            self.hit = patch_was_invoked

        def __call__(self, *_args, **_kwargs):  # not actually called
            pass

    # Patch the CustomLinear's patch-handling branch to record that it was reached.
    original_patch_branch = CustomLinear._autocast_forward_with_patches

    def tracked_patch_branch(self, input):
        patch_was_invoked["hit"] = True
        # Return a same-shape tensor so the outer caller doesn't choke.
        return torch.zeros_like(input @ self.weight.t())

    new_child._patches_and_weights = [(_SentinelPatch(), 1.0)]
    try:
        CustomLinear._autocast_forward_with_patches = tracked_patch_branch
        _ = new_child(torch.zeros(1, 4, dtype=torch.float32))
    finally:
        CustomLinear._autocast_forward_with_patches = original_patch_branch
        new_child._patches_and_weights = []

    assert patch_was_invoked["hit"] is True, (
        "FP8-wrapped forward did not reach CustomLinear.forward — LoRA/ControlLoRA patches "
        "would be silently bypassed on FP8 checkpoint models."
    )


def test_apply_fp8_layerwise_casting_uses_hook_path_for_model_mixin():
    """Regression test for the FLUX.2 Klein 9B partial-load device-mismatch crash.

    Diffusers' `enable_layerwise_casting()` registers a `LayerwiseCastingHook` whose
    `pre_forward` only casts dtype (not device) and whose hook system replaces
    `Linear.forward` with a wrapper that calls the *original* `Linear.forward` captured
    before the hook was installed. `ModelCache.put()` later wraps Linear as CustomLinear
    sharing `__dict__`, so the diffusers wrapper is carried into the new CustomLinear and
    routes calls to the captured original Linear.forward — bypassing
    `CustomLinear.forward`'s `cast_to_device`. On partial load (some weights on CPU,
    input on cuda), this raises a device-mismatch error.

    The fix routes ModelMixin through `_apply_fp8_to_nn_module` (hook-based,
    `forward`-preserving). This test asserts that path is taken even when the model
    inherits from ModelMixin.
    """
    from diffusers.models.modeling_utils import ModelMixin

    class _FakeModelMixin(ModelMixin):
        # ModelMixin requires a config_name class attribute and a config dict for serialization.
        # We never serialize, so we only need to satisfy isinstance() checks.
        config_name = "config.json"

        def __init__(self):
            super().__init__()
            self.linear = torch.nn.Linear(4, 4, bias=False)

        def forward(self, x):
            return self.linear(x)

    loader = _make_loader(device="cuda")
    config = _make_config(ModelType.Main, fp8=True)

    model = _FakeModelMixin()

    with (
        patch.object(ModelLoader, "_should_use_fp8", return_value=True),
        patch.object(ModelLoader, "_apply_fp8_to_nn_module") as mock_to_nn,
        patch.object(_FakeModelMixin, "enable_layerwise_casting") as mock_enable,
    ):
        loader._apply_fp8_layerwise_casting(model, config)

    mock_to_nn.assert_called_once()
    mock_enable.assert_not_called()


# ===== _device_supports_fp8_storage probe ===================================
# The probe gates FP8 storage in two places: the generic layerwise-casting path and the
# Krea 2 Qwen3-VL encoder. It must never regress CUDA, and must not claim support on CPU.


@pytest.fixture(autouse=True)
def _clear_fp8_probe_cache():
    _FP8_STORAGE_SUPPORTED.clear()
    _FP8_PROBE_FAILURE_REPORTED.clear()
    yield
    _FP8_STORAGE_SUPPORTED.clear()
    _FP8_PROBE_FAILURE_REPORTED.clear()


def test_device_supports_fp8_storage_probes_cuda_too():
    """ROCm reports `device.type == "cuda"` and its float8 coverage varies by architecture.

    Answering the whole CUDA branch True without asking let such a build pass the gate, have its
    weights cast on the CPU -- which always works -- and moved to VRAM, and then raise
    "not implemented for 'Float8_e4m3fn'" on the first forward, after the VRAM was committed.
    """
    ok, log = _probe_with_recorder(torch.device("cuda", 1))
    assert ok is True
    assert log == [torch.float8_e4m3fn, torch.device("cuda", 1), torch.bfloat16, torch.float16]


def test_device_supports_fp8_storage_rejects_a_cuda_build_without_an_e4m3fn_upcast():
    """Older gfx has no `e4m3fn` conversion at all, and gfx90a prefers `e4m3fnuz`. The fallback has
    to be chosen here, not discovered mid-generation."""
    ok, _ = _probe_with_recorder(torch.device("cuda"), fail_on=torch.bfloat16)
    assert ok is False


def test_device_supports_fp8_storage_rejects_cpu():
    assert _device_supports_fp8_storage(torch.device("cpu")) is False


def test_device_supports_fp8_storage_xpu_probes_and_survives_failure():
    """XPU float8 support is build/driver dependent, so a failing probe must return False
    rather than propagate."""
    with patch("torch.zeros", side_effect=RuntimeError("no float8 on this build")):
        assert _device_supports_fp8_storage(torch.device("xpu")) is False


class _RecordingTensor:
    """Stands in for a tensor so the probe's cast sequence can be observed without a real GPU."""

    def __init__(self, log: list, fail_on=None):
        self._log = log
        self._fail_on = fail_on

    def to(self, target):
        if self._fail_on is not None and target == self._fail_on:
            raise RuntimeError(f"unsupported: {target}")
        self._log.append(target)
        return self


def _probe_with_recorder(device: torch.device, fail_on=None) -> tuple[bool, list]:
    log: list = []
    with patch("torch.zeros", return_value=_RecordingTensor(log, fail_on)) as mock_zeros:
        result = _device_supports_fp8_storage(device)
    # The storage cast happens on CPU at runtime, so the probe must not allocate on the device.
    assert mock_zeros.call_args.kwargs.get("device") is None
    return result, log


def test_device_supports_fp8_storage_mirrors_the_runtime_cast_sequence():
    """At runtime the storage cast is CPU-side, the fp8 tensor is copied to the device, and the
    pre-hook upcasts there. A probe that did all three on the device would pass on a build where
    the fp8 host->device copy or one upcast target fails, then break at forward time."""
    ok, log = _probe_with_recorder(torch.device("xpu", 1))
    assert ok is True
    assert log == [torch.float8_e4m3fn, torch.device("xpu", 1), torch.bfloat16, torch.float16]


def test_device_supports_fp8_storage_rejects_a_build_missing_bf16_upcast():
    """compute_dtype is bf16 for Krea-2/FLUX; fp16-only support must not report True."""
    ok, _ = _probe_with_recorder(torch.device("xpu"), fail_on=torch.bfloat16)
    assert ok is False


def test_device_supports_fp8_storage_does_not_cache_failures():
    """The probe runs during a model load, so a transient failure (e.g. the device is
    momentarily full) must not disable FP8 for the lifetime of the process."""
    with patch("torch.zeros", side_effect=torch.OutOfMemoryError("transient")):
        assert _device_supports_fp8_storage(torch.device("xpu")) is False
    ok, _ = _probe_with_recorder(torch.device("xpu"))
    assert ok is True


def test_device_supports_fp8_storage_is_cached_per_device():
    """float8 support is a per-device property; one device's answer must not decide for another."""
    ok, _ = _probe_with_recorder(torch.device("xpu", 0))
    assert ok is True
    # xpu:1 has not been probed, so a failing probe there must be observed, not short-circuited.
    with patch("torch.zeros", side_effect=RuntimeError("no float8 on this device")):
        assert _device_supports_fp8_storage(torch.device("xpu", 1)) is False


def test_model_declared_skip_patterns_unions_both_diffusers_attributes():
    """`enable_layerwise_casting()` unions `_skip_layerwise_casting_patterns` with
    `_keep_in_fp32_modules`. We replaced that call with our own hook-based path, so we have to read
    both — otherwise a model that declares only the latter loses its exclusions silently.
    """

    class _Model(torch.nn.Module):
        _skip_layerwise_casting_patterns = ["t_embedder"]
        _keep_in_fp32_modules = ["time_embedder"]

    assert _model_declared_skip_patterns(_Model()) == ("t_embedder", "time_embedder")


def test_model_declared_skip_patterns_tolerates_missing_and_odd_declarations():
    """Most models declare neither attribute; diffusers sets them to `None` on some. A bare string
    is accepted too, so a subclass that writes one instead of a list isn't silently expanded into
    per-character patterns."""

    class _Bare(torch.nn.Module):
        pass

    class _Nulls(torch.nn.Module):
        _skip_layerwise_casting_patterns = None
        _keep_in_fp32_modules = None

    class _Strings(torch.nn.Module):
        _keep_in_fp32_modules = "time_embedder"

    assert _model_declared_skip_patterns(_Bare()) == ()
    assert _model_declared_skip_patterns(_Nulls()) == ()
    assert _model_declared_skip_patterns(_Strings()) == ("time_embedder",)


def test_keep_in_fp32_modules_are_not_cast():
    """End-to-end through the cast: a module named only by `_keep_in_fp32_modules` keeps its
    compute dtype."""

    class _Model(torch.nn.Module):
        _keep_in_fp32_modules = ["time_embedder"]

        def __init__(self):
            super().__init__()
            self.time_embedder = torch.nn.Linear(4, 4)
            self.attn = torch.nn.Linear(4, 4)

    loader = _make_loader(device="cuda")
    model = _Model().to(torch.bfloat16)

    with patch.object(ModelLoader, "_should_use_fp8", return_value=True):
        loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

    assert model.time_embedder.weight.dtype == torch.bfloat16
    assert model.attn.weight.dtype == torch.float8_e4m3fn


class TestComputeDtypeIsAlwaysAFloat:
    """The compute dtype is read off the model's parameters, and not every parameter is arithmetic.

    `_is_quantized_param` exists because a checkpoint quantized by an external tool can reach the
    cast with packed `uint8` weights that `_should_use_fp8`'s format check cannot see. Taking the
    *first* parameter's dtype would record one of those as the dtype the model computes in: the
    pre-hook would widen every other layer to `uint8`, and `get_model_compute_dtype` would hand
    `uint8` to the denoise loop. Finite garbage, nothing logged.
    """

    def _model(self, leading: torch.Tensor) -> torch.nn.Module:
        model = torch.nn.Module()
        # Registered first, so `model.parameters()` yields it first.
        model.register_parameter("packed", torch.nn.Parameter(leading, requires_grad=False))
        model.add_module("attn", torch.nn.Linear(4, 4).to(torch.bfloat16))
        return model

    def test_a_packed_leading_param_is_not_taken_as_the_compute_dtype(self) -> None:
        """A leading *float8* param is covered by a different guard — `count_fp8_weights` returns
        before the dtype is derived at all — so only the packed-integer case reaches this code."""
        loader = _make_loader(device="cuda")
        model = self._model(torch.zeros(4, 4, dtype=torch.uint8))

        with patch.object(ModelLoader, "_should_use_fp8", return_value=True):
            loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
        # And the cast actually ran against that dtype rather than skipping the model.
        assert model.attn.weight.dtype is torch.float8_e4m3fn


class TestComputeDtypeIgnoresKeepInFp32Parameters:
    """A parameter kept in float32 on purpose says nothing about the dtype the other layers compute in.

    Wan registers `scale_shift_table` (float32, in `_keep_in_fp32_modules`) before any submodule, so the
    first float parameter is not the compute dtype: fp8 weights would be widened to float32 on every forward.
    """

    @staticmethod
    def _cast(model: torch.nn.Module) -> None:
        loader = _make_loader(device="cuda")
        with patch.object(ModelLoader, "_should_use_fp8", return_value=True):
            loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

    @staticmethod
    def _model(keep) -> torch.nn.Module:
        model = torch.nn.Module()
        if keep is not _MISSING:
            model._keep_in_fp32_modules = keep
        model.register_parameter("scale_shift_table", torch.nn.Parameter(torch.zeros(1, 2, 4), requires_grad=False))
        model.add_module("attn", torch.nn.Linear(4, 4).to(torch.bfloat16))
        return model

    def test_a_leading_fp32_keep_parameter_is_not_the_compute_dtype(self) -> None:
        model = self._model(["scale_shift_table"])
        self._cast(model)

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
        assert model.attn.weight.dtype is torch.float8_e4m3fn

    def test_a_bare_string_declaration_is_a_name_not_a_set_of_characters(self) -> None:
        model = self._model("scale_shift_table")
        self._cast(model)

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16

    @pytest.mark.parametrize("keep", [_MISSING, None, [], ["other"], [None, 3]])
    def test_without_a_usable_declaration_the_first_float_parameter_decides(self, keep) -> None:
        model = self._model(keep)
        self._cast(model)

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.float32

    def test_a_model_whose_only_floats_are_kept_computes_in_the_first_of_them(self) -> None:
        model = torch.nn.Module()
        model._keep_in_fp32_modules = ["scale_shift_table"]
        model.register_parameter("scale_shift_table", torch.nn.Parameter(torch.zeros(1, 2, 4), requires_grad=False))
        self._cast(model)

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.float32

    def test_the_real_wan_transformer_computes_in_bf16_and_keeps_its_fp32_islands(self, tmp_path) -> None:
        from diffusers import WanTransformer3DModel

        WanTransformer3DModel(**WAN_TINY_KWARGS).save_pretrained(tmp_path)
        model = WanTransformer3DModel.from_pretrained(tmp_path, torch_dtype=torch.bfloat16)
        first_name, first_param = next(iter(model.named_parameters()))
        assert first_name == "scale_shift_table"
        assert first_param.dtype is torch.float32

        self._cast(model)

        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
        assert model.blocks[0].attn1.to_q.weight.dtype is torch.float8_e4m3fn
        # The fp32 island survives the cast (Wan protects it through both `_keep_in_fp32_modules` and
        # `_skip_layerwise_casting_patterns`; `test_keep_in_fp32_modules_are_not_cast` covers the keep list alone).
        assert model.condition_embedder.time_embedder.linear_1.weight.dtype is torch.float32


class TestAlreadyFp8StorageGuard:
    """FP8 storage must not run over weights that are already fp8 and headed for the tensor cores.

    Layerwise casting installs a pre-hook that restores the compute dtype before every forward. On
    a scaled-fp8 checkpoint that hook does two things at once: `_can_use_fp8_matmul` no longer sees
    an fp8 weight, so the matmul silently falls back, and the hook upcasts the weight *without*
    applying its `weight_scale`, i.e. a weight off by `1/weight_scale`. Neither is visible in the
    output of a successful generation, so the guard is load-bearing and needs a test that fails if
    it is reverted.
    """

    def _model(self) -> torch.nn.Module:
        model = torch.nn.Sequential(torch.nn.Linear(16, 32))
        model[0].weight = torch.nn.Parameter(
            torch.zeros(32, 16, dtype=torch.float32).to(torch.float8_e4m3fn), requires_grad=False
        )
        return model

    def test_a_model_whose_weights_are_already_fp8_is_left_alone(self) -> None:
        loader = _make_loader("cuda")
        model = self._model()

        with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True):
            result = loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

        assert result is model
        # No compute-dtype marker means `_apply_fp8_to_nn_module` never ran over it.
        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None
        assert model[0].weight.dtype is torch.float8_e4m3fn

    def test_a_full_precision_model_is_still_cast(self) -> None:
        """The guard must key on the weights, not merely on fp8_compute being enabled."""
        loader = _make_loader("cuda")
        model = torch.nn.Sequential(torch.nn.Linear(16, 32))

        with (
            _device_holds_fp8(),
            patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True),
        ):
            loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

        assert model[0].weight.dtype is torch.float8_e4m3fn
        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is not None

    def test_ordinary_storage_casting_is_unaffected_when_the_matmul_is_unavailable(self) -> None:
        """The guard must not become a blanket "skip fp8 storage" once fp8_compute is off.

        Only the already-fp8 case is protected. A full-precision model still gets the storage cast,
        which is the entire point of the toggle on a card without the fp8 matmul.

        The mirror case -- an already-fp8 model with the matmul off -- is covered below. It used to
        be unreachable, and is not any more: FP8 Storage keeps scaled weights packed too.
        """
        loader = _make_loader("cuda")
        model = torch.nn.Sequential(torch.nn.Linear(16, 32))

        with (
            _device_holds_fp8(),
            patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False),
        ):
            loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

        assert model[0].weight.dtype is torch.float8_e4m3fn

    def test_already_fp8_weights_are_left_alone_when_the_matmul_is_off(self) -> None:
        """The case FP8 Storage created: weights kept packed without the fp8 matmul.

        The guard used to ask whether the matmul was available, which is a different question from
        the one that matters -- whether the model already holds fp8 weights. With FP8 Storage on and
        `fp8_compute` off the cast would run over packed weights and upcast them with their
        `weight_scale` never applied, i.e. off by 1/weight_scale on every layer, or derive an fp8
        compute dtype and refuse the load outright.
        """
        loader = _make_loader("cuda")
        model = torch.nn.Sequential(torch.nn.Linear(16, 32))
        scale = torch.tensor(0.0056)
        model[0].weight = torch.nn.Parameter(
            torch.full((32, 16), 0.5 / scale.item()).to(torch.float8_e4m3fn), requires_grad=False
        )
        model[0].register_buffer("weight_scale", scale)

        with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False):
            returned = loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))

        assert returned is model
        assert model[0].weight.dtype is torch.float8_e4m3fn
        assert torch.equal(model[0].weight_scale, scale)
        # No hooks: an upcast before every forward is what would drop the scale.
        assert not model[0]._forward_pre_hooks
        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None


class TestApplyFp8SkipCallback:
    """The `skip=` callback keeps scaled-fp8 layers out of the storage cast.

    Its one caller (the Qwen3-VL encoder) casts the *unquantized* remainder of a partly-quantized
    checkpoint to fp8 storage while leaving the scaled layers on the matmul path. Without the
    callback those layers would be cast without their scale.
    """

    def test_a_module_the_callback_rejects_is_not_cast(self) -> None:
        model = torch.nn.Sequential()
        model.add_module("keep", torch.nn.Linear(16, 32))
        model.add_module("cast", torch.nn.Linear(16, 32))
        model.keep.weight_scale = torch.tensor(2.0)

        ModelLoader._apply_fp8_to_nn_module(
            model,
            storage_dtype=torch.float8_e4m3fn,
            compute_dtype=torch.bfloat16,
            skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,
        )

        assert model.keep.weight.dtype is not torch.float8_e4m3fn
        assert model.cast.weight.dtype is torch.float8_e4m3fn


class TestSkippedModulesNeverKeepCheckpointFp8:
    """A pattern-skipped module must not be left holding float8 weights.

    The cast pass installs the upcast pre-hook only on modules it casts. A module it *skips* keeps
    whatever dtype it arrived with — fine when that is the compute dtype, broken when the loader
    kept the checkpoint's fp8 weights: no hook and no cast back. Whether that shows up depends on
    the layer class, since `apply_custom_layers_to_model` only gives some of them an fp8-capable
    wrapper; `test_every_supported_layer_class_forwards_after_a_pattern_skip` pins which. Reachable
    wherever a loader combines `keep_fp8` with fp8 storage on the remainder (the Qwen3-VL encoder),
    and otherwise dependent on the loader's skip list and `_FP8_DEFAULT_SKIP_PATTERNS` never naming
    the same module.
    """

    def _model(self) -> torch.nn.Module:
        model = torch.nn.Module()
        # `proj_out` is in `_FP8_DEFAULT_SKIP_PATTERNS`; `attn` is not.
        model.add_module("proj_out", torch.nn.Linear(16, 32))
        model.add_module("attn", torch.nn.Linear(16, 32))
        return model

    def test_a_pattern_skipped_module_is_restored_to_the_compute_dtype(self) -> None:
        model = self._model()
        # As a loader that kept checkpoint fp8 weights would hand it over.
        model.proj_out.weight = torch.nn.Parameter(
            torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False
        )

        ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)

        assert model.proj_out.weight.dtype is torch.bfloat16, "skipped module left computing on fp8 codes"
        assert model.attn.weight.dtype is torch.float8_e4m3fn

    def test_a_pattern_skipped_scaled_layer_keeps_its_fp8_weight(self) -> None:
        """A scaled-fp8 `proj_out` is computed with its `weight_scale`; upcasting its codes without the
        scale would make the final projection wrong by that factor, silently."""
        model = self._model()
        codes = torch.full((32, 16), 3.0).to(torch.float8_e4m3fn)
        model.proj_out.weight = torch.nn.Parameter(codes, requires_grad=False)
        model.proj_out.weight_scale = torch.tensor(2.0)

        ModelLoader._apply_fp8_to_nn_module(
            model,
            storage_dtype=torch.float8_e4m3fn,
            compute_dtype=torch.bfloat16,
            skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,
        )

        assert model.proj_out.weight.dtype is torch.float8_e4m3fn
        assert torch.equal(model.proj_out.weight.float(), codes.float())

        # The dtype alone does not settle it: what matters is that the forward still applies the
        # scale. A cast that dropped it would leave the projection at 1/scale of the right answer.
        model.proj_out.bias = torch.nn.Parameter(torch.zeros(32, dtype=torch.bfloat16), requires_grad=False)
        apply_custom_layers_to_model(model)
        inp = torch.randn(4, 16, dtype=torch.bfloat16)
        dequantized = codes.to(torch.bfloat16) * 2.0

        assert torch.equal(model.proj_out(inp), torch.nn.functional.linear(inp, dequantized))

    def test_an_extra_skip_pattern_gets_the_same_treatment(self) -> None:
        model = self._model()
        model.attn.weight = torch.nn.Parameter(
            torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False
        )

        ModelLoader._apply_fp8_to_nn_module(
            model,
            storage_dtype=torch.float8_e4m3fn,
            compute_dtype=torch.bfloat16,
            extra_skip_patterns=("attn",),
        )

        assert model.attn.weight.dtype is torch.bfloat16

    def test_a_full_precision_skipped_module_is_untouched(self) -> None:
        """The restore must not disturb the ordinary case it shares a branch with."""
        model = self._model()
        model.proj_out.weight = torch.nn.Parameter(torch.zeros(32, 16, dtype=torch.float32), requires_grad=False)

        ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)

        assert model.proj_out.weight.dtype is torch.float32

    def test_a_caller_skipped_scaled_layer_keeps_its_fp8_weight(self) -> None:
        """The `skip=` callback means the opposite of a pattern skip: its one caller excludes
        scaled-fp8 layers, which stay quantized and go through `_scaled_mm` with their
        `weight_scale`. Upcasting those would drop the scale."""
        model = self._model()
        model.attn.weight = torch.nn.Parameter(
            torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False
        )
        model.attn.weight_scale = torch.tensor(2.0)

        ModelLoader._apply_fp8_to_nn_module(
            model,
            storage_dtype=torch.float8_e4m3fn,
            compute_dtype=torch.bfloat16,
            skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,
        )

        assert model.attn.weight.dtype is torch.float8_e4m3fn

    @pytest.mark.parametrize(
        ("make_module", "make_input"),
        [
            pytest.param(
                lambda: torch.nn.Linear(16, 32), lambda: torch.randn(4, 16, dtype=torch.bfloat16), id="Linear"
            ),
            pytest.param(
                lambda: torch.nn.Conv1d(4, 8, 3), lambda: torch.randn(1, 4, 16, dtype=torch.bfloat16), id="Conv1d"
            ),
            pytest.param(
                lambda: torch.nn.Conv2d(4, 8, 3), lambda: torch.randn(1, 4, 8, 8, dtype=torch.bfloat16), id="Conv2d"
            ),
            pytest.param(
                lambda: torch.nn.Conv3d(4, 8, 3), lambda: torch.randn(1, 4, 6, 6, 6, dtype=torch.bfloat16), id="Conv3d"
            ),
            pytest.param(
                lambda: torch.nn.ConvTranspose1d(4, 8, 3),
                lambda: torch.randn(1, 4, 16, dtype=torch.bfloat16),
                id="ConvTranspose1d",
            ),
            pytest.param(
                lambda: torch.nn.ConvTranspose2d(4, 8, 3),
                lambda: torch.randn(1, 4, 8, 8, dtype=torch.bfloat16),
                id="ConvTranspose2d",
            ),
            pytest.param(
                lambda: torch.nn.ConvTranspose3d(4, 8, 3),
                lambda: torch.randn(1, 4, 6, 6, 6, dtype=torch.bfloat16),
                id="ConvTranspose3d",
            ),
            pytest.param(lambda: torch.nn.Embedding(16, 32), lambda: torch.tensor([1, 2, 3]), id="Embedding"),
        ],
    )
    def test_every_supported_layer_class_forwards_after_a_pattern_skip(self, make_module, make_input) -> None:
        """One case per class in `_FP8_SUPPORTED_PYTORCH_LAYERS`, run the way the cache leaves them.

        This is what makes the restore load-bearing rather than belt-and-braces. Only `Linear` and
        `Conv2d` get a wrapper from `apply_custom_layers_to_model` that can consume an fp8 weight;
        `Conv1d`'s only moves the weight to the device, `Conv3d` and the three `ConvTranspose`
        classes get none, and `CustomEmbedding` hands the next op a float8 tensor. Drop the restore
        and six of these eight fail — five by raising mid-forward.
        """
        torch.manual_seed(0)
        module = make_module().to(torch.bfloat16)
        # Round-trip first, so the reference is what the fp8 codes actually represent rather than
        # the full-precision weight they were quantized from.
        module.weight = torch.nn.Parameter(
            module.weight.data.to(torch.float8_e4m3fn).to(torch.bfloat16), requires_grad=False
        )
        reference = copy.deepcopy(module)
        module.weight = torch.nn.Parameter(module.weight.data.to(torch.float8_e4m3fn), requires_grad=False)

        model = torch.nn.Module()
        # `^proj_out$` is in `_FP8_DEFAULT_SKIP_PATTERNS`, so this module is never cast or hooked.
        model.add_module("proj_out", module)

        ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
        apply_custom_layers_to_model(model)

        inp = make_input()
        out = model.proj_out(inp)

        assert out.dtype is torch.bfloat16
        assert torch.equal(out, reference(inp))


@pytest.mark.parametrize("submodel", [SubModelType.TextEncoder, SubModelType.VisionEncoder])
def test_a_krea2_pipelines_encoders_never_take_fp8_storage(submodel):
    """FP8 Storage on a Krea-2 pipeline casts its transformer, never its Qwen3-VL text encoder or the vision
    tower edit mode loads from it: both condition the image."""
    loader = _make_loader("cuda")
    config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.Krea2)

    with _device_holds_fp8():
        assert loader._should_use_fp8(config, SubModelType.Transformer) is True
        assert loader._should_use_fp8(config, submodel) is False


def _quantized_layer(scheme: str) -> torch.nn.Module:
    if scheme == "int8":
        codes = torch.randint(-127, 128, (128, 64), dtype=torch.int8)
        return Int8ConvrotLinear(codes, torch.rand(128, 1) + 0.5, convrot=False, bias=torch.randn(128))
    if scheme == "int4":
        packed = torch.randint(-128, 128, (128, 32), dtype=torch.int8)
        return Int4ConvrotLinear(packed, torch.rand(128, 1) + 0.5, convrot=False, bias=torch.randn(128))
    tensors = nvfp4_tensors("layer", nvfp4_codes(torch.rand(128, 64) > 0.5), block_scale=1.0, global_scale=0.5)
    return NVFP4Linear(tensors["layer.weight"], tensors["layer.weight_scale"], tensors["layer.weight_scale_2"])


@pytest.mark.parametrize("scheme", ["int8", "int4", "nvfp4", None])
def test_fp8_storage_declines_an_int8_or_int4_build_and_casts_the_dense_layers_of_any_other(scheme, caplog) -> None:
    """One int8 or int4 layer declines the whole model, so its dense neighbour keeps the precision the build chose. An
    nvfp4 build is cast like a dense one: the dense layer goes to fp8 and the nvfp4 buffers stay as stored."""
    torch.manual_seed(0)
    model = torch.nn.Module()
    model.dense = torch.nn.Linear(16, 32).to(torch.bfloat16)
    if scheme is not None:
        model.quantized = _quantized_layer(scheme)
    before = {name: tensor.clone() for name, tensor in model.state_dict().items()}
    config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)

    with caplog.at_level("INFO", logger="test"), _device_holds_fp8():
        _make_loader()._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)

    messages = [record.getMessage() for record in caplog.records]
    skipped = [m for m in messages if m.startswith("FP8 Storage skipped for test - ")]
    if scheme in ("int8", "int4"):
        after = model.state_dict()
        assert after.keys() == before.keys()
        for name, tensor in before.items():
            assert after[name].dtype is tensor.dtype, name
            assert torch.equal(after[name], tensor), name
        assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None
        assert skipped == [FP8_STORAGE_SKIPPED.format(name="test")]
        return
    assert model.dense.weight.dtype is torch.float8_e4m3fn
    assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is torch.bfloat16
    assert not skipped
    assert any(m.startswith("FP8 layerwise casting enabled for test") for m in messages)
    for name, tensor in before.items():
        if name.startswith("quantized."):
            assert model.state_dict()[name].dtype is tensor.dtype, name
            assert torch.equal(model.state_dict()[name].float(), tensor.float()), name


def test_an_int8_build_that_also_holds_fp8_weights_is_reported_as_already_fp8(caplog) -> None:
    """A build that holds scaled fp8 layers keeps them packed only because FP8 Storage is on. The notice names that,
    not the quantized layers: the latter would read as a reason to turn the setting off, which unpacks every scaled
    layer."""
    model = torch.nn.Module()
    model.dense = torch.nn.Linear(16, 32).to(torch.bfloat16)
    model.quantized = _quantized_layer("int8")
    model.scaled = torch.nn.Linear(16, 32)
    model.scaled.weight = torch.nn.Parameter(torch.zeros(32, 16).to(torch.float8_e4m3fn), requires_grad=False)
    dense_before = model.dense.weight.clone()
    config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)

    with caplog.at_level("INFO", logger="test"), _device_holds_fp8():
        _make_loader()._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)

    messages = [record.getMessage() for record in caplog.records]
    assert sum("weight(s) are already fp8" in message for message in messages) == 1
    assert not any("this quantized build" in message for message in messages)
    assert model.dense.weight.dtype is torch.bfloat16
    assert torch.equal(model.dense.weight, dense_before)
    assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None