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
import copy
import gc
import time
import traceback
from contextlib import contextmanager, nullcontext, suppress
from threading import BoundedSemaphore, Thread
from threading import Event as ThreadEvent
from typing import Callable, Iterator, Literal, Optional
import torch
from starlette.concurrency import run_in_threadpool
from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, services_for_queue_user
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.events.events_common import (
BatchEnqueuedEvent,
FastAPIEvent,
QueueClearedEvent,
QueueItemStatusChangedEvent,
UserAccessChangedEvent,
register_events,
)
from invokeai.app.services.invocation_stats.invocation_stats_common import GESStatsNotFoundError
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.session_processor.architecture_switch import ArchitectureSwitchOffload
from invokeai.app.services.session_processor.session_processor_base import (
InvocationServices,
OnAfterRunNode,
OnAfterRunSession,
OnBeforeRunNode,
OnBeforeRunSession,
OnNodeError,
OnNonFatalProcessorError,
SessionProcessorBase,
SessionRunnerBase,
)
from invokeai.app.services.session_processor.session_processor_common import CanceledException, SessionProcessorStatus
from invokeai.app.services.session_processor.workflow_call_runtime import (
WorkflowCallCoordinator,
WorkflowCallQueueLifecycle,
)
from invokeai.app.services.session_queue.session_queue_common import (
SessionQueueItem,
SessionQueueItemChangedError,
SessionQueueItemNotFoundError,
)
from invokeai.app.services.shared.graph import CollectInvocation, IterateInvocation, NodeInputError
from invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import calibration_run_id
from invokeai.app.util.profiler import Profiler
from invokeai.app.util.startup_utils import log_attention_backends
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
from invokeai.backend.util.attention import attention_caller
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
from invokeai.backend.util.wddm import paged_bytes
from invokeai.backend.working_memory import probe
# Paged-out VRAM worth a warning. Weight uploads page a few hundred MB for an instant (0.25-0.36 GiB measured on an
# RX 9060 XT), so the threshold sits above that; a session that ends with more than this paged has lost real VRAM.
_VRAM_PAGING_WARNING_BYTES = 512 * 2**20
# A failed owner lookup is retried before the item is refused, so that a transient error
# — a busy-timeout on the shared SQLite connection under multi-GPU write contention, say —
# does not cost the user their queued work. Both call sites run on a worker thread, so the
# wait between attempts blocks nothing else.
OWNER_LOOKUP_ATTEMPTS = 3
OWNER_LOOKUP_RETRY_SECONDS = 0.25
# How long `DefaultSessionProcessor.stop` waits, in all, for its workers to leave their sessions. A node that checks for
# cancellation stops within one step; the bound also covers most nodes without such a check (a large VAE decode), and
# keeps a node that never returns from holding up shutdown for good.
WORKER_STOP_TIMEOUT_SECONDS = 30.0
# After this long, `stop` says which worker it is waiting for: the wait runs on the event-loop thread at shutdown.
WORKER_STOP_NOTICE_SECONDS = 1.0
# Workers a stop gave up on. Process-wide, like the device pool whose locks they may still hold: no processor of this
# process starts, and none replaces the pool, while one of them runs.
_abandoned_workers: list[Thread] = []
def refuse_while_an_abandoned_worker_runs() -> None:
"""Raise RuntimeError while a worker an earlier `DefaultSessionProcessor.stop` gave up on still runs."""
_abandoned_workers[:] = [thread for thread in _abandoned_workers if thread.is_alive()]
if _abandoned_workers:
raise RuntimeError(
f"Session worker {', '.join(thread.name for thread in _abandoned_workers)} of the previous session "
"processor is still running a node; it would share its GPU with the new workers. Restart the process."
)
def queue_owner_is_active(
services: InvocationServices, queue_item: SessionQueueItem, *, unreadable_is_active: bool = False
) -> bool:
"""Whether the queue item's owner is still permitted to execute work.
Deactivating (or deleting) an account must also revoke its queued execution:
a queued graph consumes GPU time, reads media, and writes outputs on behalf of
its owner. Pending items are rejected at dequeue; running items are checked before
every node, so they stop at the next node boundary — and once more after the graph's
last node, so a one-node graph is not recorded as completed for an owner revoked while
it ran (and immediately mid-node for nodes with step callbacks, via the cancel event
set when the item is canceled).
The check is skipped entirely when multiuser mode is disabled.
The ``system`` user — which owns everything migrated from before multiuser support
(see migration_27) — is deliberately NOT special-cased. It has a real, active
database row, so it passes on its own merits. Exempting it here would only change
behaviour when the row is missing or inactive, and that is precisely the case where
this gate would then disagree with the save gates in `invocation_context`, which
have no such exemption: the item would burn GPU time and then fail at the first
`context.images.save()`. Better to reject it at dequeue.
A lookup that keeps failing is treated as *not* authorized, after
``OWNER_LOOKUP_ATTEMPTS`` tries. Returning "active" on an unreadable database would
make unknown state executable: the account may well have been deactivated a moment
ago, and this gate is what stands between that and GPU time spent on its behalf.
Failing closed costs a still-valid user a cancellation instead — recoverable, since
canceled items can be retried, and only reachable when the database has been
unreadable across every attempt, by which point the instance has larger problems.
``unreadable_is_active`` inverts only that last decision, for the one caller that runs
*after* the work rather than before it. Ahead of a node, failing closed spends nothing
and may save a GPU; after the graph's last node there is no execution left to refuse,
so the same failure would cancel a completed generation — destroying a valid user's
result over a transient busy-timeout, and, for a workflow-call child, taking the whole
parent chain with it. A genuinely revoked owner loses nothing by the difference: the
save gates in ``invocation_context`` re-read the record independently and have already
refused every write.
The exception is swallowed rather than raised for the same reason as before: this runs
between nodes on a path with no exception handling of its own, and letting it escape
would abandon the session without its normal teardown.
"""
if not services.configuration.multiuser:
return True
for attempt in range(OWNER_LOOKUP_ATTEMPTS):
try:
user = services.users.get(queue_item.user_id)
except Exception:
services.logger.warning(
f"Could not verify owner {queue_item.user_id} of queue item {queue_item.item_id} "
f"(attempt {attempt + 1}/{OWNER_LOOKUP_ATTEMPTS})",
exc_info=True,
)
if attempt + 1 < OWNER_LOOKUP_ATTEMPTS:
time.sleep(OWNER_LOOKUP_RETRY_SECONDS)
continue
return user is not None and user.is_active
if unreadable_is_active:
services.logger.warning(
f"Could not verify owner {queue_item.user_id} of queue item {queue_item.item_id} after it finished; "
"letting the completed work stand"
)
return True
services.logger.error(
f"Could not verify owner {queue_item.user_id} of queue item {queue_item.item_id}; refusing execution"
)
return False
class DefaultSessionRunner(SessionRunnerBase):
"""Processes a single session's invocations."""
def __init__(
self,
on_before_run_session_callbacks: Optional[list[OnBeforeRunSession]] = None,
on_before_run_node_callbacks: Optional[list[OnBeforeRunNode]] = None,
on_after_run_node_callbacks: Optional[list[OnAfterRunNode]] = None,
on_node_error_callbacks: Optional[list[OnNodeError]] = None,
on_after_run_session_callbacks: Optional[list[OnAfterRunSession]] = None,
):
"""
Args:
on_before_run_session_callbacks: Callbacks to run before the session starts.
on_before_run_node_callbacks: Callbacks to run before each node starts.
on_after_run_node_callbacks: Callbacks to run after each node completes.
on_node_error_callbacks: Callbacks to run when a node errors.
on_after_run_session_callbacks: Callbacks to run after the session completes.
"""
self._on_before_run_session_callbacks = on_before_run_session_callbacks or []
self._on_before_run_node_callbacks = on_before_run_node_callbacks or []
self._on_after_run_node_callbacks = on_after_run_node_callbacks or []
self._on_node_error_callbacks = on_node_error_callbacks or []
self._on_after_run_session_callbacks = on_after_run_session_callbacks or []
self.workflow_call_coordinator = WorkflowCallCoordinator(self)
self.workflow_call_queue_lifecycle = WorkflowCallQueueLifecycle(self)
# Per runner, hence per worker and device: each worker remembers the architecture it last ran.
self._architecture_switch = ArchitectureSwitchOffload()
# The calibration run of the item this runner is executing, None for every other item.
self._calibration_run_id: Optional[str] = None
# What the outcome hooks last reported: `run_node` swallows a node's failure or cancellation, and a calibration
# node must not keep valid measurements then.
self._node_outcome: Optional[Literal["completed", "failed"]] = None
# The item as the queue left it in the last `_on_after_run_session`, taken before its statistics and callbacks
# run (None when the queue no longer had it): a calibration item's outcome, also when one of those raised.
self._settled_item: Optional[SessionQueueItem] = None
def start(self, services: InvocationServices, cancel_event: ThreadEvent, profiler: Optional[Profiler] = None):
self._services = services
self._cancel_event = cancel_event
self._profiler = profiler
def _is_canceled(self) -> bool:
"""Check if the cancel event is set. This is also passed to the invocation context builder and called during
denoising to check if the session has been canceled."""
return self._cancel_event.is_set()
def _run_session_loop(self, queue_item: SessionQueueItem) -> None:
# Loop over invocations until the session is complete or canceled
while True:
try:
invocation = queue_item.session.next()
# Anything other than a `NodeInputError` is handled as a processor error
except NodeInputError as e:
error_type = e.__class__.__name__
error_message = str(e)
error_traceback = traceback.format_exc()
self._on_node_error(
invocation=e.node,
queue_item=queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
break
if invocation is None or self._is_canceled():
break
# Revalidate the owner before the node: an account deactivated mid-session
# must not execute further nodes.
if self._cancel_if_owner_revoked(queue_item):
break
if self._calibration_run_id is None:
self.run_node(invocation, queue_item)
elif not self._run_calibration_node(invocation, queue_item, self._calibration_run_id):
break
# The session is complete if all invocations have been run or there is an error on the session.
# At this time, the queue item may be canceled, but the object itself here won't be updated yet. We must
# use the cancel event to check if the session is canceled.
session_finished = queue_item.session.is_complete()
already_terminal = self._is_canceled() or queue_item.status in ["failed", "canceled", "completed"]
if session_finished:
# Re-check ownership after the final node. The next pass still lets the scheduler
# materialize any downstream node that became ready while finalizing a loop.
#
# Deliberately narrow, because after a node the balance is the reverse of
# what it is before one: there is no execution left to refuse, only a
# finished result to destroy. So it runs only when the session finished its
# own work — `has_error()` sessions are `is_complete()` too, and cancelling
# one would overwrite its error and drag a workflow call's waiting parent
# down with it — and it does not fail closed (see `queue_owner_is_active`).
# A suspended workflow call is not `is_complete()`, so it is untouched here
# and re-checked when the parent resumes.
if session_finished and not already_terminal and not queue_item.session.has_error():
if self._cancel_if_owner_revoked(queue_item, unreadable_is_active=True):
break
if not already_terminal:
continue
if already_terminal:
break
def _cancel_if_owner_revoked(self, queue_item: SessionQueueItem, *, unreadable_is_active: bool = False) -> bool:
"""Cancel the item if its owner may no longer execute work. Returns True if canceled."""
if queue_owner_is_active(self._services, queue_item, unreadable_is_active=unreadable_is_active):
return False
self._services.logger.warning(
f"Canceling queue item {queue_item.item_id}: owner {queue_item.user_id} is deactivated, "
"deleted, or could not be verified"
)
# A copy for the queue to update: the session loop's own item keeps the status it had.
canceling = copy.copy(queue_item)
with suppress(SessionQueueItemNotFoundError):
self._settle(
queue_item.item_id,
lambda: self._services.session_queue.cancel_queue_item(queue_item.item_id, queue_item=canceling),
queue_item=canceling,
)
return True
def _settle(
self,
item_id: int,
transition: Callable[[], SessionQueueItem],
*,
queue_item: Optional[SessionQueueItem] = None,
) -> SessionQueueItem:
"""Run a terminal queue transition of the item and keep the item it returned in `_settled_item`: a calibration
item's outcome, should the queue prune or clear the item before the runner records it. The queue announces a
transition after committing it and updating a supplied `queue_item`. Keep that snapshot if the announcement
raises and the transition moved it to a final status, even if the row was pruned meanwhile; otherwise read the
row back while it still exists."""
status_before = None if queue_item is None else queue_item.status
try:
settled = transition()
except Exception as error:
if (
queue_item is not None
and queue_item.status != status_before
and queue_item.status in ("completed", "failed", "canceled")
):
self._settled_item = queue_item
elif not isinstance(error, SessionQueueItemNotFoundError):
with suppress(Exception):
current = self._services.session_queue.get_queue_item(item_id)
if current.status in ("completed", "failed", "canceled"):
self._settled_item = current
raise
self._settled_item = settled
return settled
def run(self, queue_item: SessionQueueItem):
# Exceptions raised outside `run_node` are handled by the processor. There is no need to catch them here.
self._refresh_user_fits()
# getattr, like the workflow-call lifecycle's reads: runners also execute stand-in items without an origin.
run_id = calibration_run_id(getattr(queue_item, "origin", None))
if run_id is not None:
self._run_calibration_item(queue_item, run_id)
return
self._on_before_run_session(queue_item=queue_item)
self._run_session_loop(queue_item)
self._on_after_run_session(queue_item=queue_item)
def _refresh_user_fits(self) -> None:
"""Let this item's estimates read the calibration store as it is now: once per item, never per estimate."""
# getattr: stand-in service containers that runners execute with need not carry the calibration service.
service = getattr(self._services, "working_memory_calibration", None)
if service is None:
return
try:
service.refresh_user_fits()
except Exception:
# The fits read so far stay in force; a store that cannot be read must not fail a generation.
self._services.logger.warning("Could not refresh the working-memory user fits", exc_info=True)
def _run_calibration_item(self, queue_item: SessionQueueItem, run_id: str) -> None:
"""Run a working-memory calibration item, measuring each node (see `working_memory.probe`).
The item is admitted again here, whatever admitted it to the queue -- a retry and a workflow-call child carry
the origin and owner of the item they came from: its owner must still be an administrator, the machine must
still calibrate on one GPU, and its run must still exist. Otherwise it fails before any node runs.
"""
service = self._services.working_memory_calibration
raised: Optional[BaseException] = None
# The item as the queue left it after the session (`_settled_item`): once the item is gone, only the runner can
# tell a prune of a finished item (completed, failed or canceled) from a clear that removed it before it
# finished.
self._settled_item = None
try:
try:
refusal = (
"Working-memory calibration is not available in this process."
if service is None
else service.admit(queue_item, run_id)
)
except Exception as error:
self._services.logger.warning(f"Could not admit calibration item {queue_item.item_id}", exc_info=True)
refusal = f"Could not admit the calibration item: {error}"
if refusal is not None:
self._services.logger.warning(f"Failing calibration item {queue_item.item_id}: {refusal}")
failing = copy.copy(queue_item)
with suppress(SessionQueueItemNotFoundError):
self._settle(
queue_item.item_id,
lambda: self._services.session_queue.fail_queue_item(
queue_item.item_id, "WorkingMemoryCalibrationError", refusal, refusal, queue_item=failing
),
queue_item=failing,
)
return
self._calibration_run_id = run_id
try:
self._on_before_run_session(queue_item=queue_item)
self._run_session_loop(queue_item)
self._on_after_run_session(queue_item=queue_item)
finally:
self._calibration_run_id = None
except BaseException as error:
raised = error
raise
finally:
# Also when the session raised: `admit` recorded the item as running, and only this replaces that.
if service is not None:
try:
service.observe(queue_item, run_id, raised, self._settled_item)
except Exception:
self._services.logger.warning(
f"Could not record the outcome of calibration item {queue_item.item_id}", exc_info=True
)
# `raised` and the exception's traceback (through this frame) would otherwise reference each other, so the
# failed node's frames and tensors would wait for the cyclic GC instead of being freed when the worker
# drops the exception, before its VRAM release.
raised = None
def _run_calibration_node(self, invocation: BaseInvocation, queue_item: SessionQueueItem, run_id: str) -> bool:
"""Run one node of a calibration item inside a probe scope and persist its windows, whether the node completed,
failed or was canceled; unless it completed, they are persisted invalid. Returns False when they could not be
persisted: the item has failed then."""
service = self._services.working_memory_calibration
try:
assert service is not None
# Read before the node runs: a model reset while it runs removes points these windows must not bring back.
model_reset_epochs = service.model_reset_epochs(run_id)
except Exception as error:
return self._fail_calibration_node(invocation, queue_item, error)
with probe.calibration_scope(
run_id=run_id,
queue_item_id=queue_item.item_id,
# The source id: what the client that built the graph knows the node by.
node_id=queue_item.session.prepared_source_mapping.get(invocation.id, invocation.id),
node_type=invocation.get_type(),
) as scope:
self._node_outcome = None
self.run_node(invocation, queue_item)
if self._node_outcome != "completed":
# A node that neither completed nor failed was canceled: `run_node` passes over a CanceledException.
scope.invalidate("exception" if self._node_outcome == "failed" else "canceled")
if not scope.windows:
return True
try:
service.record_windows(run_id, scope.windows, model_reset_epochs)
except Exception as error:
return self._fail_calibration_node(invocation, queue_item, error)
return True
def _fail_calibration_node(
self, invocation: BaseInvocation, queue_item: SessionQueueItem, error: Exception
) -> bool:
"""Fail the item whose node's measurements cannot be saved. Call from the `except` block (for the traceback)."""
message = f"Could not save the working-memory measurements of node {invocation.id}: {error}"
self._services.logger.error(message, exc_info=True)
details = traceback.format_exc()
# A copy for the queue to update, as in `_cancel_if_owner_revoked`.
failing = copy.copy(queue_item)
with suppress(SessionQueueItemNotFoundError):
self._settle(
queue_item.item_id,
lambda: self._services.session_queue.fail_queue_item(
queue_item.item_id, "WorkingMemoryCalibrationError", message, details, queue_item=failing
),
queue_item=failing,
)
return False
def run_node(self, invocation: BaseInvocation, queue_item: SessionQueueItem):
try:
# Any unhandled exception in this scope is an invocation error & will fail the graph
with self._services.performance_statistics.collect_stats(invocation, queue_item.session_id):
self._on_before_run_node(invocation, queue_item)
execution_ref = queue_item.session.get_execution_ref(invocation.id)
child_capability = None
workflow_inputs = None
workflow_authorizer = None
authorized_workflow_record = None
if isinstance(invocation, CallSavedWorkflowInvocation):
child_capability = queue_item.session.build_child_execution_capability(
execution_ref,
authorization_context={"user_id": queue_item.user_id},
)
workflow_inputs = self.workflow_call_coordinator._collect_call_saved_workflow_inputs(
invocation, queue_item
)
if isinstance(invocation, CallSavedWorkflowInvocation):
def workflow_authorizer(_workflow_id: str):
nonlocal authorized_workflow_record
authorized_workflow_record = invocation.validate_selected_workflow(context)
return authorized_workflow_record
data = InvocationContextData(
invocation=invocation,
source_invocation_id=queue_item.session.prepared_source_mapping[invocation.id],
queue_item=queue_item,
execution_frame=execution_ref.frame.iteration_path,
execution_state_id=execution_ref.state_id,
execution_frame_id=execution_ref.frame.frame_id,
execution_workflow_call_depth=execution_ref.frame.workflow_call_depth,
execution_child_capability=child_capability,
execution_workflow_authorizer=workflow_authorizer,
execution_workflow_inputs=workflow_inputs,
)
# The context hands nodes these services too, so it must carry the same user-scoped cache.
node_services = services_for_queue_user(self._services, queue_item.user_id)
context = build_invocation_context(
data=data,
services=node_services,
is_canceled=self._is_canceled,
)
# Retain the queue boundary for compatibility contexts that cannot record lifecycle effects.
if isinstance(invocation, CallSavedWorkflowInvocation) and not getattr(
context.execution_effects, "allow_lifecycle_effects", False
):
workflow_record = invocation.validate_selected_workflow(context)
self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)
return
# Invoke the node, optionally on a borrowed idle GPU (text encoders only). Its attention calls are
# attributed to its type, which the pinned-kernel report (`attention_backend`) names.
# Leaving `invocation_resources` releases what the context held for the run, however it ended.
with (
self._maybe_offload_to_idle_gpu(invocation),
attention_caller(invocation.get_type()),
data.invocation_resources,
):
run_result = invocation.invoke_internal_with_effects(context=context, services=node_services)
output = run_result.output
control_collection = None
if self._on_after_run_node_callbacks and isinstance(invocation, (IterateInvocation, CollectInvocation)):
control_collection = invocation.collection
# Save output and history
execution_ref = queue_item.session.get_execution_ref(
invocation.id, effect_count=len(run_result.effects)
)
finalized_outputs = queue_item.session.apply(execution_ref, run_result)
if isinstance(invocation, CallSavedWorkflowInvocation):
failure_effect = next(
(effect for effect in run_result.effects if getattr(effect, "kind", None) == "fail"),
None,
)
if failure_effect is not None:
error_message = str(getattr(failure_effect, "message", ""))
error_type = getattr(failure_effect, "error_type", None) or "ValueError"
error_traceback = getattr(failure_effect, "error_traceback", None) or error_message
self._on_node_error(
invocation=invocation,
queue_item=queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
return
if authorized_workflow_record is None:
raise RuntimeError("Saved workflow execution completed without authorization.")
workflow_record = authorized_workflow_record
self._dispatch_workflow_call_effects(
invocation=invocation,
queue_item=queue_item,
workflow_record=workflow_record,
effects=run_result.effects,
)
return
if control_collection is not None:
invocation.collection = control_collection
try:
self._on_after_run_node(invocation, queue_item, output)
for finalized_invocation, finalized_output in finalized_outputs:
# For output collections are finalized when their matching ForReturn completes. Emit a
# follow-up event so listeners receive the materialized final collection, not the placeholder
# produced when the For iteration started.
self._services.events.emit_invocation_complete(
invocation=finalized_invocation,
queue_item=queue_item,
output=finalized_output,
)
finally:
if control_collection is not None:
invocation.collection = []
except SessionQueueItemChangedError:
# A concurrent cancellation or terminal transition won the parent CAS. The in-memory session
# belongs to the losing worker and must not be persisted or emitted as a new invocation error.
try:
current_queue_item = self._services.session_queue.get_queue_item(queue_item.item_id)
except SessionQueueItemNotFoundError:
return
self._services.logger.info(
"Discarding stale workflow-call transition for queue item %s; current status is %s",
queue_item.item_id,
current_queue_item.status,
)
return
except CanceledException:
# A CanceledException is raised during the denoising step callback if the cancel event is set. We don't need
# to do any handling here, and no error should be set - just pass and the cancellation will be handled
# correctly in the next iteration of the session runner loop.
#
# See the comment in the processor's `_on_queue_item_status_changed()` method for more details on how we
# handle cancellation.
pass
except Exception as e:
error_type = e.__class__.__name__
error_message = str(e)
error_traceback = traceback.format_exc()
self._on_node_error(
invocation=invocation,
queue_item=queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
def _dispatch_workflow_call_effects(
self,
*,
invocation: CallSavedWorkflowInvocation,
queue_item: SessionQueueItem,
workflow_record,
effects,
) -> None:
"""Pass lifecycle intent through queue adapter, retaining old boundary fallback."""
hook = getattr(self.workflow_call_queue_lifecycle, "apply_execution_effects", None)
if hook is None:
hook = getattr(self.workflow_call_coordinator, "apply_execution_effects", None)
if hook is not None:
hook(
invocation=invocation,
queue_item=queue_item,
workflow_record=workflow_record,
effects=effects,
)
return
self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)
@contextmanager
def _maybe_offload_to_idle_gpu(self, invocation: BaseInvocation) -> Iterator[None]:
"""Temporarily re-pin this worker thread to an idle GPU for a text-encoder node.
When ``offload_text_encoders_to_idle_gpus`` is enabled and an idle generation GPU can be
borrowed, the encoder model loads into that GPU's cache and its forward runs there (all
device-selecting code resolves to the pinned device), keeping the busy GPU's denoise model
resident. The conditioning output is stored on the CPU, so the denoiser picks it up on the
worker's own GPU after the pin is restored.
The borrow holds the idle device's exclusive-use lock for the whole node, so a native
session on that GPU can never run concurrently against the same cached encoder (which would
corrupt it). If no idle GPU is free, the node runs on the worker's own GPU unchanged.
"""
native_device = TorchDevice.get_session_device()
if (
native_device is None
or native_device.type not in ("cuda", "xpu")
or not invocation.idle_gpu_offloadable
or not self._services.configuration.offload_text_encoders_to_idle_gpus
):
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.
borrowed_cache = load.ram_cache if load is not None else None
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 None
try:
if swap_stats:
borrowed_cache.stats = native_cache.stats
yield
finally:
if swap_stats:
borrowed_cache.stats = saved_borrowed_stats
def _on_before_run_session(self, queue_item: SessionQueueItem) -> None:
"""Called before a session is run.
- Start the profiler if profiling is enabled.
- Run any callbacks registered for this event.
"""
self._services.logger.debug(
f"On before run session: queue item {queue_item.item_id}, session {queue_item.session_id}"
)
# If profiling is enabled, start the profiler
if self._profiler is not None:
self._profiler.start(profile_id=queue_item.session_id)
self._offload_other_architectures(queue_item)
for callback in self._on_before_run_session_callbacks:
callback(queue_item=queue_item)
def _offload_other_architectures(self, queue_item: SessionQueueItem) -> None:
"""Clear this worker's VRAM of models the session does not name when it switches architecture.
Best effort: a failure costs at most the VRAM the offload would have freed, never the session.
"""
model_manager = getattr(self._services, "model_manager", None)
load = model_manager.load if model_manager is not None else None
if load is None or not self._services.configuration.offload_on_architecture_switch:
return
try:
self._architecture_switch.before_session(queue_item.session.graph, load.ram_cache)
except Exception:
self._services.logger.warning("Could not clear VRAM for an architecture switch", exc_info=True)
def _on_after_run_session(self, queue_item: SessionQueueItem) -> None:
"""Called after a session is run.
- Stop the profiler if profiling is enabled.
- Update the queue item's session object in the database.
- If not already canceled or failed, complete the queue item.
- Log and reset performance statistics.
- Run any callbacks registered for this event.
Keeps the item as the queue left it in `_settled_item` before the statistics and callbacks run. When the queue
no longer has it, `_settled_item` keeps what an earlier terminal transition of the item returned.
"""
self._services.logger.debug(
f"On after run session: queue item {queue_item.item_id}, session {queue_item.session_id}"
)
# The item's preview frame is disposable: whatever the outcome, nothing may replay it now.
self._services.progress_previews.clear(queue_item.item_id)
# If we are profiling, stop the profiler and dump the profile & stats
if self._profiler is not None:
profile_path = self._profiler.stop()
stats_path = profile_path.with_suffix(".json")
self._services.performance_statistics.dump_stats(
graph_execution_state_id=queue_item.session.id, output_path=stats_path
)
try:
# Update the queue item with the completed session. If the queue item has been removed from the queue,
# we'll get a SessionQueueItemNotFoundError and we can ignore it. This can happen if the queue is cleared
# while the session is running.
queue_item = self._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)
# The queue item may have been canceled or failed while the session was running. We should only complete it
# if it is not already canceled or failed.
if queue_item.status not in ["canceled", "failed"] and queue_item.session.is_complete():
completing = queue_item
queue_item = self._settle(
completing.item_id,
lambda: self._services.session_queue.complete_queue_item(completing.item_id, queue_item=completing),
queue_item=completing,
)
self._settled_item = queue_item
# We'll get a GESStatsNotFoundError if we try to log stats for an untracked graph, but in the processor
# we don't care about that - suppress the error.
with suppress(GESStatsNotFoundError):
self._services.performance_statistics.log_stats(queue_item.session.id)
self._services.performance_statistics.reset_stats(queue_item.session.id)
for callback in self._on_after_run_session_callbacks:
callback(queue_item=queue_item)
except SessionQueueItemNotFoundError:
pass
def _on_before_run_node(self, invocation: BaseInvocation, queue_item: SessionQueueItem):
"""Called before a node is run.
- Emits an invocation started event.
- Run any callbacks registered for this event.
"""
self._services.logger.debug(
f"On before run node: queue item {queue_item.item_id}, session {queue_item.session_id}, node {invocation.id} ({invocation.get_type()})"
)
# Send starting event
self._services.events.emit_invocation_started(queue_item=queue_item, invocation=invocation)
for callback in self._on_before_run_node_callbacks:
callback(invocation=invocation, queue_item=queue_item)
def _on_after_run_node(
self, invocation: BaseInvocation, queue_item: SessionQueueItem, output: BaseInvocationOutput
):
"""Called after a node is run.
- Emits an invocation complete event.
- Run any callbacks registered for this event.
- Records that the node completed (see `_run_calibration_node`).
"""
self._services.logger.debug(
f"On after run node: queue item {queue_item.item_id}, session {queue_item.session_id}, node {invocation.id} ({invocation.get_type()})"
)
# The node's denoise is over: its last frame must not be replayed as if still running.
self._services.progress_previews.clear_node(queue_item.item_id, invocation.id)
# Send complete event on successful runs
self._services.events.emit_invocation_complete(invocation=invocation, queue_item=queue_item, output=output)
for callback in self._on_after_run_node_callbacks:
callback(invocation=invocation, queue_item=queue_item, output=output)
self._node_outcome = "completed"
def _on_node_error(
self,
invocation: BaseInvocation,
queue_item: SessionQueueItem,
error_type: str,
error_message: str,
error_traceback: str,
require_active: bool = False,
):
"""Called when a node errors. Node errors may occur when running or preparing the node..
- Records that the node failed, ahead of anything that can raise (see `_run_calibration_node`).
- Set the node error on the session object.
- Log the error.
- Fail the queue item.
- Emits an invocation error event.
- Run any callbacks registered for this event.
"""
self._node_outcome = "failed"
self._services.progress_previews.clear_node(queue_item.item_id, invocation.id)
self._services.logger.debug(
f"On node error: queue item {queue_item.item_id}, session {queue_item.session_id}, node {invocation.id} ({invocation.get_type()})"
)
# Node errors do not get the full traceback. Only the queue item gets the full traceback.
node_error = f"{error_type}: {error_message}"
queue_item.session.set_node_error(invocation.id, node_error)
self._services.logger.error(
f"Error while invoking session {queue_item.session_id}, invocation {invocation.id} ({invocation.get_type()}): {error_message}"
)
self._services.logger.error(error_traceback)
# Keep the live session for the invocation error event. Terminal queue persistence may clean up prepared
# execution mappings, but the event still needs the source id for the invocation that failed.
event_queue_item = queue_item
# Fail the queue item
if require_active:
saved = self._save_queue_item_session_if_active(queue_item)
if not saved:
return False
queue_item = self._services.session_queue.get_queue_item(queue_item.item_id)
else:
queue_item = self._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)
failing = queue_item.item_id
queue_item = self._settle(
failing,
lambda: self._services.session_queue.fail_queue_item(failing, error_type, error_message, error_traceback),
)
# Send error event
self._services.events.emit_invocation_error(
queue_item=event_queue_item,
invocation=invocation,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
for callback in self._on_node_error_callbacks:
callback(
invocation=invocation,
queue_item=queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
return True
def _save_queue_item_session_if_active(self, queue_item: SessionQueueItem) -> bool:
"""Persist a workflow-call transition only while its queue item remains active."""
saver = getattr(self._services.session_queue, "_save_queue_item_session_if_active", None)
if saver is not None:
return bool(saver(queue_item.item_id, queue_item.session))
try:
current_queue_item = self._services.session_queue.get_queue_item(queue_item.item_id)
except SessionQueueItemNotFoundError:
return False
if current_queue_item.status in ("completed", "failed", "canceled"):
return False
self._services.session_queue.save_queue_item_session(queue_item.item_id, queue_item.session)
return True
class _SessionWorker:
"""A single generation worker: one thread, optionally pinned to one device.
In single-device (legacy) mode there is exactly one worker with `device=None`. In multi-GPU
mode there is one worker per configured device, each with its own session runner and cancel
event so concurrent sessions can be canceled independently.
"""
def __init__(self, device: Optional[torch.device], runner: SessionRunnerBase) -> None:
self.device = device
self.runner = runner
self.cancel_event = ThreadEvent()
self.poll_now_event = ThreadEvent()
self.queue_item: Optional[SessionQueueItem] = None
self.thread: Optional[Thread] = None
# Paged-out VRAM at the previous session's end and at the last warning; only this worker's thread uses them.
self.paging_last_bytes = 0
self.paging_warned_bytes = 0
@property
def label(self) -> str:
return str(self.device) if self.device is not None else "default device"
class DefaultSessionProcessor(SessionProcessorBase):
def __init__(
self,
session_runner: Optional[SessionRunnerBase] = None,
on_non_fatal_processor_error_callbacks: Optional[list[OnNonFatalProcessorError]] = None,
thread_limit: int = 1,
polling_interval: int = 1,
) -> None:
super().__init__()
self.session_runner = session_runner if session_runner else DefaultSessionRunner()
self.workflow_call_queue_lifecycle = self.session_runner.workflow_call_queue_lifecycle
self._on_non_fatal_processor_error_callbacks = on_non_fatal_processor_error_callbacks or []
self._thread_limit = thread_limit
self._polling_interval = polling_interval
self._workers: list[_SessionWorker] = []
# One per worker, once `register_generation_devices` resolved them.
self._devices: Optional[list[Optional[torch.device]]] = None
def register_generation_devices(self, configuration: InvokeAIAppConfig) -> list[Optional[torch.device]]:
"""Resolve the workers' devices and register them in `GENERATION_DEVICE_POOL`, so the model loader can find
idle GPUs to borrow. Returns the devices, one per worker.
Work outside the session queue borrows from the pool from the moment its service starts (the image index's
backfill, say), so the composition root calls this before the invoker starts any service
(`ApiDependencies.initialize`). `start` calls it only when nothing did: registering again would drop a borrow in
flight. Registering creates no CUDA context: the pool holds device objects, and a worker pins its GPU in CUDA
only once it claims its first queue item (#9413).
`generation_devices` (by default `"auto"`, every available GPU) resolves to one normalized device per worker,
or to a single `None` (one worker on the device the global config chooses) when the resolution is empty, as
with an empty list.
Raises RuntimeError while a worker an earlier `stop` gave up on still runs (see `stop`).
"""
refuse_while_an_abandoned_worker_runs()
devices = TorchDevice.get_generation_devices(configuration.generation_devices)
self._devices = list(devices) if devices else [None]
GENERATION_DEVICE_POOL.set_generation_devices([d for d in self._devices if d is not None])
return self._devices
def _clone_session_runner(self, template: SessionRunnerBase) -> SessionRunnerBase:
"""Create an independent runner for an additional worker.
Each worker needs its own runner because the runner stores its session's cancel event.
We carry over the template's callbacks so all workers behave identically.
"""
# `type is`, not isinstance: a subclass would be silently downgraded to a plain
# DefaultSessionRunner, losing its overrides.
if type(template) is DefaultSessionRunner:
return DefaultSessionRunner(
on_before_run_session_callbacks=list(template._on_before_run_session_callbacks),
on_before_run_node_callbacks=list(template._on_before_run_node_callbacks),
on_after_run_node_callbacks=list(template._on_after_run_node_callbacks),
on_node_error_callbacks=list(template._on_node_error_callbacks),
on_after_run_session_callbacks=list(template._on_after_run_session_callbacks),
)
# Any other implementation cannot be cloned generically, and sharing one instance across
# workers is not safe either: every start() overwrites the runner's stored cancel event, so
# only the last worker's cancellation would ever fire. Fail loudly at startup instead.
raise ValueError(
f"Multiple generation devices require DefaultSessionRunner; got {type(template).__name__}. "
"Provide a DefaultSessionRunner (with callbacks), or configure a single device in "
"generation_devices."
)
def start(self, invoker: Invoker) -> None:
"""Start one worker per generation device. Raises RuntimeError while a worker an earlier `stop` gave up on
still runs (see `stop`)."""
refuse_while_an_abandoned_worker_runs()
self._invoker: Invoker = invoker
self._resume_event = ThreadEvent()
self._stop_event = ThreadEvent()
register_events(QueueClearedEvent, self._on_queue_cleared)
register_events(BatchEnqueuedEvent, self._on_batch_enqueued)
register_events(QueueItemStatusChangedEvent, self._on_queue_item_status_changed)
register_events(UserAccessChangedEvent, self._on_user_access_changed)
devices = (
self._devices
if self._devices is not None
else self.register_generation_devices(self._invoker.services.configuration)
)
# 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)
# 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
# empty_cache wrapper cannot intercept it. Trade it for cached workspace blocks instead.
if sum(1 for d in devices if d is not None and d.type == "cuda") > 1:
disable_conv_benchmark_empty_cache()
# If profiling is enabled, create a profiler. The same profiler will be used for all sessions. Internally,
# the profiler will create a new profile for each session. Profiling uses a process-global cProfile, which
# cannot cleanly attribute work when multiple sessions run concurrently, so it is disabled in multi-GPU mode.
profiler_enabled = self._invoker.services.configuration.profile_graphs
if profiler_enabled and len(devices) > 1:
self._invoker.services.logger.warning(
"Graph profiling is disabled because multiple generation devices are configured."
)
profiler_enabled = False
self._profiler = (
Profiler(
logger=self._invoker.services.logger,
output_dir=self._invoker.services.configuration.profiles_path,
prefix=self._invoker.services.configuration.profile_prefix,
)
if profiler_enabled
else None
)
self._thread_semaphore = BoundedSemaphore(len(devices))
# Start in the running (resumed) state.
self._stop_event.clear()
self._resume_event.set()
self._workers = []
for index, device in enumerate(devices):
runner = self.session_runner if index == 0 else self._clone_session_runner(self.session_runner)
worker = _SessionWorker(device=device, runner=runner)
runner.start(services=invoker.services, cancel_event=worker.cancel_event, profiler=self._profiler)
self._workers.append(worker)
if len(self._workers) > 1:
self._invoker.services.logger.info(
f"Starting session processor with {len(self._workers)} parallel workers on devices: "
f"{', '.join(w.label for w in self._workers)}"
)
for index, worker in enumerate(self._workers):
worker.thread = Thread(
name=f"session_processor_{index}",
target=self._process,
daemon=True,
kwargs={
"worker": worker,
"stop_event": self._stop_event,
"resume_event": self._resume_event,
},
)
worker.thread.start()
def stop(self, *args, **kwargs) -> None:
"""Stop the workers and wait for them to exit, up to `WORKER_STOP_TIMEOUT_SECONDS` for all of them together.
The invoker stops every other service once this returns, so a worker that exits in time never runs beside a
stopped service. A wait longer than `WORKER_STOP_NOTICE_SECONDS` names the worker and its queue item in the
log. A worker still in a node at the deadline is given up on, with an error in the log, so that shutdown
finishes: a node without a cancel point may never return. A later stop does not wait for it again. It keeps
its GPU, so until it exits no session processor of this process starts and none replaces the generation device
pool. The services it uses stop under it; once the database is disposed, its writes are refused.
"""
self._stop_event.set()
# Cancel any in-progress generation so that long-running nodes (e.g. denoising) stop at
# the next step boundary instead of running to completion. Without this, a generation
# thread may still be executing CUDA operations when Python teardown begins, which can
# cause a C++ std::terminate() crash ("terminate called without an active exception").
for worker in self._workers:
worker.cancel_event.set()
# Wake any worker sleeping in poll_now_event.wait() or blocked in resume_event.wait() (paused).
self._poll_now()
self._resume_event.set()
deadline = time.monotonic() + WORKER_STOP_TIMEOUT_SECONDS
for worker in self._workers:
# A worker given up on by an earlier stop gets no second wait.
if worker.thread is None or worker.thread in _abandoned_workers:
continue
worker.thread.join(timeout=max(0.0, min(deadline - time.monotonic(), WORKER_STOP_NOTICE_SECONDS)))
remaining = deadline - time.monotonic()
if worker.thread.is_alive() and remaining > 0:
self._invoker.services.logger.info(
f"Waiting up to {remaining:.0f}s for the {self._describe_running(worker)} to stop"
)
worker.thread.join(timeout=remaining)
if worker.thread.is_alive():
_abandoned_workers.append(worker.thread)
self._invoker.services.logger.error(
f"The {self._describe_running(worker)} did not stop within {WORKER_STOP_TIMEOUT_SECONDS:.0f}s; "
"shutting down without it. Restart the process before starting Invoke again."
)
@staticmethod
def _describe_running(worker: _SessionWorker) -> str:
assert worker.thread is not None
queue_item = worker.queue_item
item = f" (queue item {queue_item.item_id})" if queue_item is not None else ""
return f"session worker {worker.thread.name} on {worker.label}{item}"
def _poll_now(self) -> None:
# Each consumer clears only its own notification, never another worker's wake-up.
for worker in self._workers:
worker.poll_now_event.set()
async def _on_queue_cleared(self, event: FastAPIEvent[QueueClearedEvent]) -> None:
# Cancel every worker currently running an item covered by the clear. A user-scoped
# clear (event.user_id set) covers only that user's items — other users' workers
# must keep running; setting their cancel event would stop a session whose row the
# clear didn't touch, abandoning it in_progress. (In-progress items in scope were
# also individually canceled by the service before the rows were deleted; this is
# the backstop for workers that claimed an item after that pass.)
payload = event[1]
canceled = False
for worker in self._workers:
# Bound to a local for the same reason as in `_on_queue_item_status_changed`:
# the worker thread can clear the field between two reads of it.
queue_item = worker.queue_item
if (
queue_item
and queue_item.queue_id == payload.queue_id
and (payload.user_id is None or queue_item.user_id == payload.user_id)
):
worker.cancel_event.set()
canceled = True
if canceled:
self._poll_now()
async def _on_batch_enqueued(self, event: FastAPIEvent[BatchEnqueuedEvent]) -> None:
self._poll_now()
async def _on_user_access_changed(self, event: FastAPIEvent[UserAccessChangedEvent]) -> None:
# If the owner of the currently running queue item was deactivated or deleted,
# cancel the item immediately. Canceling emits a QueueItemStatusChangedEvent,
# which sets the cancel event (see `_on_queue_item_status_changed`), stopping
# long-running nodes at their next step callback rather than waiting for the
# node to finish. Pending items are handled at dequeue.
event_data = event[1]
if event_data.is_active:
return
# A single user may have items running on several workers concurrently, so
# cancel every match rather than stopping at the first.
queue_items: list[SessionQueueItem] = []
for worker in self._workers:
queue_item = worker.queue_item
if queue_item is not None and queue_item.user_id == event_data.user_id:
queue_items.append(queue_item)
if not queue_items:
return
# Run the cancellations in a thread. `cancel_queue_item` walks the workflow-call
# chain and issues a transaction per item, all behind the process-wide SQLite lock;
# doing that inline would block the event loop — and with it every HTTP response,
# socket emission, and event dispatch, including the QueueItemStatusChangedEvents
# this cancellation depends on to reach the workers.
#
# The workers' cancel events are deliberately NOT set here. `cancel_queue_item`
# writes the row terminal before emitting, and `_process` relies on that ordering:
# a cancel event set while the row is still non-terminal is treated as a stale
# signal from a previous item and cleared (see the guard after dequeue), which
# would discard this cancellation.
# Re-read the owner at the point of decision rather than trusting the event alone.
# Handlers are dispatched as independent tasks, so a deactivate immediately
# followed by a reactivate can leave this one parked here while the second event
# has already come and gone (it returns early above) — cancelling then would kill
# a running item of an account the database says is active, with nothing to undo
# it.
#
# A failed read fails closed here too, and for a stronger reason than at the
# dequeue and between-node gates: this handler is the only thing that stops a
# *single-node* graph, which is checked once before it starts and never again.
# The event is itself evidence of a committed deactivation, so when the re-read
# cannot contradict it, the event stands.
def _cancel_all() -> None:
for item in queue_items:
if not self._invoker.services.configuration.multiuser:
return
try:
owner = self._invoker.services.users.get(item.user_id)
except Exception:
self._invoker.services.logger.warning(
f"Could not re-verify owner {item.user_id} of queue item {item.item_id}; "
"honoring the access-changed event and canceling"
)
else:
if owner is not None and owner.is_active:
continue
self._invoker.services.logger.warning(
f"Canceling queue item {item.item_id}: owner {item.user_id} was deactivated or deleted"
)
with suppress(SessionQueueItemNotFoundError):
self._invoker.services.session_queue.cancel_queue_item(item.item_id)
await run_in_threadpool(_cancel_all)
async def _on_queue_item_status_changed(self, event: FastAPIEvent[QueueItemStatusChangedEvent]) -> None:
# Find the worker (if any) currently running the item whose status changed.
for worker in self._workers:
# Bound to a local: the worker thread can clear the field between the two reads
# a `worker.queue_item and worker.queue_item.x` test would make, and the
# AttributeError would escape this handler — which the event dispatcher runs in
# the same task as every other handler for this event, so the ones registered
# after it would be skipped.
queue_item = worker.queue_item
if queue_item and queue_item.item_id == event[1].item_id:
if event[1].status in ["completed", "failed", "canceled"]:
# When the queue item is canceled via HTTP, the status is set to "canceled" and this event is
# emitted. We respond by setting that worker's cancel event, which its session runner checks
# between invocations (and which denoise_latents' step callback checks mid-node, raising
# CanceledException to stop immediately).
if event[1].status == "canceled":
worker.cancel_event.set()
self._poll_now()
return
def _release_vram_after_session(self, worker: _SessionWorker, *, run_returned: bool) -> None:
"""Return this worker's unoccupied cached VRAM to the driver now that its session is over.
A session that ended early -- canceled, failed in a node, or aborted by an error escaping the runner
(`run_returned` False) -- never ran the nodes that would release its working memory (a VAE decode, say). A
canceled or failed node also leaves its own working set orphaned in the caching allocator, so the GPU keeps
reporting the memory as used. Ask for the release explicitly. After an out-of-memory failure this matters
most: those blocks were the card's only headroom, and the next session can fail on its first device operation
that needs memory from the driver rather than from torch's allocator. On a multi-GPU box with a peer
mid-render the call is deferred (see `TorchDevice.empty_cache`) and runs at the first flush that finds no
other device mid-session. A session that ran to completion has released its own working memory along the way,
so it only flushes a release a peer deferred onto it -- a flag test when nothing is pending.
With `clear_vram_after_session`, every unlocked model on this worker's device also moves to
RAM first (it stays cached there), and the release is forced past a busy peer: deferred, it
would leave the freed memory with the allocator while this worker's next session budgets its
first load, which then loads at minimum residency. Once per session, and the user opted in.
Best effort: the session's outcome is already recorded, and neither the offload nor the forced release (which
raises when the device refuses it) on a sick device context may fail the worker.
"""
try:
services = self._invoker.services
if services.configuration.clear_vram_after_session and services.model_manager.load is not None:
with MODEL_LOAD_LOCK.read_lock():
services.model_manager.load.ram_cache.offload_models_from_vram_except(())
TorchDevice.empty_cache(force=True)
elif self._session_ended_early(worker, run_returned):
TorchDevice.empty_cache()
else:
TorchDevice.flush_deferred_empty_cache()
except Exception:
self._invoker.services.logger.warning(
f"Could not release cached VRAM after the session on {worker.label}", exc_info=True
)
@staticmethod
def _session_ended_early(worker: _SessionWorker, run_returned: bool) -> bool:
"""True when the session was stopped by the cancel event, recorded a node error, or the runner raised.
The runner records node errors on the in-memory session it was handed, which is `queue_item.session`. An
ending between nodes (the owner revoked before the status handler set the cancel event, a calibration whose
measurements were not saved) counts as finished: no node was interrupted.
"""
if not run_returned or worker.cancel_event.is_set():
return True
queue_item = worker.queue_item
return queue_item is not None and queue_item.session.has_error()
def _log_attention_backends(self, worker: _SessionWorker) -> None:
"""Log which SDPA kernels this worker's device has and the order they are tried in, once per device.
Asked for each item about to run, rather than at startup: the probe allocates, so on the boot path it would
create a CUDA context on an idle server, and so would an item that is skipped before it runs in single-device
mode. `log_attention_backends` remembers the device, so the probe runs on the first such item, before models are
resident; it ends with `empty_cache()`. A diagnostic: it must not fail the item.
"""
try:
log_attention_backends(self._invoker.services.logger, worker.device or TorchDevice.choose_torch_device())
except Exception:
self._invoker.services.logger.debug(
f"Could not probe the attention backends on {worker.label}", exc_info=True
)
def _warn_if_vram_paged(self, worker: _SessionWorker) -> None:
"""Say so when Windows keeps part of this worker's GPU memory in shared system memory across sessions.
On a ROCm build under Windows an allocation that does not fit the video-memory budget, or finds no contiguous
VRAM, is placed in system memory instead of failing -- and another program on the same GPU can push this
process's memory out the same way. Every generation that touches it slows down, with nothing else in the log to
explain why. Only what was paged at the end of two consecutive sessions counts: an overflow at the end of a
decode can return to VRAM within seconds. Warns once per episode: again only after that grew by the threshold,
re-armed once a reading drops below it. `paged_bytes` answers None everywhere else, which keeps this silent.
"""
try:
paged = paged_bytes(worker.device or TorchDevice.choose_torch_device())
except Exception:
self._invoker.services.logger.debug(f"Could not read paged VRAM on {worker.label}", exc_info=True)
return
if paged is None:
return
sustained = min(paged, worker.paging_last_bytes)
worker.paging_last_bytes = paged
if paged < _VRAM_PAGING_WARNING_BYTES:
worker.paging_warned_bytes = 0
return
if sustained < worker.paging_warned_bytes + _VRAM_PAGING_WARNING_BYTES:
return
worker.paging_warned_bytes = sustained
self._invoker.services.logger.warning(
f"Windows kept {sustained / 2**30:.1f} GiB of Invoke's GPU memory on {worker.label} in shared system memory "
"after the last two generations, which makes them much slower. Close other programs that use this GPU. If "
"it keeps happening, lower the image size, set max_cache_vram_gb lower or device_working_mem_gb higher, "
"and restart Invoke to get the memory back into VRAM."
)
def resume(self) -> SessionProcessorStatus:
if not self._resume_event.is_set():
self._resume_event.set()
return self.get_status()
def pause(self) -> SessionProcessorStatus:
if self._resume_event.is_set():
self._resume_event.clear()
return self.get_status()
def get_status(self) -> SessionProcessorStatus:
return SessionProcessorStatus(
is_started=self._resume_event.is_set(),
is_processing=any(worker.queue_item is not None for worker in self._workers),
)
def get_running_queue_item_owners(self) -> set[str]:
# `worker.queue_item` is written by the worker thread and read here from the event
# loop, so it is bound to a local before being dereferenced — the field can go
# `None` between the two. `_workers` is rebound by `start()` rather than mutated
# after it, and iteration binds the list object, so it cannot change under this
# loop. The worst a race yields is the item that was running an instant ago, whose
# owner the caller re-reads from the database anyway.
owners: set[str] = set()
for worker in self._workers:
queue_item = worker.queue_item
if queue_item is not None:
owners.add(queue_item.user_id)
return owners
def _is_queue_item_terminal(self, item_id: int) -> bool:
"""Return True if the queue item is already finished (canceled/failed/completed) or gone.
Checked right after a worker claims an item to catch a cancellation that raced the claim and
so never reached this worker's cancel_event — e.g. the status-changed handler ran before the
worker recorded `queue_item` and so couldn't match a worker to signal.
"""
try:
status = self._invoker.services.session_queue.get_queue_item(item_id).status
except SessionQueueItemNotFoundError:
return True
return status in ("canceled", "failed", "completed")
def _is_image_move_maintenance_active(self) -> bool:
image_moves = getattr(self._invoker.services, "image_moves", None)
return image_moves is not None and image_moves.is_maintenance_active()
def _dequeue_if_storage_maintenance_inactive(
self, device: Optional[str]
) -> tuple[bool, Optional[SessionQueueItem]]:
"""Atomically check storage maintenance state and claim the next queue item.
Gallery maintenance reserves its busy flag before taking the same mutation lock. If
this worker wins the lock first, the subsequent reservation sees the claimed item in
queue status; if maintenance wins, this worker leaves queued work pending.
"""
image_moves = getattr(self._invoker.services, "image_moves", None)
mutation_lock = (
image_moves.image_mutation_lock(blocking=False) if image_moves is not None else nullcontext(True)
)
with mutation_lock as lock_acquired:
if not lock_acquired:
return False, None
if self._is_image_move_maintenance_active():
return False, None
item = self._invoker.services.session_queue.dequeue(device=device)
return True, item
def _cancel_queue_item_if_owner_inactive(self, queue_item: SessionQueueItem) -> bool:
"""Cancel a dequeued item whose owner is deactivated, deleted, or unverifiable.
Returns True if the item was rejected (canceled) and must not be executed.
"""
if queue_owner_is_active(self._invoker.services, queue_item):
return False
self._invoker.services.logger.warning(
f"Canceling queue item {queue_item.item_id}: owner {queue_item.user_id} is deactivated, "
"deleted, or could not be verified"
)
with suppress(SessionQueueItemNotFoundError):
self._invoker.services.session_queue.cancel_queue_item(queue_item.item_id)
return True
def _process(
self,
worker: _SessionWorker,
stop_event: ThreadEvent,
resume_event: ThreadEvent,
):
try:
# Any unhandled exception in this block is a fatal processor error and will stop this worker.
self._thread_semaphore.acquire()
# Pin this worker thread to its device so all device-selecting code (TorchDevice.choose_torch_device,
# which nodes and the model loader consult) resolves to this GPU. CUDA's and XPU's current
# device are both per-thread.
if worker.device is not None:
TorchDevice.set_session_device(worker.device)
# torch.cuda.set_device() initializes CUDA on the device, which can permanently reserve
# VRAM in an otherwise idle process (#9413). Defer the CUDA-side pin until this worker
# claims its first queue item; the pin is per-thread and this thread persists, so pinning
# once before the first item is equivalent to pinning here. torch.xpu.set_device() brings
# up a SYCL context with the same effect, so XPU is deferred on the same terms.
device_pin_needed = worker.device is not None and worker.device.type in ("cuda", "xpu")
worker.cancel_event.clear()
while not stop_event.is_set():
worker.poll_now_event.clear()
# The previous item, if any, is finished with. Cleared here rather than
# after `run_queue_item` because the non-fatal error handler below needs it
# to fail the item, and it reaches this point by `continue`. Without this,
# a worker that finishes an item and then parks — paused, or waiting out
# image-move maintenance, both of which block before the dequeue below —
# goes on reporting that item as running for as long as it stays parked.
# `get_status` and `get_running_queue_item_owners` both read it.
worker.queue_item = None
session_started = False
processor_error = False
try:
# Any unhandled exception in this block is a nonfatal processor error and will be handled.
# If we are paused, wait for resume event
resume_event.wait()
if stop_event.is_set():
break
# Clear any stale cancel signal from the previous item BEFORE claiming the next
# one. Clearing it after dequeue (as before) could wipe a cancel that arrived for
# the item we just claimed — e.g. during the gc.collect() below — silently losing
# the cancellation. Any cancel that arrives after this point for the claimed item
# 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):
worker.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).
maintenance_inactive, worker.queue_item = self._dequeue_if_storage_maintenance_inactive(
device=str(worker.device) if worker.device is not None else None
)
if not maintenance_inactive:
self._invoker.services.logger.debug("Image storage maintenance is active")
worker.poll_now_event.wait(self._polling_interval)
continue
if worker.queue_item is None:
# The queue was empty, wait for next polling interval or event to try again
self._invoker.services.logger.debug("Waiting for next polling interval or event")
worker.poll_now_event.wait(self._polling_interval)
continue
if device_pin_needed:
assert worker.device is not None
# 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 this
# deferral exists to perform.
if worker.device.type == "cuda":
torch.cuda.set_device(worker.device)
else:
torch.xpu.set_device(worker.device)
device_pin_needed = False
# A cancellation can race the claim: it may have marked the row terminal before
# this worker recorded `queue_item`, so _on_queue_item_status_changed couldn't set
# our cancel_event. A fresh DB status read is the authority — skip running an
# already-finished item so the cancel is never lost.
if self._is_queue_item_terminal(worker.queue_item.item_id):
self._invoker.services.logger.debug(
f"Queue item {worker.queue_item.item_id} was canceled before it started; skipping."
)
continue
if worker.cancel_event.is_set():
if stop_event.is_set():
# Shutdown raced the claim: don't start new work, and mark the fresh
# claim canceled so it isn't abandoned in_progress (dequeue only ever
# claims 'pending' rows).
with suppress(SessionQueueItemNotFoundError):
self._invoker.services.session_queue.cancel_queue_item(worker.queue_item.item_id)
continue
# The event was set by a delayed handler for the PREVIOUS item (it matched
# the stale worker.queue_item before dequeue replaced it). No cancellation
# targeted the freshly claimed row — a genuine cancel writes the row
# terminal BEFORE emitting its event, and the terminal check above just
# said this row isn't. Clear the stale signal and run the item rather than
# discarding an unrelated user's queued generation.
worker.cancel_event.clear()
# Close the clear's own race: a genuine cancel for THIS item that landed
# between the terminal check and the clear has already written the row
# terminal (the DB write precedes the event), so one more read catches it.
# A cancel landing after this read re-sets the event via the status-change
# handler (worker.queue_item now IS this item) and the runner catches it.
if self._is_queue_item_terminal(worker.queue_item.item_id):
self._invoker.services.logger.debug(
f"Queue item {worker.queue_item.item_id} was canceled before it started; skipping."
)
continue
# Reject items whose owner was deactivated or deleted while the item
# was pending — no invocation may run and no output may be saved on
# behalf of a revoked account.
if self._cancel_queue_item_if_owner_inactive(worker.queue_item):
continue
# GC-ing here can reduce peak memory usage of the invoke process by freeing allocated memory blocks.
# Most queue items take seconds to execute, so the relative cost of a GC is very small.
# Python will never cede allocated memory back to the OS, so anything we can do to reduce the peak
# allocation is well worth it.
gc.collect()
self._log_attention_backends(worker)
self._invoker.services.logger.info(
f"Executing queue item {worker.queue_item.item_id}, session {worker.queue_item.session_id} "
f"on {worker.label}"
)
# Run the graph. Hold this GPU's exclusive-use lock for the whole session so no
# other worker can borrow it for text-encoder offload while we're running on it
# (a borrow + concurrent native session on one GPU would corrupt the shared
# cached encoder). Acquired here, after dequeue, so an idle worker doesn't hold
# the lock and block borrows while waiting for work.
# Route through this worker's own runner's workflow-call lifecycle so child
# workflow completion resumes the parent via the runner that owns this
# worker's cancel event.
GENERATION_DEVICE_POOL.acquire_session(worker.device)
session_started = True
try:
worker.runner.workflow_call_queue_lifecycle.run_queue_item(worker.queue_item)
finally:
GENERATION_DEVICE_POOL.release_session(worker.device)
self._release_vram_after_session(worker, run_returned=True)
self._warn_if_vram_paged(worker)
except Exception as e:
error_type = e.__class__.__name__
error_message = str(e)
error_traceback = traceback.format_exc()
self._on_non_fatal_processor_error(
queue_item=worker.queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
processor_error = True
if processor_error:
# Outside the `except`: while the exception is in flight its traceback keeps the failed node's
# frames, and the tensors in them, alive, so the release would not free what that node held.
if session_started:
self._release_vram_after_session(worker, run_returned=False)
# Wait for next polling interval or event to try again
worker.poll_now_event.wait(self._polling_interval)
except Exception as e:
# Fatal error in this worker, log and pass - we're done here
error_type = e.__class__.__name__
error_message = str(e)
error_traceback = traceback.format_exc()
self._invoker.services.logger.error(f"Fatal Error in session processor {error_type}: {error_message}")
self._invoker.services.logger.error(error_traceback)
pass
finally:
worker.queue_item = None
if worker.device is not None:
TorchDevice.clear_session_device()
self._thread_semaphore.release()
def _on_non_fatal_processor_error(
self,
queue_item: Optional[SessionQueueItem],
error_type: str,
error_message: str,
error_traceback: str,
) -> None:
"""Called when a non-fatal error occurs in the processor.
- Log the error.
- If a queue item is provided, update the queue item with the completed session & fail it.
- Run any callbacks registered for this event.
"""
self._invoker.services.logger.error(f"Non-fatal error in session processor {error_type}: {error_message}")
self._invoker.services.logger.error(error_traceback)
if queue_item is not None:
# This path bypasses the runner's after-session hook; the item's frame must not outlive it.
self._invoker.services.progress_previews.clear(queue_item.item_id)
try:
queue_item = self._invoker.services.session_queue.set_queue_item_session(
queue_item.item_id, queue_item.session
)
queue_item = self._invoker.services.session_queue.fail_queue_item(
item_id=queue_item.item_id,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)
except SessionQueueItemNotFoundError:
self._invoker.services.logger.warning(
f"Could not mark queue item {queue_item.item_id} as failed because it no longer exists in the database."
)
for callback in self._on_non_fatal_processor_error_callbacks:
callback(
queue_item=queue_item,
error_type=error_type,
error_message=error_message,
error_traceback=error_traceback,
)