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.

13.9 KB
Raw Blame
"""Tests for DefaultSessionRunner._maybe_offload_to_idle_gpu (idle-GPU text-encoder offload).

These exercise the re-pinning + borrow-lock logic without needing real CUDA: the session device is
a thread-local set via TorchDevice, and the device pool only manipulates locks keyed by device
string.
"""

import logging
import threading
import time
from collections.abc import Iterator
from types import SimpleNamespace
from unittest.mock import patch

import pytest
import torch

from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner
from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL
from invokeai.backend.util.devices import TorchDevice


@pytest.fixture(autouse=True)
def reset_state() -> Iterator[None]:
    GENERATION_DEVICE_POOL.reset()
    # These tests intentionally model a two-GPU pool on machines with any
    # hardware topology. Keep the real pool/session-pin behavior under test,
    # but do not let the runner switch torch to the fictional second device.
    target = "invokeai.backend.util.device_pool.set_torch_current_device"
    # The borrow records torch's current device to restore it; report the thread's pin rather than
    # asking a real (or absent) GPU.
    current = "invokeai.backend.util.device_pool._torch_current_device"
    with patch(target), patch(current, side_effect=lambda device_type: TorchDevice.get_session_device()):
        try:
            yield
        finally:
            TorchDevice.clear_session_device()
            GENERATION_DEVICE_POOL.reset()


class _FakeInvocation:
    def __init__(self, idle_gpu_offloadable: bool, type_str: str = "fake_node"):
        self.idle_gpu_offloadable = idle_gpu_offloadable
        self._type_str = type_str

    def get_type(self) -> str:
        return self._type_str


class _FakeConfig:
    def __init__(self, enabled: bool = True):
        self.offload_text_encoders_to_idle_gpus = enabled


class _FakeServices:
    def __init__(self, enabled: bool = True):
        self.configuration = _FakeConfig(enabled)
        self.logger = logging.getLogger("test-encoder-offload")
        # model_manager.load is None-able in production (some tests run without a model manager);
        # the offload path must tolerate that.
        self.model_manager = SimpleNamespace(load=None)


def _runner(enabled: bool = True) -> DefaultSessionRunner:
    runner = DefaultSessionRunner()
    runner._services = _FakeServices(enabled)  # type: ignore[assignment]
    return runner


def test_encoder_node_repins_to_idle_gpu_and_restores():
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
        # Re-pinned to the borrowed idle GPU for the duration of the node...
        assert TorchDevice.get_session_device() == torch.device("cuda:1")
        # ...and that GPU is locked, so nothing else can borrow it.
        assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) is None

    # Pin restored and the borrow released.
    assert TorchDevice.get_session_device() == torch.device("cuda:0")
    assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")


def test_borrow_is_released_when_repinning_fails():
    """A failure while re-pinning must not strand the borrow lock.

    The lock is process-wide, so leaking it would make that GPU permanently unborrowable — a
    silent, permanent loss of the idle-GPU offload with no error after the first one.
    """
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    target = "invokeai.backend.util.device_pool.set_torch_current_device"
    with patch(target, side_effect=RuntimeError("CUDA driver shutting down")):
        with pytest.raises(RuntimeError, match="driver shutting down"):
            with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
                pass

    # The idle GPU is borrowable again, and the session pin was restored.
    assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")
    assert TorchDevice.get_session_device() == torch.device("cuda:0")


def test_non_encoder_node_is_not_offloaded():
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    with runner._maybe_offload_to_idle_gpu(_FakeInvocation(False, "denoise_latents")):
        assert TorchDevice.get_session_device() == torch.device("cuda:0")
    # Idle device was never borrowed.
    assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")


def test_no_offload_when_target_running_a_session():
    """With both GPUs busy (the other holds a session lock), the encoder stays on its own GPU."""
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")
    GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:1"))
    try:
        with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
            assert TorchDevice.get_session_device() == torch.device("cuda:0")
    finally:
        GENERATION_DEVICE_POOL.release_session(torch.device("cuda:1"))


def test_flag_off_disables_offload():
    runner = _runner(enabled=False)
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
        assert TorchDevice.get_session_device() == torch.device("cuda:0")
    assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")


def test_borrow_released_on_exception():
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    with pytest.raises(RuntimeError):
        with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
            raise RuntimeError("node failed")

    # The pin is restored and the borrow lock released even though the node raised.
    assert TorchDevice.get_session_device() == torch.device("cuda:0")
    assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")


def test_single_gpu_never_offloads():
    runner = _runner()
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0")])
    TorchDevice.set_session_device("cuda:0")

    with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
        assert TorchDevice.get_session_device() == torch.device("cuda:0")


def test_concurrent_workers_never_share_a_gpu():
    """Regression for the garbled-image bug: two sessions running at once must never use the same
    GPU for an encoder concurrently. Each worker holds its own GPU's session lock (as the processor
    does) and runs encoder nodes that may borrow the other GPU through the real offload path; we
    assert no GPU is ever occupied by two workers at the same time.

    Before the fix, a startup race let one worker offload its encoder onto the other's GPU while
    that GPU also ran a native session — both touching the same cached encoder. This test exercises
    that exact interleaving and would flag it as occupancy > 1.
    """
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])

    occupancy = {"cuda:0": 0, "cuda:1": 0}
    occ_lock = threading.Lock()
    violations: list[str] = []

    def occupy(device_str: str) -> None:
        with occ_lock:
            occupancy[device_str] += 1
            if occupancy[device_str] > 1:
                violations.append(device_str)

    def vacate(device_str: str) -> None:
        with occ_lock:
            occupancy[device_str] -= 1

    def worker(own: str) -> None:
        runner = _runner()
        own_device = torch.device(own)
        encoder = _FakeInvocation(True, "flux_text_encoder")
        for _ in range(150):
            # The processor holds the device's session lock for the whole run.
            GENERATION_DEVICE_POOL.acquire_session(own_device)
            TorchDevice.set_session_device(own_device)
            occupy(own)
            try:
                with runner._maybe_offload_to_idle_gpu(encoder):
                    current = str(TorchDevice.get_session_device())
                    if current != own:
                        # The node was re-pinned to a borrowed GPU; it must be exclusively ours.
                        occupy(current)
                        try:
                            time.sleep(0.0002)
                        finally:
                            vacate(current)
                    else:
                        time.sleep(0.0001)
            finally:
                vacate(own)
                TorchDevice.clear_session_device()
                GENERATION_DEVICE_POOL.release_session(own_device)

    threads = [threading.Thread(target=worker, args=(d,)) for d in ("cuda:0", "cuda:1")]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    assert not violations, f"GPU(s) used by two workers at once: {set(violations)}"


def test_offloaded_encoder_stats_attributed_to_running_session():
    """An offloaded encoder's cache activity must land in the RUNNING session's CacheStats.
    collect_stats() attaches the session's stats to the native device's cache; when the node is
    re-pinned to a borrowed GPU, the borrowed cache's stats still point at whatever session last
    ran there. The offload context must temporarily point the borrowed cache at the native cache's
    stats and restore afterwards."""

    class _FakeCache:
        def __init__(self, name: str):
            self.stats = SimpleNamespace(owner=name)

    native_cache = _FakeCache("running-session")
    borrowed_cache = _FakeCache("stale-previous-session")
    native_stats = native_cache.stats
    borrowed_stale_stats = borrowed_cache.stats
    caches = {"cuda:0": native_cache, "cuda:1": borrowed_cache}

    class _FakeLoad:
        @property
        def ram_cache(self):
            return caches[str(TorchDevice.get_session_device())]

    runner = _runner()
    runner._services.model_manager = SimpleNamespace(load=_FakeLoad())  # type: ignore[attr-defined]
    GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])
    TorchDevice.set_session_device("cuda:0")

    with runner._maybe_offload_to_idle_gpu(_FakeInvocation(True, "flux_text_encoder")):
        # Encoder loads on the borrowed device now record into the running session's stats object.
        assert borrowed_cache.stats is native_stats

    # The borrowed cache's own stats pointer is restored; the native one was never touched.
    assert borrowed_cache.stats is borrowed_stale_stats
    assert native_cache.stats is native_stats


def test_real_nodes_declare_the_marker_correctly():
    """The @invocation(idle_gpu_offloadable=...) marker is wired through to the class, and is set on
    encoder nodes but not on ordinary nodes."""
    from invokeai.app.invocations.primitives import IntegerInvocation
    from invokeai.app.invocations.text_encoder.compel import CompelInvocation
    from invokeai.app.invocations.text_encoder.flux_text_encoder import FluxTextEncoderInvocation

    assert FluxTextEncoderInvocation.idle_gpu_offloadable is True
    assert CompelInvocation.idle_gpu_offloadable is True
    # A non-encoder node defaults to False (never re-pinned to a borrowed GPU).
    assert IntegerInvocation.idle_gpu_offloadable is False


def test_every_text_encoder_node_declares_the_marker():
    """Every `*_text_encoder` node must carry the flag.

    Four encoders (wan, krea2, ideogram4, ernie_image) were added after the flag landed and went
    unmarked for several releases — on a multi-GPU box they silently ran on the session's own GPU,
    holding VRAM the denoise model needed. Enumerating the registry rather than listing the known
    encoders is deliberate: the next encoder to be added is the one this guards.

    A text encoder that genuinely should not be offloaded (it does session-GPU work, or runs long
    enough that holding the lent GPU's lock would stall a session dequeued onto it) belongs in
    `_NOT_OFFLOADABLE` with a comment saying why.
    """
    # Importing the package imports every node module in its tree, which is what registers them.
    import invokeai.app.invocations  # noqa: F401
    from invokeai.app.invocations.baseinvocation import InvocationRegistry

    # Encoders that must NOT be offloadable. Empty today; add with a justification.
    _NOT_OFFLOADABLE: set[str] = set()

    encoders = {
        cls.get_type(): cls.idle_gpu_offloadable
        for cls in InvocationRegistry.get_invocation_classes()
        if cls.get_type().endswith("_text_encoder")
    }
    # Sanity-check the enumeration itself: if this drops to nothing, the assertion below is vacuous.
    assert len(encoders) >= 11, f"expected the known text encoders to be registered, got {sorted(encoders)}"

    unmarked = sorted(t for t, flag in encoders.items() if not flag and t not in _NOT_OFFLOADABLE)
    assert not unmarked, (
        f"text-encoder nodes missing idle_gpu_offloadable=True: {unmarked}. "
        "Add the flag to the @invocation decorator, or add the type to _NOT_OFFLOADABLE with a reason."
    )
    # The four that prompted this guard, named explicitly so a rename cannot silently drop them.
    for node_type in ("wan_text_encoder", "krea2_text_encoder", "ideogram4_text_encoder", "ernie_image_text_encoder"):
        assert encoders.get(node_type) is True, f"{node_type} is not registered as an offloadable text encoder"