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.

42.9 KB
Raw Blame
import gc
import weakref
from typing import Callable, Iterable

import pytest
import torch

from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (
    CachedModelWithPartialLoad,
)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
    apply_custom_layers_to_model,
)
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.layers.merged_layer_patch import MergedLayerPatch, Range
from invokeai.backend.patches.layers.swapped_halves_layer_patch import SwappedHalvesLayerPatch
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw


class DummyModuleWithOneLayer(torch.nn.Module):
    def __init__(self, in_features: int, out_features: int, device: str, dtype: torch.dtype):
        super().__init__()
        self.linear_layer_1 = torch.nn.Linear(in_features, out_features, device=device, dtype=dtype)

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


class DummyModuleWithTwoLayers(torch.nn.Module):
    def __init__(self, in_features: int, out_features: int, device: str, dtype: torch.dtype):
        super().__init__()
        self.linear_layer_1 = torch.nn.Linear(in_features, out_features, device=device, dtype=dtype)
        self.linear_layer_2 = torch.nn.Linear(out_features, out_features, device=device, dtype=dtype)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.linear_layer_2(self.linear_layer_1(x))


class DummyModuleWithNestedLayer(torch.nn.Module):
    """A model with both a top-level layer (dotless key) and a nested submodule (dotted key)."""

    def __init__(self, in_features: int, out_features: int, device: str, dtype: torch.dtype):
        super().__init__()
        self.top_layer = torch.nn.Linear(in_features, in_features, device=device, dtype=dtype)
        self.block = DummyModuleWithOneLayer(in_features, out_features, device=device, dtype=dtype)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.block(self.top_layer(x))


def test_apply_smart_model_patches_retains_patch_cache_handle_for_context_lifetime():
    """A loaded-model handle must pin each patch's cache record until patch use is complete."""

    class CacheHandle:
        is_entered = False

        def __enter__(self):
            self.is_entered = True
            return self

        def __exit__(self, *args):
            self.is_entered = False
            return None

    handle_ref: weakref.ReferenceType[CacheHandle] | None = None

    def patch_specs():
        nonlocal handle_ref
        handle = CacheHandle()
        handle_ref = weakref.ref(handle)
        yield (ModelPatchRaw({}), 0.0, handle)
        assert handle.is_entered

    model = DummyModuleWithOneLayer(1, 1, device="cpu", dtype=torch.float32)
    with LayerPatcher.apply_smart_model_patches(model=model, patches=patch_specs(), prefix="", dtype=torch.float32):
        gc.collect()
        assert handle_ref is not None and handle_ref() is not None

    gc.collect()
    assert handle_ref is not None and handle_ref() is None


class _PinTracker:
    """A stand-in for the model_in_ram() context manager carried in a 3-tuple patch spec."""

    def __init__(self):
        self.enter_count = 0
        self.exit_count = 0

    def __enter__(self):
        self.enter_count += 1
        return self

    def __exit__(self, *args):
        self.exit_count += 1
        return None


def test_apply_smart_model_patches_exits_every_pin_on_normal_exit():
    """Each pin must be entered before patching and exited exactly once when the context closes.

    Regression guard for the `finally: cache_pins.close()` in apply_smart_model_patches: without it,
    every LoRA cache record stays locked forever and becomes permanently invisible to eviction while
    still charged to the shared RAM budget. The weakref-based retention test above cannot catch a
    dropped close() (the pins would be collected silently), so assert the __exit__ calls directly.
    """
    pins = [_PinTracker(), _PinTracker()]
    patches = [(ModelPatchRaw({}), 0.5, pins[0]), (ModelPatchRaw({}), 0.5, pins[1])]

    model = DummyModuleWithOneLayer(1, 1, device="cpu", dtype=torch.float32)
    with LayerPatcher.apply_smart_model_patches(model=model, patches=iter(patches), prefix="", dtype=torch.float32):
        assert all(pin.enter_count == 1 and pin.exit_count == 0 for pin in pins)

    assert all(pin.enter_count == 1 and pin.exit_count == 1 for pin in pins)


def test_apply_smart_model_patches_exits_every_pin_when_the_body_raises():
    pin = _PinTracker()

    model = DummyModuleWithOneLayer(1, 1, device="cpu", dtype=torch.float32)
    with pytest.raises(RuntimeError, match="boom"):
        with LayerPatcher.apply_smart_model_patches(
            model=model, patches=iter([(ModelPatchRaw({}), 0.5, pin)]), prefix="", dtype=torch.float32
        ):
            raise RuntimeError("boom")

    assert pin.enter_count == 1
    assert pin.exit_count == 1


def test_apply_smart_model_patches_exits_every_pin_when_restoration_raises(monkeypatch):
    """A failure while restoring patched weights must still release the cache pins."""
    from invokeai.backend.util.original_weights_storage import OriginalWeightsStorage

    pin = _PinTracker()

    def raising_get_changed_weights(self):
        raise RuntimeError("restore failed")

    monkeypatch.setattr(OriginalWeightsStorage, "get_changed_weights", raising_get_changed_weights)

    model = DummyModuleWithOneLayer(1, 1, device="cpu", dtype=torch.float32)
    with pytest.raises(RuntimeError, match="restore failed"):
        with LayerPatcher.apply_smart_model_patches(
            model=model, patches=iter([(ModelPatchRaw({}), 0.5, pin)]), prefix="", dtype=torch.float32
        ):
            pass

    assert pin.enter_count == 1
    assert pin.exit_count == 1


def test_apply_smart_model_patches_unwinds_entered_pins_when_a_later_load_raises():
    """A producer that fails while loading LoRA B must release LoRA A's already-entered pin."""
    pin_a = _PinTracker()

    def patch_specs():
        yield (ModelPatchRaw({}), 0.5, pin_a)
        raise RuntimeError("load of the second LoRA failed")

    model = DummyModuleWithOneLayer(1, 1, device="cpu", dtype=torch.float32)
    with pytest.raises(RuntimeError, match="load of the second LoRA failed"):
        with LayerPatcher.apply_smart_model_patches(model=model, patches=patch_specs(), prefix="", dtype=torch.float32):
            pass

    assert pin_a.enter_count == 1
    assert pin_a.exit_count == 1


@torch.no_grad()
def test_apply_smart_model_patches_mixed_dotted_and_dotless_keys():
    """Regression test: a patch whose first layer key is a dotless top-level module (e.g. a Flux2 diffusers
    LoRA whose first converted layer is `context_embedder`) followed by dotted nested keys must not be
    misclassified as a flattened patch. Inspecting only the first key would set layer_keys_are_flattened=True
    and trip `assert "." not in layer_key` in _get_submodule on the subsequent dotted keys.
    """
    dtype = torch.float16
    in_features = 4
    out_features = 8
    lora_rank = 2
    model = DummyModuleWithNestedLayer(in_features, out_features, device="cpu", dtype=dtype)
    apply_custom_layers_to_model(model)

    # Insertion order matters: the dotless top-level key comes first, the dotted nested key second.
    lora_layers = {
        "top_layer": LoRALayer.from_state_dict_values(
            values={
                "lora_down.weight": torch.ones((lora_rank, in_features), device="cpu", dtype=dtype),
                "lora_up.weight": torch.ones((in_features, lora_rank), device="cpu", dtype=dtype),
            },
        ),
        "block.linear_layer_1": LoRALayer.from_state_dict_values(
            values={
                "lora_down.weight": torch.ones((lora_rank, in_features), device="cpu", dtype=dtype),
                "lora_up.weight": torch.ones((out_features, lora_rank), device="cpu", dtype=dtype),
            },
        ),
    }
    lora = ModelPatchRaw(lora_layers)
    assert next(iter(lora.layers.keys())) == "top_layer"  # the dotless key is first

    input = torch.randn(1, in_features, device="cpu", dtype=dtype)
    output_before_patch = model(input)

    # This previously raised AssertionError on the "block.linear_layer_1" key.
    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(lora, 0.5)], prefix="", dtype=dtype, force_direct_patching=True
    ):
        output_during_patch = model(input)

    output_after_patch = model(input)

    # Both layers were actually patched (output changed), and unpatching restored the original output.
    assert not torch.allclose(output_before_patch, output_during_patch)
    assert torch.allclose(output_before_patch, output_after_patch)


@pytest.mark.parametrize(
    "device",
    [
        "cpu",
        pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA device")),
    ],
)
@pytest.mark.parametrize("num_loras", [1, 2])
@pytest.mark.parametrize(
    ["force_sidecar_patching", "force_direct_patching"], [(True, False), (False, True), (False, False)]
)
@torch.no_grad()
def test_apply_smart_model_patches(
    device: str, num_loras: int, force_sidecar_patching: bool, force_direct_patching: bool
):
    """Test the basic behavior of ModelPatcher.apply_smart_model_patches(...). Check that unpatching works correctly."""
    dtype = torch.float16
    linear_in_features = 4
    linear_out_features = 8
    lora_rank = 2
    model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device=device, dtype=dtype)
    apply_custom_layers_to_model(model)

    # Initialize num_loras LoRA models with weights of 0.5.
    lora_weight = 0.5
    lora_models: list[tuple[ModelPatchRaw, float]] = []
    for _ in range(num_loras):
        lora_layers = {
            "linear_layer_1": LoRALayer.from_state_dict_values(
                values={
                    "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.float16),
                    "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.float16),
                },
            )
        }
        lora = ModelPatchRaw(lora_layers)
        lora_models.append((lora, lora_weight))

    orig_linear_weight = model.linear_layer_1.weight.data.detach().clone()
    expected_patched_linear_weight = orig_linear_weight + (lora_rank * lora_weight * num_loras)

    # Run inference before patching the model.
    input = torch.randn(1, linear_in_features, device=device, dtype=dtype)
    output_before_patch = model(input)

    expect_sidecar_wrappers = device == "cpu"
    if force_sidecar_patching:
        expect_sidecar_wrappers = True
    elif force_direct_patching:
        expect_sidecar_wrappers = False

    # Patch the model and run inference during the patch.
    with LayerPatcher.apply_smart_model_patches(
        model=model,
        patches=lora_models,
        prefix="",
        dtype=dtype,
        force_direct_patching=force_direct_patching,
        force_sidecar_patching=force_sidecar_patching,
    ):
        if expect_sidecar_wrappers:
            # There should be sidecar patches in the model.
            assert model.linear_layer_1.get_num_patches() == num_loras
        else:
            # There should be no sidecar patches in the model.
            assert model.linear_layer_1.get_num_patches() == 0
            torch.testing.assert_close(model.linear_layer_1.weight.data, expected_patched_linear_weight)

            # After patching, the patched model should still be on its original device.
            assert model.linear_layer_1.weight.data.device.type == device

            # After patching, all LoRA layer weights should have been moved back to the cpu.
            for lora, _ in lora_models:
                assert lora.layers["linear_layer_1"].up.device.type == "cpu"
                assert lora.layers["linear_layer_1"].down.device.type == "cpu"

        output_during_patch = model(input)

    # Run inference after unpatching.
    output_after_patch = model(input)

    # Check that the output before patching is different from the output during patching.
    assert not torch.allclose(output_before_patch, output_during_patch)

    # Check that the output before patching is the same as the output after patching.
    assert torch.allclose(output_before_patch, output_after_patch)


@pytest.mark.parametrize(["num_loras"], [(1,), (2,)])
@torch.no_grad()
def test_apply_smart_lora_patches_to_partially_loaded_model(num_loras: int):
    """Test the behavior of ModelPatcher.apply_smart_lora_patches(...) when it is applied to a
    CachedModelWithPartialLoad that is partially loaded into VRAM.
    """

    if not torch.cuda.is_available():
        pytest.skip("requires CUDA device")

    # Initialize the model on the CPU.
    dtype = torch.float16
    linear_in_features = 4
    linear_out_features = 8
    lora_rank = 2
    model = DummyModuleWithTwoLayers(linear_in_features, linear_out_features, device="cpu", dtype=dtype)
    apply_custom_layers_to_model(model)
    cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("cuda"))
    model_total_bytes = cached_model.total_bytes()
    assert cached_model.cur_vram_bytes() == 0

    # Partially load the model into VRAM.
    target_vram_bytes = int(model_total_bytes * 0.6)
    _ = cached_model.partial_load_to_vram(target_vram_bytes)
    assert cached_model.model.linear_layer_1.weight.device.type == "cuda"
    assert cached_model.model.linear_layer_2.weight.device.type == "cpu"

    # Initialize num_loras LoRA models with weights of 0.5.
    lora_weight = 0.5
    lora_models: list[tuple[ModelPatchRaw, float]] = []
    for _ in range(num_loras):
        lora_layers = {
            "linear_layer_1": LoRALayer.from_state_dict_values(
                values={
                    "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.float16),
                    "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.float16),
                },
            ),
            "linear_layer_2": LoRALayer.from_state_dict_values(
                values={
                    "lora_down.weight": torch.ones((lora_rank, linear_out_features), device="cpu", dtype=torch.float16),
                    "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.float16),
                },
            ),
        }
        lora = ModelPatchRaw(lora_layers)
        lora_models.append((lora, lora_weight))

    # Run inference before patching the model.
    input = torch.randn(1, linear_in_features, device="cuda", dtype=dtype)
    output_before_patch = cached_model.model(input)

    # Patch the model and run inference during the patch.
    with LayerPatcher.apply_smart_model_patches(model=cached_model.model, patches=lora_models, prefix="", dtype=dtype):
        # Check that the second layer has sidecar patches, but the first layer does not.
        assert cached_model.model.linear_layer_1.get_num_patches() == 0
        assert cached_model.model.linear_layer_2.get_num_patches() == num_loras

        output_during_patch = cached_model.model(input)

    # Run inference after unpatching.
    output_after_patch = cached_model.model(input)

    # Check that the output before patching is different from the output during patching.
    assert not torch.allclose(output_before_patch, output_during_patch)

    # Check that the output before patching is the same as the output after patching.
    assert torch.allclose(output_before_patch, output_after_patch)


@torch.no_grad()
@pytest.mark.parametrize(["num_loras"], [(1,), (2,)])
def test_all_patching_methods_produce_same_output(num_loras: int):
    """Test that apply_lora_wrapper_patches(...) produces the same model outputs as apply_lora_patches(...)."""
    dtype = torch.float32
    linear_in_features = 4
    linear_out_features = 8
    lora_rank = 2
    model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device="cpu", dtype=dtype)
    apply_custom_layers_to_model(model)

    # Initialize num_loras LoRA models with weights of 0.5.
    lora_weight = 0.5
    lora_models: list[tuple[ModelPatchRaw, float]] = []
    for _ in range(num_loras):
        lora_layers = {
            "linear_layer_1": LoRALayer.from_state_dict_values(
                values={
                    "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.float16),
                    "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.float16),
                },
            )
        }
        lora = ModelPatchRaw(lora_layers)
        lora_models.append((lora, lora_weight))

    input = torch.randn(1, linear_in_features, device="cpu", dtype=dtype)

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=lora_models, prefix="", dtype=dtype, force_direct_patching=True
    ):
        output_force_direct = model(input)

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=lora_models, prefix="", dtype=dtype, force_sidecar_patching=True
    ):
        output_force_sidecar = model(input)

    with LayerPatcher.apply_smart_model_patches(model=model, patches=lora_models, prefix="", dtype=dtype):
        output_smart = model(input)

    # Note: We set atol=1e-5 because the test failed occasionally with the default atol=1e-8. Slight numerical
    # differences are tolerable and expected due to the difference between sidecar vs. patching.
    assert torch.allclose(output_force_direct, output_force_sidecar, atol=1e-5)
    assert torch.allclose(output_force_direct, output_smart, atol=1e-5)


@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA device")
@torch.no_grad()
def test_apply_smart_model_patches_change_device():
    """Test that if LoRA patching is applied on the CPU, and then the patched model is moved to the GPU, unpatching
    still behaves correctly.
    """
    linear_in_features = 4
    linear_out_features = 8
    lora_dim = 2
    # Initialize the model on the CPU.
    model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device="cpu", dtype=torch.float16)
    apply_custom_layers_to_model(model)

    lora_layers = {
        "linear_layer_1": LoRALayer.from_state_dict_values(
            values={
                "lora_down.weight": torch.ones((lora_dim, linear_in_features), device="cpu", dtype=torch.float16),
                "lora_up.weight": torch.ones((linear_out_features, lora_dim), device="cpu", dtype=torch.float16),
            },
        )
    }
    lora = ModelPatchRaw(lora_layers)

    orig_linear_weight = model.linear_layer_1.weight.data.detach().clone()

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(lora, 0.5)], prefix="", dtype=torch.float16, force_direct_patching=True
    ):
        # After patching, all LoRA layer weights should have been moved back to the cpu.
        assert lora_layers["linear_layer_1"].up.device.type == "cpu"
        assert lora_layers["linear_layer_1"].down.device.type == "cpu"

        # After patching, the patched model should still be on the CPU.
        assert model.linear_layer_1.weight.data.device.type == "cpu"

        # There should be no sidecar patches in the model.
        assert model.linear_layer_1.get_num_patches() == 0

        # Move the model to the GPU.
        assert model.to("cuda")

    # After unpatching, the original model weights should have been restored on the GPU.
    assert model.linear_layer_1.weight.data.device.type == "cuda"
    torch.testing.assert_close(model.linear_layer_1.weight.data, orig_linear_weight, check_device=False)


def test_apply_smart_model_patches_force_sidecar_and_direct_patching():
    """Test that ModelPatcher.apply_smart_model_patches(..., force_direct_patching=True, force_sidecar_patching=True)
    raises an error.
    """
    linear_in_features = 4
    linear_out_features = 8
    lora_rank = 2
    model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device="cpu", dtype=torch.float16)
    apply_custom_layers_to_model(model)

    lora_layers = {
        "linear_layer_1": LoRALayer.from_state_dict_values(
            values={
                "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.float16),
                "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.float16),
            },
        )
    }
    lora = ModelPatchRaw(lora_layers)
    with pytest.raises(ValueError, match="Cannot force both direct and sidecar patching."):
        with LayerPatcher.apply_smart_model_patches(
            model=model,
            patches=[(lora, 0.5)],
            prefix="",
            dtype=torch.float16,
            force_direct_patching=True,
            force_sidecar_patching=True,
        ):
            pass


@torch.no_grad()
def test_apply_smart_model_patches_fp8_weights_force_sidecar():
    """Regression test: a module whose weights are stored in float8 (e.g. from fp8_storage layerwise
    casting) must be sidecar-patched, even when direct patching is explicitly requested. Direct patching
    does an in-place add on the model weight, which has no CUDA add kernel for float8 and raises
    'ufunc_add_CUDA not implemented for Float8_e4m3fn'.
    """
    linear_in_features = 4
    linear_out_features = 8
    lora_rank = 2
    # Build the model, then cast its weights to fp8 to mimic fp8_storage layerwise casting.
    model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device="cpu", dtype=torch.bfloat16)
    model.linear_layer_1.weight.data = model.linear_layer_1.weight.data.to(torch.float8_e4m3fn)
    model.linear_layer_1.bias.data = model.linear_layer_1.bias.data.to(torch.float8_e4m3fn)
    apply_custom_layers_to_model(model)

    assert LayerPatcher._is_any_part_of_layer_fp8(model.linear_layer_1)

    lora_layers = {
        "linear_layer_1": LoRALayer.from_state_dict_values(
            values={
                "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.bfloat16),
                "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.bfloat16),
            },
        )
    }
    lora = ModelPatchRaw(lora_layers)

    # force_direct_patching=True would crash on fp8 weights if it were honored; the fp8 guard must
    # override it and route to sidecar patching instead.
    with LayerPatcher.apply_smart_model_patches(
        model=model,
        patches=[(lora, 0.5)],
        prefix="",
        dtype=torch.bfloat16,
        force_direct_patching=True,
    ):
        # A sidecar patch was added to the module rather than the weight being modified in place.
        assert model.linear_layer_1.get_num_patches() == 1

    # After exiting the context, the sidecar patch is cleared.
    assert model.linear_layer_1.get_num_patches() == 0


def test_shape_expanding_patch_excludes_concurrent_model_construction():
    """FLUX Control LoRA shape expansion registers a new nn.Parameter (setattr routes through
    nn.Module.register_parameter). Model construction on another thread monkey-patches
    register_parameter process-wide (accelerate's init_empty_weights) so that any registered
    parameter lands on the meta device. Patch application must therefore hold the
    MODEL_LOAD_LOCK read lock: it must WAIT for an in-flight construction, or the expanded
    parameter would be stranded on meta ("Cannot copy out of meta tensor")."""
    import threading

    from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
    from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer

    small_in_features = 4
    big_in_features = 8
    out_features = 16
    rank = 4

    model = DummyModuleWithOneLayer(small_in_features, out_features, "cpu", torch.float32)
    layer = FluxControlLoRALayer(
        up=torch.ones(out_features, rank),
        mid=None,
        down=torch.ones(rank, big_in_features),
        alpha=float(rank),
        bias=None,
    )
    patch = ModelPatchRaw({"linear_layer_1": layer})

    hijack_installed = threading.Event()
    release_construction = threading.Event()
    original_register_parameter = torch.nn.Module.register_parameter

    def hijacking_register_parameter(module: torch.nn.Module, name: str, param) -> None:
        # Emulate accelerate.init_empty_weights: while the construction patch is installed, ANY
        # registered parameter is rerouted to the meta device.
        if param is not None:
            param = torch.nn.Parameter(param.to("meta"), requires_grad=param.requires_grad)
        original_register_parameter(module, name, param)

    def construct_model() -> None:
        with MODEL_LOAD_LOCK.write_lock():
            torch.nn.Module.register_parameter = hijacking_register_parameter
            try:
                hijack_installed.set()
                release_construction.wait(timeout=30)
            finally:
                torch.nn.Module.register_parameter = original_register_parameter

    result: dict[str, object] = {}

    def apply_patch() -> None:
        with LayerPatcher.apply_smart_model_patches(
            model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.float32, force_direct_patching=True
        ):
            result["device"] = model.linear_layer_1.weight.device.type
            result["shape"] = tuple(model.linear_layer_1.weight.shape)

    constructor = threading.Thread(target=construct_model)
    patcher = threading.Thread(target=apply_patch)
    try:
        constructor.start()
        assert hijack_installed.wait(timeout=10)
        patcher.start()
        # The patcher must block behind the construction's write lock (if it ran now, the hijack
        # would strand its expanded parameter on meta).
        patcher.join(timeout=0.5)
        assert patcher.is_alive(), "patch application must wait for an in-flight model construction"
    finally:
        release_construction.set()
        constructor.join(timeout=10)
        patcher.join(timeout=10)

    assert not patcher.is_alive()
    assert result["device"] == "cpu"
    assert result["shape"] == (out_features, big_in_features)


def test_lazy_patch_iterator_that_constructs_a_model_does_not_deadlock():
    """Regression test for a self-deadlock on cold-cache LoRA patching.

    Callers pass ``patches`` as a lazy generator that constructs each LoRA on demand
    (e.g. flux_text_encoder._t5_lora_iterator -> context.models.load()); a cold-cache
    construction takes MODEL_LOAD_LOCK.write_lock(). MODEL_LOAD_LOCK is a non-reentrant,
    write-preferring readers-writer lock, so consuming such a generator *while the patcher
    holds the read lock* would deadlock (the write acquire waits for readers==0, but the
    consuming thread is that reader). apply_smart_model_patches must therefore materialize
    the iterable before taking the read lock. This test simulates a LoRA load by acquiring
    (and releasing) the write lock during iteration; it must complete, not hang.
    """
    import threading

    from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK

    in_features = 4
    out_features = 16
    rank = 4

    model = DummyModuleWithOneLayer(in_features, out_features, "cpu", torch.float32)
    layer = LoRALayer(
        up=torch.ones(out_features, rank),
        mid=None,
        down=torch.ones(rank, in_features),
        alpha=float(rank),
        bias=None,
    )
    patch = ModelPatchRaw({"linear_layer_1": layer})

    def lazy_patch_iterator():
        # Emulate a cold-cache model construction (context.models.load) that grabs the write lock
        # before the patch tuple is available.
        with MODEL_LOAD_LOCK.write_lock():
            pass
        yield (patch, 1.0)

    result: dict[str, object] = {}

    def apply_patch() -> None:
        with LayerPatcher.apply_smart_model_patches(
            model=model,
            patches=lazy_patch_iterator(),
            prefix="",
            dtype=torch.float32,
            force_direct_patching=True,
        ):
            result["done"] = True

    patcher = threading.Thread(target=apply_patch)
    patcher.start()
    patcher.join(timeout=10)
    assert not patcher.is_alive(), "patching a lazily-constructed LoRA must not deadlock on MODEL_LOAD_LOCK"
    assert result.get("done") is True


def _lora_layer(in_features: int, out_features: int, rank: int = 4, dtype: torch.dtype = torch.float16) -> LoRALayer:
    # fp16 factors by default, under a bf16 compute dtype: the sidecar path then casts them even on CPU, so a
    # placement that is not put back is visible without a GPU.
    return LoRALayer(
        up=torch.ones(out_features, rank, dtype=dtype),
        mid=None,
        down=torch.ones(rank, in_features, dtype=dtype),
        alpha=None,
        bias=None,
    )


def _merged_layer(in_features: int, out_features: int) -> MergedLayerPatch:
    half = out_features // 2
    return MergedLayerPatch(
        lora_layers=[_lora_layer(in_features, half), _lora_layer(in_features, out_features - half)],
        ranges=[Range(0, half), Range(half, out_features)],
    )


def _mixed_dtype_merged_layer(in_features: int, out_features: int) -> MergedLayerPatch:
    # Q/K/V factors converted separately need not share a dtype. Under the bf16 compute dtype only the
    # fp16 half is cast by the sidecar path, so restoring both to one dtype changes the other.
    half = out_features // 2
    return MergedLayerPatch(
        lora_layers=[
            _lora_layer(in_features, half),
            _lora_layer(in_features, out_features - half, dtype=torch.bfloat16),
        ],
        ranges=[Range(0, half), Range(half, out_features)],
    )


def _swapped_halves_layer(in_features: int, out_features: int) -> SwappedHalvesLayerPatch:
    return SwappedHalvesLayerPatch(_lora_layer(in_features, out_features))


def _innermost_loras(layer: BaseLayerPatch) -> list[LoRALayer]:
    if isinstance(layer, MergedLayerPatch):
        return [lora for sub_layer in layer.lora_layers for lora in _innermost_loras(sub_layer)]
    if isinstance(layer, SwappedHalvesLayerPatch):
        return _innermost_loras(layer.layer)
    assert isinstance(layer, LoRALayer)
    return [layer]


def _placements(patch: ModelPatchRaw) -> list[tuple[torch.device, torch.dtype]]:
    """The (device, dtype) of each innermost LoRA factor, in order, so each sub-layer is checked on its own."""
    return [
        (tensor.device, tensor.dtype)
        for layer in patch.layers.values()
        for lora in _innermost_loras(layer)
        for tensor in (lora.up, lora.down)
    ]


@pytest.mark.parametrize(
    "make_layer",
    [_lora_layer, _merged_layer, _mixed_dtype_merged_layer, _swapped_halves_layer],
    ids=["lora", "merged", "mixed_dtype_merged", "swapped_halves"],
)
@pytest.mark.parametrize("force_sidecar", [False, True], ids=["direct", "sidecar"])
@pytest.mark.parametrize(
    "device",
    ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],
)
def test_patching_leaves_the_cached_patch_where_it_found_it(
    make_layer: Callable[[int, int], BaseLayerPatch], force_sidecar: bool, device: str
) -> None:
    """A patch is the model cache's own object, not a copy, and `BaseLayerPatch.to()` rebinds its
    tensors in place. So anything patching does to a patch's device or dtype outlives the patched
    scope, inside a record the cache is still accounting for.

    Both paths used to leave a mark. Direct patching promoted the patch to float32 for the maths and
    returned only its device, permanently doubling the record while the cache went on billing the
    size it measured at `put()`. Sidecar patching moved it onto the compute device and returned
    nothing: `clear_patches()` drops the module's reference, so the tensors stayed on the GPU inside
    a RAM-pinned record -- `cur_vram_bytes()` reports zero for it and `full_unload_from_vram()`
    early-returns, so the cache could not reclaim what it could not see. At a few tens of MB that was
    invisible; at LTX-2's 8.9 GB step-distillation LoRA it is a first-order VRAM consumer.

    Wrapper patches hold their tensors only in sub-patches, so their placement has to be read from
    there too, or the restore is a no-op that strands the inner layers.
    """
    model = DummyModuleWithOneLayer(in_features=8, out_features=16, device=device, dtype=torch.bfloat16)
    apply_custom_layers_to_model(model)
    patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 16)})
    before = _placements(patch)
    before_bytes = patch.calc_size()

    with LayerPatcher.apply_smart_model_patches(
        model=model,
        patches=[(patch, 1.0)],
        prefix="",
        dtype=torch.bfloat16,
        force_direct_patching=not force_sidecar,
        force_sidecar_patching=force_sidecar,
    ):
        # The sidecar path has to keep every sub-layer on the compute device and dtype while the forward needs
        # it. On CPU the cast is the only move, so this also keeps the restore check below from passing vacuously.
        if force_sidecar:
            assert {placement_device.type for placement_device, _ in _placements(patch)} == {device}
            assert {placement_dtype for _, placement_dtype in _placements(patch)} == {torch.bfloat16}

    assert _placements(patch) == before
    assert patch.calc_size() == before_bytes


@pytest.mark.parametrize(
    "input_device",
    ["meta", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],
)
@pytest.mark.parametrize(
    "make_layer", [_lora_layer, _merged_layer, _swapped_halves_layer], ids=["lora", "merged", "swapped_halves"]
)
@torch.no_grad()
def test_sidecar_forward_leaves_the_cached_patch_in_place_during_the_scope(
    make_layer: Callable[[int, int], BaseLayerPatch], input_device: str
) -> None:
    """The sidecar forward moves a copy of each patch to the input's device. For wrapper patches the copy used
    to share its sub-patches with the cached patch, so the first forward moved those off the device the model
    cache accounts them on, until the scope ended."""
    model = DummyModuleWithOneLayer(in_features=8, out_features=16, device="cpu", dtype=torch.bfloat16)
    apply_custom_layers_to_model(model)
    model.linear_layer_1.set_device_autocasting_enabled(True)
    patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 16)})

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_sidecar_patching=True
    ):
        # Whatever placement patching itself chose for the scope; only the forward must not change it.
        during_scope = _placements(patch)
        model(torch.ones(1, 8, device=input_device, dtype=torch.bfloat16))
        assert _placements(patch) == during_scope
        assert all(placement_device.type == "cpu" for placement_device, _ in _placements(patch))


@pytest.mark.parametrize("make_layer", [_lora_layer, _swapped_halves_layer], ids=["lora", "swapped_halves"])
@pytest.mark.parametrize(
    "device",
    ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU"))],
)
def test_direct_patching_that_fails_still_returns_the_cached_patch(
    make_layer: Callable[[int, int], BaseLayerPatch], device: str
) -> None:
    """Direct-patched patches are not in the sidecar restore list, so the direct path has to put the
    patch back itself on every way out. A LoRA built for another shape raises from `get_parameters`
    after the patch has already been moved and promoted to float32."""
    model = DummyModuleWithOneLayer(in_features=8, out_features=16, device=device, dtype=torch.bfloat16)
    apply_custom_layers_to_model(model)
    # 12 output rows cannot be reshaped onto the module's 16.
    patch = ModelPatchRaw(layers={"linear_layer_1": make_layer(8, 12)})
    before = _placements(patch)
    [(leaf, _, _)] = LayerPatcher._leaf_placements(patch.layers["linear_layer_1"])
    up, down = leaf.up, leaf.down

    with pytest.raises(RuntimeError, match="is invalid for input of size"):
        with LayerPatcher.apply_smart_model_patches(
            model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_direct_patching=True
        ):
            pass

    assert _placements(patch) == before
    assert leaf.up is up and leaf.down is down


@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a GPU")
def test_every_layer_of_a_multi_layer_patch_is_returned() -> None:
    """A real LoRA is many layers -- the LTX-2 accelerator is 1660 of them -- and each is moved
    onto the device separately. Restoring only the ones that happen to be reached first would
    strand the remainder, which is the same leak in a form that a single-layer test cannot see."""
    model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=torch.bfloat16)
    apply_custom_layers_to_model(model)
    patch = ModelPatchRaw(
        layers={
            name: LoRALayer(
                up=torch.ones(8, 4, dtype=torch.bfloat16),
                mid=None,
                down=torch.ones(4, 8, dtype=torch.bfloat16),
                alpha=None,
                bias=None,
            )
            for name in ("linear_layer_1", "linear_layer_2")
        }
    )

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.bfloat16, force_sidecar_patching=True
    ):
        pass

    for layer in patch.layers.values():
        assert layer.up.device.type == "cpu"
        assert layer.up.dtype == torch.bfloat16


def _integer_lora(names: Iterable[str], features: int, rank: int = 4) -> ModelPatchRaw:
    """Small integer factors keep `up @ down` exact in fp32 on every device, so results compare bit for bit."""
    generator = torch.Generator().manual_seed(0)
    layers = {}
    for name in names:
        layer = _lora_layer(features, features, rank, dtype=torch.float32)
        layer.up = torch.randint(-2, 3, (features, rank), generator=generator).float()
        layer.down = torch.randint(-2, 3, (rank, features), generator=generator).float()
        layers[name] = layer
    return ModelPatchRaw(layers=layers)


requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA device")


@requires_cuda
@torch.no_grad()
def test_direct_patching_on_a_device_keeps_each_weights_memory_and_matches_out_of_place_math():
    """Patching and restoring in place keeps every weight's allocation, so the allocator pool is not
    left fragmented by a fresh tensor per patched weight."""
    dtype = torch.bfloat16
    model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=dtype)
    apply_custom_layers_to_model(model)
    names = ["linear_layer_1", "linear_layer_2"]
    patch = _integer_lora(names, features=8)
    patch_weight = 0.75

    originals = {name: getattr(model, name).weight.detach().clone() for name in names}
    pointers = {name: getattr(model, name).weight.data_ptr() for name in names}
    expected = {
        name: originals[name]
        + (patch.layers[name].up @ patch.layers[name].down * patch_weight).to(device="cuda", dtype=dtype)
        for name in names
    }

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(patch, patch_weight)], prefix="", dtype=dtype, force_direct_patching=True
    ):
        for name in names:
            weight = getattr(model, name).weight
            assert weight.data_ptr() == pointers[name]
            assert torch.equal(weight, expected[name])

    for name in names:
        weight = getattr(model, name).weight
        assert weight.data_ptr() == pointers[name]
        assert torch.equal(weight, originals[name])


@requires_cuda
@torch.no_grad()
def test_direct_patching_does_not_reach_a_parameter_over_the_same_storage():
    """The model cache binds tied weights (a text encoder's `lm_head` and `embed_tokens`) as separate parameters
    over one tensor. An in-place patch of one would change the other, so that weight is replaced instead."""
    dtype = torch.bfloat16
    model = DummyModuleWithTwoLayers(in_features=8, out_features=8, device="cuda", dtype=dtype)
    apply_custom_layers_to_model(model)
    model.linear_layer_2.weight = torch.nn.Parameter(model.linear_layer_1.weight.data)
    original = model.linear_layer_1.weight.detach().clone()

    with LayerPatcher.apply_smart_model_patches(
        model=model,
        patches=[(_integer_lora(["linear_layer_1"], features=8), 1.0)],
        prefix="",
        dtype=dtype,
        force_direct_patching=True,
    ):
        assert not torch.equal(model.linear_layer_1.weight, original)
        assert torch.equal(model.linear_layer_2.weight, original)

    assert torch.equal(model.linear_layer_1.weight, original)
    assert torch.equal(model.linear_layer_2.weight, original)


@pytest.mark.parametrize("device", ["cpu", pytest.param("cuda", marks=requires_cuda)])
@torch.no_grad()
def test_flux_control_lora_expands_the_weight_for_the_scope_and_restores_its_shape(device: str):
    model = DummyModuleWithOneLayer(4, 16, device=device, dtype=torch.float32)
    apply_custom_layers_to_model(model)
    original = model.linear_layer_1.weight.detach().clone()
    patch = ModelPatchRaw(
        layers={
            "linear_layer_1": FluxControlLoRALayer(
                up=torch.ones(16, 4), mid=None, down=torch.ones(4, 8), alpha=torch.tensor(4.0), bias=None
            )
        }
    )

    with LayerPatcher.apply_smart_model_patches(
        model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.float32, force_direct_patching=True
    ):
        expanded = model.linear_layer_1.weight
        assert expanded.shape == (16, 8)
        # The original columns carry the patch and the new ones only the patch.
        assert torch.equal(expanded[:, :4], original + 4.0)
        assert torch.equal(expanded[:, 4:], torch.full((16, 4), 4.0, device=device))

    assert model.linear_layer_1.weight.shape == original.shape
    assert torch.equal(model.linear_layer_1.weight, original)


@requires_cuda
@torch.no_grad()
def test_restore_follows_the_current_parameter_when_the_model_left_the_device_during_the_scope():
    """An offload with a RAM copy rebinds the weight to the canonical CPU tensor. The restore must replace it
    rather than write the original into the canonical copy."""
    dtype = torch.bfloat16
    model = DummyModuleWithOneLayer(8, 8, device="cuda", dtype=dtype)
    apply_custom_layers_to_model(model)
    original = model.linear_layer_1.weight.detach().clone()
    canonical = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
    canonical_before = {k: v.clone() for k, v in canonical.items()}

    with LayerPatcher.apply_smart_model_patches(
        model=model,
        patches=[(_integer_lora(["linear_layer_1"], features=8), 1.0)],
        prefix="",
        dtype=dtype,
        force_direct_patching=True,
    ):
        model.load_state_dict(canonical, assign=True)

    assert all(torch.equal(canonical[k], canonical_before[k]) for k in canonical)
    assert torch.equal(model.linear_layer_1.weight.cpu(), original.cpu())