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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(gpu): run prompt tools and image embedding on an idle GPU
Lincoln Steind8abddd43dc0
diff --git a/docs/src/content/docs/configuration/invokeai-yaml.mdx b/docs/src/content/docs/configuration/invokeai-yaml.mdxindex 289052025a..9904bed1dc 100644--- a/docs/src/content/docs/configuration/invokeai-yaml.mdx+++ b/docs/src/content/docs/configuration/invokeai-yaml.mdx@@ -169,6 +169,12 @@ Notes:- It is purely a placement optimization and does not change generated images.- A borrowed GPU is used exclusively for the encoder while it runs, so it never interferes with a generation session running on that same GPU.+#### Prompt Tools and Image Indexing on Multiple GPUs++**Expand Prompt**, **Image to Prompt** and image embedding for the image map and search by image run outside the generation queue. With two or more GPUs configured, each such request takes an idle GPU for as long as it runs — the first idle one in `generation_devices` order — so it no longer competes for memory with a generation running on another GPU. While a GPU is lent this way, queued generations start on the other GPUs rather than waiting for it, and these requests never take every GPU at once, so the queue always has one to start on. When no GPU can be taken, the request runs on the default device as it did before. There is no setting for this, and a single-GPU install behaves as it always has.++Background indexing of new images already waits until no generation is running, so it simply takes the first idle GPU; it is search by image that benefits during a generation.+#### Image Subfolder StrategyBy default, generated images are stored in a single flat directory under `outputs/images/`. The `image_subfolder_strategy` setting lets you organize newly-created images into subfolders automatically. You can edit this setting in `invokeai.yaml` or, as an admin user, in the Settings panel.diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex f47a22702e..ae60341195 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -2,6 +2,7 @@ import asyncioimport loggingimport reimport threading+from contextlib import ExitStackfrom pathlib import Pathfrom typing import Optionalfrom urllib.parse import quote@@ -34,6 +35,7 @@ from invokeai.app.util.misc import SEED_MAX, get_random_seedfrom invokeai.backend.llava_onevision_pipeline import LlavaOnevisionPipelinefrom invokeai.backend.model_manager.taxonomy import ModelTypefrom invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, ProgressCallback, TextLLMPipeline+from invokeai.backend.util.device_pool import idle_device_borrowedfrom invokeai.backend.util.devices import TorchDevicelogger = logging.getLogger(__name__)@@ -466,26 +468,31 @@ def _run_expand_prompt(else AutoTokenizer.from_pretrained(model_abs_path, local_files_only=True))- with _model_load_lock:- loaded_model = model_manager.load.load_model(model_config, user_id=user_id)-- with torch.no_grad(), loaded_model.model_on_device() as (_, model):- pipeline = TextLLMPipeline(model, tokenizer, processor)- model_device = next(model.parameters()).device-- progress_callback = _make_progress_callback(events, task_id, user_id)-- effective_seed = seed if seed is not None else get_random_seed()- output = pipeline.run(- prompt=prompt,- system_prompt=system_prompt or DEFAULT_SYSTEM_PROMPT,- max_new_tokens=max_tokens,- seed=effective_seed,- device=model_device,- dtype=TorchDevice.choose_torch_dtype(),- progress_callback=progress_callback,- image=image,- )+ # Outside the session queue: take an idle GPU (and its lock) for the load and the run. The borrow is+ # taken once the load lock is ours, so a request queued behind another's load holds no GPU meanwhile;+ # borrowing never blocks, so this ordering cannot deadlock.+ with ExitStack() as gpu:+ with _model_load_lock:+ gpu.enter_context(idle_device_borrowed(purpose="Expand Prompt"))+ loaded_model = model_manager.load.load_model(model_config, user_id=user_id)++ with torch.no_grad(), loaded_model.model_on_device() as (_, model):+ pipeline = TextLLMPipeline(model, tokenizer, processor)+ model_device = next(model.parameters()).device++ progress_callback = _make_progress_callback(events, task_id, user_id)++ effective_seed = seed if seed is not None else get_random_seed()+ output = pipeline.run(+ prompt=prompt,+ system_prompt=system_prompt or DEFAULT_SYSTEM_PROMPT,+ max_new_tokens=max_tokens,+ seed=effective_seed,+ device=model_device,+ dtype=TorchDevice.choose_torch_dtype(),+ progress_callback=progress_callback,+ image=image,+ )return output, effective_seed@@ -575,34 +582,36 @@ def _run_image_to_prompt(if task_id is not None:events.emit_llm_task_progress(task_id=task_id, user_id=user_id, phase="loading_model", message="Loading model")- with _model_load_lock:- loaded_model = model_manager.load.load_model(model_config, user_id=user_id)-- # Load the image from InvokeAI's image store.- image = ApiDependencies.invoker.services.images.get_pil_image(image_name)- image = image.convert("RGB")-- with torch.no_grad(), loaded_model.model_on_device() as (_, model):- if not isinstance(model, LlavaOnevisionForConditionalGeneration):- raise TypeError(f"Expected LlavaOnevisionForConditionalGeneration, got {type(model).__name__}")-- model_abs_path = _resolve_model_path(model_config.path)- processor = AutoProcessor.from_pretrained(model_abs_path, local_files_only=True)- if not isinstance(processor, LlavaOnevisionProcessor):- raise TypeError(f"Expected LlavaOnevisionProcessor, got {type(processor).__name__}")-- pipeline = LlavaOnevisionPipeline(model, processor)- model_device = next(model.parameters()).device-- progress_callback = _make_progress_callback(events, task_id, user_id)-- output = pipeline.run(- prompt=instruction,- images=[image],- device=model_device,- dtype=TorchDevice.choose_torch_dtype(),- progress_callback=progress_callback,- )+ # Read before the borrow below, so neither disk read holds a GPU.+ image = ApiDependencies.invoker.services.images.get_pil_image(image_name).convert("RGB")+ processor = AutoProcessor.from_pretrained(_resolve_model_path(model_config.path), local_files_only=True)+ if not isinstance(processor, LlavaOnevisionProcessor):+ raise TypeError(f"Expected LlavaOnevisionProcessor, got {type(processor).__name__}")++ # Outside the session queue: take an idle GPU (and its lock) for the load and the run. The borrow is+ # taken once the load lock is ours, so a request queued behind another's load holds no GPU meanwhile;+ # borrowing never blocks, so this ordering cannot deadlock.+ with ExitStack() as gpu:+ with _model_load_lock:+ gpu.enter_context(idle_device_borrowed(purpose="Image to Prompt"))+ loaded_model = model_manager.load.load_model(model_config, user_id=user_id)++ with torch.no_grad(), loaded_model.model_on_device() as (_, model):+ if not isinstance(model, LlavaOnevisionForConditionalGeneration):+ raise TypeError(f"Expected LlavaOnevisionForConditionalGeneration, got {type(model).__name__}")++ pipeline = LlavaOnevisionPipeline(model, processor)+ model_device = next(model.parameters()).device++ progress_callback = _make_progress_callback(events, task_id, user_id)++ output = pipeline.run(+ prompt=instruction,+ images=[image],+ device=model_device,+ dtype=TorchDevice.choose_torch_dtype(),+ progress_callback=progress_callback,+ )return outputdiff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 8cdf42f65d..b10ede6d46 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -28,6 +28,7 @@ from invokeai.app.services.videos.videos_common import VideoDTOfrom invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCKfrom invokeai.backend.model_manager.load.optimizations import skip_torch_weight_initfrom invokeai.backend.model_manager.taxonomy import ModelType+from invokeai.backend.util.device_pool import idle_device_borrowedfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.load_report import suppress_load_report@@ -1763,8 +1764,11 @@ class ImageIndexService(ImageIndexServiceBase):self._cpu_model = modelreturn self._embed(self._cpu_model, images, torch.device("cpu"))- loaded = self._invoker.services.model_manager.load.load_model(self._model_config)- with loaded.model_on_device() as (_, model):- # The cache decides where the model actually lives; follow it.- device = next(model.parameters()).device- return self._embed(model, images, device)+ # This runs outside the session queue (the index worker, or a request thread), so it takes an+ # idle GPU and its lock for the batch instead of sharing a busy GPU's cache with a session.+ with idle_device_borrowed(purpose="Image embedding"):+ loaded = self._invoker.services.model_manager.load.load_model(self._model_config)+ with loaded.model_on_device() as (_, model):+ # The cache decides where the model actually lives; follow it.+ device = next(model.parameters()).device+ return self._embed(model, images, device)diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex 9354ffc6c2..140238896c 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -45,7 +45,10 @@ from invokeai.app.services.session_queue.session_queue_common import (from invokeai.app.services.shared.graph import CollectInvocation, IterateInvocation, NodeInputErrorfrom invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_contextfrom invokeai.app.util.profiler import Profiler-from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+from invokeai.backend.util.device_pool import (+ GENERATION_DEVICE_POOL,+ idle_device_borrowed,+)from invokeai.backend.util.devices import TorchDevice, disable_conv_benchmark_empty_cache# A failed owner lookup is retried before the item is refused, so that a transient error@@ -127,25 +130,6 @@ def queue_owner_is_active(return False-def _set_torch_current_device(device: torch.device) -> None:- """Mirror a session-device pin onto torch's per-thread current device.-- CUDA and XPU both track a current device per thread, and index-less allocations- (e.g. ``torch.zeros(2, device="xpu")``) resolve through it. Setting only the- session device would leave such allocations on whichever GPU the thread was last- pinned to -- for a borrowed idle GPU, that is the busy denoise device the offload- exists to protect.-- Availability is checked first, mirroring TorchDevice.normalize: generation devices- can be configured (or, in tests, faked) for a backend this process cannot actually- initialise, and set_device would then fail or block on backend init.- """- if device.type == "cuda" and torch.cuda.is_available():- torch.cuda.set_device(device)- elif device.type == "xpu" and hasattr(torch, "xpu") and torch.xpu.is_available():- torch.xpu.set_device(device)--class DefaultSessionRunner(SessionRunnerBase):"""Processes a single session's invocations."""@@ -449,43 +433,32 @@ class DefaultSessionRunner(SessionRunnerBase):yieldreturn- borrowed_device = GENERATION_DEVICE_POOL.try_borrow(exclude=native_device)- if borrowed_device is None:- yield- return+ load = self._services.model_manager.load+ # Read while the thread is still pinned to its own GPU.+ native_cache = load.ram_cache if load is not None else None+ with idle_device_borrowed(exclude=native_device) as borrowed_device:+ if borrowed_device is None:+ yield+ return- self._services.logger.debug(- f"Running {invocation.get_type()} on idle device {borrowed_device} (session device {native_device})."- )- # Attribute the borrowed cache's activity to the RUNNING session. collect_stats() attached- # this session's CacheStats to the native device's cache before we re-pinned; the borrowed- # cache's .stats still points at whatever session last ran on that device — possibly an- # already-summarized one — so without this swap the encoder's cache hits/misses would be- # lost to (or corrupt) another session's numbers.- # Everything after the borrow succeeds must be inside the try: if re-pinning or the stats- # swap raises, the borrow lock has to be released anyway, or this GPU stays locked for the- # life of the process and can never be borrowed again.- native_cache = None- borrowed_cache = None- saved_borrowed_stats = None- try:- load = self._services.model_manager.load- native_cache = load.ram_cache if load is not None else None- TorchDevice.set_session_device(borrowed_device)- _set_torch_current_device(borrowed_device)+ self._services.logger.debug(+ f"Running {invocation.get_type()} on idle device {borrowed_device} (session device {native_device})."+ )+ # Attribute the borrowed cache's activity to the RUNNING session. collect_stats() attached+ # this session's CacheStats to the native device's cache before we re-pinned; the borrowed+ # cache's .stats still points at whatever session last ran on that device — possibly an+ # already-summarized one — so without this swap the encoder's cache hits/misses would be+ # lost to (or corrupt) another session's numbers.borrowed_cache = load.ram_cache if load is not None else None- saved_borrowed_stats = borrowed_cache.stats if borrowed_cache is not None else None- if borrowed_cache is not None and native_cache is not None and borrowed_cache is not native_cache:- borrowed_cache.stats = native_cache.stats- yield- finally:+ swap_stats = borrowed_cache is not None and native_cache is not None and borrowed_cache is not native_cache+ saved_borrowed_stats = borrowed_cache.stats if swap_stats else Nonetry:- if borrowed_cache is not None and borrowed_cache is not native_cache:- borrowed_cache.stats = saved_borrowed_stats- TorchDevice.set_session_device(native_device)- _set_torch_current_device(native_device)+ if swap_stats:+ borrowed_cache.stats = native_cache.stats+ yieldfinally:- GENERATION_DEVICE_POOL.release_borrow(borrowed_device)+ if swap_stats:+ borrowed_cache.stats = saved_borrowed_statsdef _on_before_run_session(self, queue_item: SessionQueueItem) -> None:"""Called before a session is run.@@ -765,6 +738,8 @@ class DefaultSessionProcessor(SessionProcessorBase):# Register the generation devices so the model loader can discover idle GPUs to host text# encoders on (see offload_text_encoders_to_idle_gpus). None means legacy single-device mode.GENERATION_DEVICE_POOL.set_generation_devices([d for d in devices if d is not None])+ # A worker that stood aside for a lent GPU re-polls as soon as that borrow ends.+ GENERATION_DEVICE_POOL.set_release_listener(self._poll_now_event.set)# With more than one CUDA/HIP generation device, torch's post-conv-algorithm-search global# emptyCache() convoys the peer GPU's in-flight step from C++, where the peer-aware@@ -1093,6 +1068,12 @@ class DefaultSessionProcessor(SessionProcessorBase):# stays set and is caught by the runner's _is_canceled() check.worker.cancel_event.clear()+ # While this GPU is lent to a borrower, a session claimed here would only wait for the+ # borrow to end; leave the item for a free GPU. Every release wakes the workers.+ if GENERATION_DEVICE_POOL.is_lent(worker.device):+ poll_now_event.wait(self._polling_interval)+ continue+# Get the next session to process. dequeue() atomically claims the item, so concurrent# workers never receive the same item. Pass this worker's device so the item is# tagged with the GPU that ran it (None in single-device/legacy mode).@@ -1108,7 +1089,7 @@ class DefaultSessionProcessor(SessionProcessorBase):if device_pin_needed:assert worker.device is not None- # Called directly rather than via _set_torch_current_device(): that helper+ # Called directly rather than via set_torch_current_device(): that helper# skips the pin when the backend reports unavailable, which is right for the# idle-GPU borrow (devices there can be configured or faked for a backend# this process cannot initialise) but would silently drop the pin thisdiff --git a/invokeai/backend/util/device_pool.py b/invokeai/backend/util/device_pool.pyindex 6e7e57aa55..e904416068 100644--- a/invokeai/backend/util/device_pool.py+++ b/invokeai/backend/util/device_pool.py@@ -1,9 +1,12 @@-"""Process-global arbiter that lends idle generation GPUs for text-encoder offload.+"""Process-global arbiter that lends idle generation GPUs.In multi-GPU mode (see ``generation_devices``) the session processor runs one generation workerper GPU. When fewer sessions are running than there are GPUs, some GPUs sit idle. This arbiter letsa busy worker temporarily *borrow* an idle GPU to host a text encoder, instead of churning the busy-GPU's denoise model in and out of VRAM.+GPU's denoise model in and out of VRAM. Model work that runs outside the session queue (Expand+Prompt, Image to Prompt, image-index embedding) borrows the same way, via :func:`idle_device_borrowed`,+so it lands on an idle GPU rather than beside a running session; when it cannot borrow, it runs+unlocked on the default device as it always did.Correctness hinges on one rule: **a borrowed GPU must never run an encoder at the same time as anative generation session on that same GPU.** They share that device's single ``ModelCache``, and a@@ -18,9 +21,10 @@ To enforce the rule, each generation device has one lock used for *both* roles:encoder runs on the worker's own GPU instead.Because borrows are non-blocking try-acquires and a session only ever blocking-acquires its *own*-device lock, there is no lock-ordering cycle — the design is deadlock-free. The cost is that, in the-startup race where a borrow wins the lock a moment before the lent GPU's own session starts, that-session waits out the whole borrowed node before beginning.+device lock, there is no lock-ordering cycle — the design is deadlock-free. A worker whose GPU is+lent does not claim queue items (see :meth:`_GenerationDevicePool.is_lent`), so they go to a free GPU+instead, and every release wakes the workers. What remains is the startup race where a borrow wins the+lock between a worker's check and its claim: that session waits out the borrow before beginning.Note that "the whole borrowed node" includes the encoder's *model load*. Caches are per-device, sothe first borrow of a given GPU always cold-loads the encoder into that GPU's cache — seconds, not@@ -34,11 +38,14 @@ that ``ernie_image_text_encoder`` can stay offloadable."""import threading-from typing import Optional+from collections.abc import Iterator+from contextlib import contextmanager+from typing import Callable, Optionalimport torchfrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.logging import InvokeAILogger# Device types that can lend/borrow for idle offload. MPS is excluded: it is always a single# shared device, so there is never another GPU to borrow.@@ -55,6 +62,17 @@ class _GenerationDevicePool:# normalized device string -> that device's exclusive-use lock.self._device_locks: dict[str, threading.Lock] = {}self._order: list[str] = []+ # Devices currently lent to a borrower, and the subset lent to work outside the session queue.+ # Guarded by _registry_lock; a device joins these only while its lock is held by the borrow.+ self._lent: set[str] = set()+ self._lent_off_queue: set[str] = set()+ # Called after every borrow is released, so a worker that stood aside can claim work at once.+ self._on_release: Optional[Callable[[], None]] = None++ def set_release_listener(self, listener: Optional[Callable[[], None]]) -> None:+ """Call ``listener`` (no arguments, any thread) after each borrow is released."""+ with self._registry_lock:+ self._on_release = listenerdef set_generation_devices(self, devices: list[torch.device]) -> None:"""Register the full set of generation devices (called once at processor startup).@@ -64,6 +82,8 @@ class _GenerationDevicePool:with self._registry_lock:self._device_locks = {}self._order = []+ self._lent = set()+ self._lent_off_queue = set()for device in devices:if device.type not in _OFFLOAD_DEVICE_TYPES:continue@@ -113,23 +133,61 @@ class _GenerationDevicePool:"""if exclude.type not in _OFFLOAD_DEVICE_TYPES:return None- exclude_key = str(TorchDevice.normalize(exclude))+ return self._try_acquire(exclude.type, exclude_key=str(TorchDevice.normalize(exclude)), off_queue=False)++ def try_borrow_off_queue(self, device_type: str) -> Optional[torch.device]:+ """Try to take an idle GPU of ``device_type`` for work outside the session queue (non-blocking).++ Same contract and selection order as :meth:`try_borrow`, with one extra refusal that keeps the+ queue moving, since such work (a prompt rewrite, say) can hold a GPU for a minute: never take+ a GPU if that would leave every GPU of the type lent to off-queue work, so the queue always+ has one to start on. A single-GPU install therefore never borrows, and keeps running+ off-queue work unlocked beside sessions as it always has, rather than making the next session+ wait for it.+ """+ if device_type not in _OFFLOAD_DEVICE_TYPES:+ return None+ return self._try_acquire(device_type, exclude_key=None, off_queue=True)++ def _try_acquire(self, device_type: str, exclude_key: Optional[str], off_queue: bool) -> Optional[torch.device]:+ # The whole selection runs under the registry lock so the off-queue refusals are checked and the+ # claim recorded atomically. Every acquire here is non-blocking, and acquire_session never holds+ # the registry lock while it blocks, so this cannot deadlock.with self._registry_lock:- candidates = [- (key, self._device_locks[key])- for key in self._order- if key != exclude_key and torch.device(key).type == exclude.type- ]- for key, lock in candidates:- if lock.acquire(blocking=False):- return torch.device(key)+ same_type = [key for key in self._order if torch.device(key).type == device_type]+ if off_queue and len(self._lent_off_queue.intersection(same_type)) + 1 >= len(same_type):+ return None+ for key in same_type:+ if key != exclude_key and self._device_locks[key].acquire(blocking=False):+ self._lent.add(key)+ if off_queue:+ self._lent_off_queue.add(key)+ return torch.device(key)return None+ def is_lent(self, device: Optional[torch.device]) -> bool:+ """True while ``device`` is lent to a borrower.++ A worker checks this before claiming a queue item: its session would only wait for the borrow+ to end, while another worker's GPU may be free to run the item now.+ """+ if device is None:+ return False+ with self._registry_lock:+ return str(TorchDevice.normalize(device)) in self._lent+def release_borrow(self, device: torch.device) -> None:- """Release a device taken by :meth:`try_borrow`."""- lock = self._get_lock(device)+ """Release a device taken by :meth:`try_borrow` or :meth:`try_borrow_off_queue`."""+ key = str(TorchDevice.normalize(device))+ with self._registry_lock:+ lock = self._device_locks.get(key)+ self._lent.discard(key)+ self._lent_off_queue.discard(key)+ listener = self._on_releaseif lock is not None:lock.release()+ if listener is not None:+ listener()def any_other_device_busy(self, device: Optional[torch.device]) -> bool:"""True when any registered generation device OTHER than ``device`` is in use.@@ -153,7 +211,97 @@ class _GenerationDevicePool:with self._registry_lock:self._device_locks = {}self._order = []+ self._lent = set()+ self._lent_off_queue = set()+ self._on_release = None# Process-global singleton.GENERATION_DEVICE_POOL = _GenerationDevicePool()+++def set_torch_current_device(device: torch.device) -> None:+ """Mirror a session-device pin onto torch's per-thread current device.++ CUDA and XPU both track a current device per thread, and index-less allocations+ (e.g. ``torch.zeros(2, device="xpu")``) resolve through it. Setting only the+ session device would leave such allocations on whichever GPU the thread was last+ pinned to -- for a borrowed idle GPU, that is the busy device the borrow exists to protect.++ Availability is checked first, mirroring TorchDevice.normalize: generation devices+ can be configured (or, in tests, faked) for a backend this process cannot actually+ initialise, and set_device would then fail or block on backend init.+ """+ if device.type == "cuda" and torch.cuda.is_available():+ torch.cuda.set_device(device)+ elif device.type == "xpu" and hasattr(torch, "xpu") and torch.xpu.is_available():+ torch.xpu.set_device(device)+++def _torch_current_device(device_type: str) -> Optional[torch.device]:+ """The calling thread's current torch device of ``device_type``, or None when that backend is unavailable."""+ if device_type == "cuda" and torch.cuda.is_available():+ return torch.device("cuda", torch.cuda.current_device())+ if device_type == "xpu" and hasattr(torch, "xpu") and torch.xpu.is_available():+ return torch.device("xpu", torch.xpu.current_device())+ return None+++@contextmanager+def idle_device_borrowed(+ exclude: Optional[torch.device] = None, purpose: Optional[str] = None+) -> Iterator[Optional[torch.device]]:+ """Pin the calling thread to an idle generation GPU for the duration of the block.++ Inside the block every device-selecting call (``TorchDevice.choose_torch_device``, the model+ loader's per-device cache, index-less torch allocations) resolves to the borrowed GPU, and that+ GPU's lock keeps a session from starting on it until the block exits. Load *and* use the model+ inside the block: a model loaded here lives in the borrowed GPU's cache.++ Yields the borrowed device, or None when nothing could be borrowed -- a CPU/MPS device, a+ legacy install, every GPU busy, or a refusal described below. The thread is then left exactly as+ it was, and the caller runs where it would have run anyway.++ With ``exclude`` (a session worker's own GPU) only other GPUs are candidates. Without it (a+ thread outside the session queue) any idle GPU of the thread's device type is, in+ ``generation_devices`` order -- except that such work never borrows on a single-GPU install and+ never holds every GPU at once (see :meth:`_GenerationDevicePool.try_borrow_off_queue`).++ ``purpose`` names the work for a debug log of where it ran (the session processor logs its own).++ On exit the thread's previous pins are restored -- or cleared, for a thread that had none. That+ matters for pooled threads (``asyncio.to_thread``): a pin left behind would silently steer+ unrelated later work on that thread to this GPU.+ """+ if exclude is not None:+ borrowed = GENERATION_DEVICE_POOL.try_borrow(exclude=exclude)+ else:+ borrowed = GENERATION_DEVICE_POOL.try_borrow_off_queue(TorchDevice.choose_torch_device().type)+ if purpose is not None:+ InvokeAILogger.get_logger(__name__).debug(+ f"{purpose} on idle device {borrowed}"+ if borrowed is not None+ else f"{purpose}: no idle device to borrow, running on {TorchDevice.choose_torch_device()}"+ )+ if borrowed is None:+ yield None+ return++ # Everything after the borrow succeeds is inside the try: if pinning raises, the borrow still has+ # to be released, or this GPU stays locked for the life of the process.+ try:+ previous_session_device = TorchDevice.get_session_device()+ previous_torch_device = _torch_current_device(borrowed.type)+ try:+ TorchDevice.set_session_device(borrowed)+ set_torch_current_device(borrowed)+ yield borrowed+ finally:+ if previous_session_device is None:+ TorchDevice.clear_session_device()+ else:+ TorchDevice.set_session_device(previous_session_device)+ if previous_torch_device is not None:+ set_torch_current_device(previous_torch_device)+ finally:+ GENERATION_DEVICE_POOL.release_borrow(borrowed)diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex f7a7f56518..53dba09219 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -2868,3 +2868,37 @@ def test_video_leaving_eligibility_clears_its_failure_bookkeeping(status = service.get_status()assert status is not Noneassert status.failed == 0+++def test_gpu_embedding_runs_on_an_idle_gpu(monkeypatch: pytest.MonkeyPatch) -> None:+ """Indexing runs outside the session queue, so a batch borrows the idle GPU instead of the busy one."""+ from unittest.mock import MagicMock++ from tests.fixtures.device_pool import GPU0, GPU1, two_gpu_pool++ seen: list[object] = []+ model = torch.nn.Linear(1, 1)+ loaded = MagicMock()+ loaded.model_on_device.return_value.__enter__.return_value = (None, model)++ def load_model(config: object) -> MagicMock:+ seen.append(TorchDevice.get_session_device())+ return loaded++ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ service._invoker = SimpleNamespace( # type: ignore[assignment]+ services=SimpleNamespace(+ configuration=SimpleNamespace(image_index_device=None),+ model_manager=SimpleNamespace(load=SimpleNamespace(load_model=load_model)),+ )+ )+ service._model_config = SimpleNamespace() # type: ignore[assignment]+ monkeypatch.setattr(+ service, "_embed", lambda model, images, device: seen.append(TorchDevice.get_session_device()) or np.zeros(1)+ )++ with two_gpu_pool(busy=(GPU0,)):+ service._encode_with_model([Image.new("RGB", (8, 8))])+ assert TorchDevice.get_session_device() is None++ assert seen == [GPU1, GPU1]diff --git a/tests/app/services/session_processor/test_encoder_offload.py b/tests/app/services/session_processor/test_encoder_offload.pyindex 05a01dd0ba..78c5ef0a7d 100644--- a/tests/app/services/session_processor/test_encoder_offload.py+++ b/tests/app/services/session_processor/test_encoder_offload.py@@ -26,8 +26,11 @@ def reset_state() -> Iterator[None]:# 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.app.services.session_processor.session_processor_default._set_torch_current_device"- with patch(target):+ 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:yieldfinally:@@ -90,7 +93,7 @@ def test_borrow_is_released_when_repinning_fails():GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])TorchDevice.set_session_device("cuda:0")- target = "invokeai.app.services.session_processor.session_processor_default._set_torch_current_device"+ 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")):diff --git a/tests/app/services/session_processor/test_lent_device_scheduling.py b/tests/app/services/session_processor/test_lent_device_scheduling.pynew file mode 100644index 0000000000..3762007965--- /dev/null+++ b/tests/app/services/session_processor/test_lent_device_scheduling.py@@ -0,0 +1,118 @@+"""A worker whose GPU is lent to a borrower leaves queue items for a free GPU.++A session claimed onto a lent GPU would only wait for the borrow to end -- up to a whole prompt+rewrite for work outside the queue -- while another GPU may be idle. These drive the real worker loop+(`_process`) against the real device pool, with the queue and runner faked.+"""++import threading+from collections.abc import Iterator+from threading import BoundedSemaphore, Event+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+import torch++from invokeai.app.services.session_processor.session_processor_default import (+ DefaultSessionProcessor,+ _SessionWorker,+)+from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+from invokeai.backend.util.devices import TorchDevice++GPU0 = torch.device("cuda:0")+GPU1 = torch.device("cuda:1")++[email protected](autouse=True)+def pool() -> Iterator[None]:+ GENERATION_DEVICE_POOL.reset()+ GENERATION_DEVICE_POOL.set_generation_devices([GPU0, GPU1])+ # The worker pins torch to its GPU before its first run; there is no real second GPU here.+ with patch("invokeai.app.services.session_processor.session_processor_default.torch.cuda.set_device"):+ try:+ yield+ finally:+ TorchDevice.clear_session_device()+ GENERATION_DEVICE_POOL.reset()+++def _start_worker(device: torch.device) -> tuple[threading.Thread, Event, list[str], DefaultSessionProcessor]:+ """Run one worker on ``device`` in a thread; it records each claim and stops after running one item."""+ stop_event = Event()+ resume_event = Event()+ resume_event.set()+ claims: list[str] = []+ item = SimpleNamespace(item_id=1, session_id="s", queue_id="default")++ class _Queue:+ def dequeue(self, device=None):+ claims.append(device)+ return item++ def get_queue_item(self, item_id: int):+ return SimpleNamespace(item_id=item_id, status="in_progress")++ runner = MagicMock()+ runner.workflow_call_queue_lifecycle.run_queue_item.side_effect = lambda queue_item: stop_event.set()+ processor = DefaultSessionProcessor()+ processor._invoker = SimpleNamespace( # type: ignore[attr-defined]+ services=SimpleNamespace(+ session_queue=_Queue(),+ logger=MagicMock(),+ image_moves=None,+ configuration=SimpleNamespace(multiuser=False),+ )+ )+ processor._polling_interval = 5 # long enough that only the release listener can wake it in time+ processor._thread_semaphore = BoundedSemaphore(1)+ processor._poll_now_event = Event()+ GENERATION_DEVICE_POOL.set_release_listener(processor._poll_now_event.set)+ thread = threading.Thread(+ target=processor._process,+ kwargs={+ "worker": _SessionWorker(device=device, runner=runner),+ "stop_event": stop_event,+ "poll_now_event": processor._poll_now_event,+ "resume_event": resume_event,+ },+ daemon=True,+ )+ thread.start()+ return thread, stop_event, claims, processor+++def test_worker_leaves_items_alone_while_its_gpu_is_lent_and_resumes_on_release() -> None:+ lent = GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda")+ assert lent == GPU0++ thread, stop_event, claims, processor = _start_worker(GPU0)+ try:+ thread.join(timeout=0.3)+ assert claims == [] # nothing claimed onto the lent GPU++ GENERATION_DEVICE_POOL.release_borrow(GPU0)+ # The release wakes the worker at once; its 5 s poll interval would fail this join.+ thread.join(timeout=2)+ assert not thread.is_alive()+ assert claims == ["cuda:0"]+ finally:+ stop_event.set()+ processor._poll_now_event.set()+ thread.join(timeout=2)+++def test_worker_on_a_free_gpu_claims_while_another_is_lent() -> None:+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda") == GPU0++ thread, stop_event, claims, processor = _start_worker(GPU1)+ try:+ thread.join(timeout=2)+ assert not thread.is_alive()+ assert claims == ["cuda:1"]+ finally:+ stop_event.set()+ processor._poll_now_event.set()+ thread.join(timeout=2)+ GENERATION_DEVICE_POOL.release_borrow(GPU0)diff --git a/tests/backend/text_llm/test_text_llm_api_models.py b/tests/backend/text_llm/test_text_llm_api_models.pyindex d617521770..17a10df025 100644--- a/tests/backend/text_llm/test_text_llm_api_models.py+++ b/tests/backend/text_llm/test_text_llm_api_models.py@@ -1,20 +1,27 @@"""Tests for TextLLM API request/response models and validation."""+from typing import Callablefrom unittest.mock import MagicMock, patchimport pytestimport torchfrom PIL import Imagefrom pydantic import ValidationError+from transformers import LlavaOnevisionForConditionalGeneration, LlavaOnevisionProcessorfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers.utilities import (ExpandPromptRequest,ExpandPromptResponse,ImageToPromptRequest,+ _model_load_lock,_run_expand_prompt,+ _run_image_to_prompt,)from invokeai.backend.model_manager.taxonomy import ModelType+from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+from invokeai.backend.util.devices import TorchDevice+from tests.fixtures.device_pool import GPU0, GPU1, two_gpu_poolclass TestExpandPromptRequest:@@ -125,3 +132,107 @@ def test_expand_prompt_with_an_image_runs_it_through_the_processor() -> None:load_tokenizer.assert_not_called()assert pipeline_class.call_args.args[1:] == (processor.tokenizer, processor)assert pipeline_class.return_value.run.call_args.kwargs["image"].mode == "RGB"+++def _services_recording_devices(model: object, seen: list[object]) -> MagicMock:+ """Model-manager services whose load and image read record the thread's session device."""+ loaded_model = MagicMock()+ loaded_model.model_on_device.return_value.__enter__.return_value = (None, model)+ services = MagicMock()++ def load_model(*args: object, **kwargs: object) -> MagicMock:+ seen.append(("load", TorchDevice.get_session_device()))+ return loaded_model++ def read_image(name: str) -> Image.Image:+ seen.append(("image read", TorchDevice.get_session_device()))+ return Image.new("RGB", (8, 8))++ services.model_manager.load.load_model.side_effect = load_model+ services.images.get_pil_image.side_effect = read_image+ return services+++def _recording(seen: list[object], label: str, result: object) -> Callable[..., object]:+ def record(*args: object, **kwargs: object) -> object:+ seen.append((label, TorchDevice.get_session_device()))+ return result++ return record+++def _borrow_recording_load_lock(seen: list[object]) -> Callable[[str], object]:+ """The real off-queue borrow, noting whether the model-load lock was already held."""+ real = GENERATION_DEVICE_POOL.try_borrow_off_queue++ def borrow(device_type: str) -> object:+ seen.append(("borrow under load lock", _model_load_lock.locked()))+ return real(device_type)++ return borrow+++def test_expand_prompt_loads_and_runs_on_the_idle_gpu() -> None:+ """With a render holding GPU 0, the LLM loads into and runs on GPU 1, and the thread is unpinned after.++ The tokenizer read comes before the borrow and the borrow after the load lock, so neither disk I/O+ nor a wait for another request's load holds a GPU a session could use.+ """+ model = MagicMock()+ model.parameters.side_effect = lambda: iter([torch.nn.Parameter(torch.zeros(1))])+ seen: list[object] = []+ services = _services_recording_devices(model, seen)+ services.model_manager.store.get_model.return_value = MagicMock(type=ModelType.TextLLM, path="model")++ with (+ two_gpu_pool(busy=(GPU0,)),+ patch.object(ApiDependencies, "invoker", MagicMock(services=services), create=True),+ patch("invokeai.app.api.routers.utilities._resolve_model_path", return_value="model"),+ patch(+ "invokeai.app.api.routers.utilities.AutoTokenizer.from_pretrained",+ side_effect=_recording(seen, "tokenizer read", MagicMock()),+ ),+ patch.object(GENERATION_DEVICE_POOL, "try_borrow_off_queue", side_effect=_borrow_recording_load_lock(seen)),+ patch("invokeai.app.api.routers.utilities.TextLLMPipeline") as pipeline_class,+ ):+ pipeline_class.return_value.run.side_effect = _recording(seen, "run", "expanded")+ _run_expand_prompt("cat", "model", 10, None, 1, None, "user")+ assert TorchDevice.get_session_device() is None++ assert seen == [+ ("tokenizer read", None),+ ("borrow under load lock", True),+ ("load", GPU1),+ ("run", GPU1),+ ]+++def test_image_to_prompt_loads_and_runs_on_the_idle_gpu() -> None:+ model = MagicMock(spec=LlavaOnevisionForConditionalGeneration)+ model.parameters.side_effect = lambda: iter([torch.nn.Parameter(torch.zeros(1))])+ seen: list[object] = []+ services = _services_recording_devices(model, seen)+ services.model_manager.store.get_model.return_value = MagicMock(type=ModelType.LlavaOnevision, path="model")++ with (+ two_gpu_pool(busy=(GPU0,)),+ patch.object(ApiDependencies, "invoker", MagicMock(services=services), create=True),+ patch("invokeai.app.api.routers.utilities._resolve_model_path", return_value="model"),+ patch(+ "invokeai.app.api.routers.utilities.AutoProcessor.from_pretrained",+ side_effect=_recording(seen, "processor read", MagicMock(spec=LlavaOnevisionProcessor)),+ ),+ patch.object(GENERATION_DEVICE_POOL, "try_borrow_off_queue", side_effect=_borrow_recording_load_lock(seen)),+ patch("invokeai.app.api.routers.utilities.LlavaOnevisionPipeline") as pipeline_class,+ ):+ pipeline_class.return_value.run.side_effect = _recording(seen, "run", "a photo")+ _run_image_to_prompt("frame.png", "llava", "describe", None, "user")+ assert TorchDevice.get_session_device() is None++ assert seen == [+ ("image read", None),+ ("processor read", None),+ ("borrow under load lock", True),+ ("load", GPU1),+ ("run", GPU1),+ ]diff --git a/tests/backend/util/test_device_pool.py b/tests/backend/util/test_device_pool.pyindex 85f6c0de4b..a04a779c23 100644--- a/tests/backend/util/test_device_pool.py+++ b/tests/backend/util/test_device_pool.py@@ -1,13 +1,16 @@-"""Tests for the idle generation-device arbiter used by text-encoder offload."""+"""Tests for the idle generation-device arbiter used by text-encoder offload and off-queue model work."""import threadingimport timefrom collections.abc import Iterator+from unittest.mock import patchimport pytestimport torch-from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL, idle_device_borrowed+from invokeai.backend.util.devices import TorchDevice+from tests.fixtures.device_pool import two_gpu_pool@pytest.fixture(autouse=True)@@ -249,3 +252,119 @@ class TestAnyOtherDeviceBusy:GENERATION_DEVICE_POOL.reset()assert not GENERATION_DEVICE_POOL.any_other_device_busy(None)assert not GENERATION_DEVICE_POOL.any_other_device_busy(torch.device("cuda:0"))+++# --- Borrowing from outside the session queue -------------------------------------------------+++def off_queue_thread() -> Iterator[list[torch.device]]:+ with two_gpu_pool() as torch_pins:+ yield torch_pins+++def test_off_queue_borrow_takes_the_first_idle_gpu_in_registration_order() -> None:+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:1"), torch.device("cuda:0")])+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0")) # a render; it still serves the queue+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda") == torch.device("cuda:1")+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("mps") is None+++def test_off_queue_borrow_never_takes_the_last_gpu_left_for_the_queue() -> None:+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda") == torch.device("cuda:0")+ # cuda:1 is idle, but lending it too would leave the queue nowhere to start a session.+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda") is None+ # A running session's encoder offload is not off-queue work, and may still borrow it.+ assert GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0")) == torch.device("cuda:1")+++def test_off_queue_borrow_is_refused_on_a_single_gpu() -> None:+ """With one GPU, a borrow would only make the next session wait for the off-queue work."""+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0")])+ assert GENERATION_DEVICE_POOL.try_borrow_off_queue("cuda") is None+++def test_off_queue_borrow_follows_the_thread_device_type() -> None:+ GENERATION_DEVICE_POOL.set_generation_devices(+ [torch.device("cuda:0"), torch.device("xpu:0"), torch.device("xpu:1")]+ )+ with (+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("xpu")),+ patch("invokeai.backend.util.device_pool.set_torch_current_device"),+ patch("invokeai.backend.util.device_pool._torch_current_device", return_value=None),+ ):+ try:+ with idle_device_borrowed() as device:+ assert device == torch.device("xpu:0")+ finally:+ TorchDevice.clear_session_device()+++def test_lent_state_and_release_listener() -> None:+ GENERATION_DEVICE_POOL.set_generation_devices([torch.device("cuda:0"), torch.device("cuda:1")])+ released: list[bool] = []+ GENERATION_DEVICE_POOL.set_release_listener(lambda: released.append(True))++ borrowed = GENERATION_DEVICE_POOL.try_borrow(exclude=torch.device("cuda:0"))+ assert borrowed is not None and GENERATION_DEVICE_POOL.is_lent(borrowed)+ assert not GENERATION_DEVICE_POOL.is_lent(torch.device("cuda:0"))+ GENERATION_DEVICE_POOL.release_borrow(borrowed)+ assert not GENERATION_DEVICE_POOL.is_lent(borrowed)+ assert released == [True]+++def test_off_queue_work_moves_to_the_idle_gpu_and_unpins_after(off_queue_thread: list[torch.device]) -> None:+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0")) # a render is running on GPU 0++ with idle_device_borrowed() as device:+ assert device == torch.device("cuda:1")+ assert TorchDevice.choose_torch_device() == torch.device("cuda:1")+ assert GENERATION_DEVICE_POOL.is_lent(torch.device("cuda:1"))++ # A pooled thread must come back unpinned, or later unrelated work would follow the pin.+ assert TorchDevice.get_session_device() is None+ assert off_queue_thread == [torch.device("cuda:1"), torch.device("cuda:0")]+ assert not GENERATION_DEVICE_POOL.is_lent(torch.device("cuda:1"))+++def test_off_queue_work_stays_put_when_every_gpu_is_busy(off_queue_thread: list[torch.device]) -> None:+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0"))+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:1"))++ with idle_device_borrowed() as device:+ assert device is None+ assert TorchDevice.get_session_device() is None++ assert off_queue_thread == []+++def test_off_queue_borrow_is_released_and_unpinned_when_the_work_raises(+ off_queue_thread: list[torch.device],+) -> None:+ with pytest.raises(RuntimeError, match="out of memory"):+ with idle_device_borrowed():+ raise RuntimeError("out of memory")++ assert TorchDevice.get_session_device() is None+ assert not GENERATION_DEVICE_POOL.is_lent(torch.device("cuda:0"))+++def test_off_queue_borrow_is_a_no_op_without_a_registered_pool() -> None:+ """Legacy installs (no generation devices) register nothing, so nothing changes for them."""+ with idle_device_borrowed() as device:+ assert device is None+ assert TorchDevice.get_session_device() is None+++def test_off_queue_borrow_is_held_until_the_pins_are_restored(off_queue_thread: list[torch.device]) -> None:+ """Releasing first would let a session start on the GPU while this thread still points at it."""+ GENERATION_DEVICE_POOL.acquire_session(torch.device("cuda:0"))+ lent_at_each_pin: list[bool] = []+ with patch(+ "invokeai.backend.util.device_pool.set_torch_current_device",+ side_effect=lambda device: lent_at_each_pin.append(GENERATION_DEVICE_POOL.is_lent(torch.device("cuda:1"))),+ ):+ with idle_device_borrowed():+ pass+ assert lent_at_each_pin == [True, True] # the pin, then the restorediff --git a/tests/fixtures/device_pool.py b/tests/fixtures/device_pool.pynew file mode 100644index 0000000000..a53d4907bc--- /dev/null+++ b/tests/fixtures/device_pool.py@@ -0,0 +1,48 @@+"""A faked two-GPU generation pool, for testing work that borrows an idle GPU on any hardware.++The pool's locks and the thread's session pin are real. Torch's own current-device calls are recorded+instead of made, an unpinned thread's default device is reported as CUDA (a CPU-only runner would+otherwise have nothing to borrow), and the dtype choice skips its device-name lookup -- the faked+``cuda:1`` does not exist on a one-GPU host, and no test here should touch a real GPU.+"""++from collections.abc import Iterator+from contextlib import contextmanager+from unittest.mock import patch++import torch++from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL+from invokeai.backend.util.devices import TorchDevice++GPU0 = torch.device("cuda:0")+GPU1 = torch.device("cuda:1")+++@contextmanager+def two_gpu_pool(busy: tuple[torch.device, ...] = ()) -> Iterator[list[torch.device]]:+ """Register GPU0 and GPU1, mark ``busy`` as running a session, and yield torch's recorded current-device pins.++ Resets the pool and clears the calling thread's session pin on exit.+ """+ GENERATION_DEVICE_POOL.reset()+ GENERATION_DEVICE_POOL.set_generation_devices([GPU0, GPU1])+ for device in busy:+ GENERATION_DEVICE_POOL.acquire_session(device)+ torch_pins: list[torch.device] = []+ with (+ patch("invokeai.backend.util.device_pool.set_torch_current_device", side_effect=torch_pins.append),+ patch("invokeai.backend.util.device_pool._torch_current_device", return_value=GPU0),+ # Only the unpinned case is faked: a pinned thread still resolves to its pin.+ patch.object(+ TorchDevice,+ "choose_torch_device",+ side_effect=lambda: TorchDevice.get_session_device() or torch.device("cuda"),+ ),+ patch.object(TorchDevice, "choose_torch_dtype", return_value=torch.bfloat16),+ ):+ try:+ yield torch_pins+ finally:+ TorchDevice.clear_session_device()+ GENERATION_DEVICE_POOL.reset()