Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

perf(execution): make For scheduling linear

JPPhotof16f76eee13b
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index ed4eb12f86..ca95289940 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -305,6 +305,14 @@ remain compatibility-owned; the narrow canonical two-level nested-`For` shape an
`Iterate`/`Collect` shape are generic-routed. On rehydration, the generic adapter restores the active class-drain
boundary so an in-flight nested stream resumes in the same frame/sequence order.
+For scheduling is linear in the collection size. The continuation transfers ownership of the remaining collection to the
+next prepared `For` node instead of deep-copying it at every iteration. Source completion uses a derived, lazy per-source
+count of pending prepared executions, and continuation validation uses the existing prepared-`For` index rather than
+rescanning every prior iteration. The count is runtime-only and is rebuilt after snapshot rehydration; it does not change
+the persisted execution-state or invocation contracts. The focused For performance, collection-ownership, count-invariant,
+and generic/compatibility differential tests cover this boundary. The direct Iterate planner has separate readiness
+projection costs and is not part of this For-specific optimization.
+
`ExecutionFrame` identifies the owning state, loop iteration path, and workflow-call depth. `ExecutionReference`
identifies one prepared execution node and its frame. `ExecutionToken` records an output port, value, frame, token
kind, and optional sequence. `loop_linkage` remains association metadata and never becomes a data token. This ledger is
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 1be291d44a..0046744bef 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -285,6 +285,7 @@ class GraphExecutionState(BaseModel):
_source_graph_flat: Any | None = PrivateAttr(default=None)
_execution_graph_flat: Any | None = PrivateAttr(default=None)
_completed_source_ids_cache: Optional[set[str]] = PrivateAttr(default=None)
+ _unexecuted_prepared_counts: Optional[dict[str, int]] = PrivateAttr(default=None)
_for_source_by_return_id: Optional[dict[str, str]] = PrivateAttr(default=None)
_apply_transaction: Optional[_ApplyTransaction] = PrivateAttr(default=None)
_generic_execution_runtime: Optional[ExecutionEngineRuntime] = PrivateAttr(default=None)
@@ -395,6 +396,7 @@ class GraphExecutionState(BaseModel):
self._source_graph_flat = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
+ self._unexecuted_prepared_counts = None
self._for_source_by_return_id = None
self._for_parent_iteration_paths_cache = {}
self._all_for_contexts_finalized_cache = {}
@@ -479,6 +481,48 @@ class GraphExecutionState(BaseModel):
# A source can be discarded while its already-prepared executions are still complete. New executions
# invalidate the derived completion cache when they are registered.
+ def _mark_exec_node_executed(self, exec_node_id: str) -> None:
+ """Mark prepared exec node executed and maintain per-source pending count."""
+ if exec_node_id in self.executed:
+ return
+ self._tx_add_set(self.executed, exec_node_id)
+ counts = self._unexecuted_prepared_counts
+ if counts is None:
+ return
+ source_node_id = self.prepared_source_mapping.get(exec_node_id)
+ if source_node_id is None:
+ return
+ # Empty loop contexts can drop reverse mappings while retaining forward mappings.
+ if exec_node_id not in self.source_prepared_mapping.get(source_node_id, ()):
+ return
+ old_count = counts.get(source_node_id, 0)
+ self._tx_record_once(
+ ("unexecuted_prepared_count", source_node_id),
+ lambda: counts.__setitem__(source_node_id, old_count),
+ )
+ counts[source_node_id] = max(old_count - 1, 0)
+
+ def _reset_unexecuted_prepared(self, source_node_id: str) -> None:
+ """Reset pending count after dropping prepared nodes for a source."""
+ if self._unexecuted_prepared_counts is None:
+ return
+ counts = self._unexecuted_prepared_counts
+ old_count = counts.get(source_node_id, 0)
+ self._tx_record_once(
+ ("unexecuted_prepared_count", source_node_id),
+ lambda: counts.__setitem__(source_node_id, old_count),
+ )
+ counts[source_node_id] = 0
+
+ def _count_unexecuted_prepared(self, source_node_id: str) -> int:
+ """Return prepared exec nodes not yet executed or skipped for source."""
+ if self._unexecuted_prepared_counts is None:
+ self._unexecuted_prepared_counts = {
+ mapped_source_id: sum(1 for exec_node_id in prepared_ids if exec_node_id not in self.executed)
+ for mapped_source_id, prepared_ids in self.source_prepared_mapping.items()
+ }
+ return self._unexecuted_prepared_counts.get(source_node_id, 0)
+
def _get_completed_source_ids_cache(self) -> set[str]:
if self._completed_source_ids_cache is None:
self._completed_source_ids_cache = {
@@ -486,8 +530,8 @@ class GraphExecutionState(BaseModel):
for source_node_id in self.graph.nodes
if source_node_id in self.executed
or (
- (prepared_node_ids := self.source_prepared_mapping.get(source_node_id))
- and all(exec_node_id in self.executed for exec_node_id in prepared_node_ids)
+ self.source_prepared_mapping.get(source_node_id)
+ and self._count_unexecuted_prepared(source_node_id) == 0
)
or self._is_source_inactive(source_node_id)
}
@@ -648,17 +692,18 @@ class GraphExecutionState(BaseModel):
next_state = self._get_loop_state_for_next_iteration(for_exec_node_id, output)
parent_iteration_path = self._get_for_parent_iteration_path(for_exec_node_id)
+ collection = for_node.collection
+ self._tx_set_attr(for_node, "collection", [])
next_for_id = self._materializer().create_for_iteration(
source_for_id=source_for_id,
iteration_index=next_index,
- collection=for_node.collection,
+ collection=collection,
state=next_state,
iteration_path=(*parent_iteration_path, next_index),
)
self._discard_source_executed(source_for_id)
self._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)
- self._tx_set_attr(for_node, "collection", [])
return None
def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
@@ -1239,16 +1284,9 @@ class GraphExecutionState(BaseModel):
parent_iteration_path = self._get_for_parent_iteration_path(node.id)
final_for_id = None
if source_node_id is not None:
- final_candidates = [
- prepared_for_id
- for prepared_for_id in self.source_prepared_mapping.get(source_node_id, ())
- if self._get_for_parent_iteration_path(prepared_for_id) == parent_iteration_path
- ]
- if final_candidates:
- final_for_id = max(
- final_candidates,
- key=lambda prepared_for_id: self.execution_graph.get_node(prepared_for_id).index,
- )
+ self._get_prepared_for_index()
+ assert self._final_prepared_for_index is not None
+ final_for_id = self._final_prepared_for_index.get((source_node_id, parent_iteration_path))
if (
source_node_id is not None
and final_for_id == node.id
@@ -1385,7 +1423,16 @@ class GraphExecutionState(BaseModel):
return dependency.cancel_child(str(child_item_id), error_message)
def _register_prepared_exec_node(self, exec_node_id: str, source_node_id: str) -> None:
+ is_new = exec_node_id not in self.source_prepared_mapping.get(source_node_id, ())
self._prepared_registry().register(exec_node_id, source_node_id)
+ if is_new and self._unexecuted_prepared_counts is not None and exec_node_id not in self.executed:
+ counts = self._unexecuted_prepared_counts
+ old_count = counts.get(source_node_id, 0)
+ self._tx_record_once(
+ ("unexecuted_prepared_count", source_node_id),
+ lambda: counts.__setitem__(source_node_id, old_count),
+ )
+ counts[source_node_id] = old_count + 1
self._tx_discard_set(self.executed, source_node_id)
if self._completed_source_ids_cache is not None:
self._tx_discard_set(self._completed_source_ids_cache, source_node_id)
@@ -2341,6 +2388,7 @@ class GraphExecutionState(BaseModel):
self._source_graph_flat = None
self._execution_graph_flat = None
self._completed_source_ids_cache = None
+ self._unexecuted_prepared_counts = None
self._for_parent_iteration_paths_cache = {}
self._all_for_contexts_finalized_cache = {}
self._prepared_for_index = None
diff --git a/invokeai/app/services/shared/graph_iterate_planner.py b/invokeai/app/services/shared/graph_iterate_planner.py
index bcf977343c..e9efad52fe 100644
--- a/invokeai/app/services/shared/graph_iterate_planner.py
+++ b/invokeai/app/services/shared/graph_iterate_planner.py
@@ -304,6 +304,7 @@ def _mark_direct_source_empty(state: "GraphExecutionState", source_node_id: str)
"""Record an empty direct iterator source without entering the legacy materializer."""
state._tx_set_mapping(state.source_prepared_mapping, source_node_id, set())
+ state._reset_unexecuted_prepared(source_node_id)
state._mark_source_executed(source_node_id)
if isinstance(state.graph.get_node(source_node_id), IterateInvocation):
state._record_empty_iterate_stream(source_node_id)
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.py
index f3c0b330cf..e988b4f6f7 100644
--- a/invokeai/app/services/shared/graph_materializer.py
+++ b/invokeai/app/services/shared/graph_materializer.py
@@ -224,7 +224,7 @@ class _ExecutionMaterializer:
final_state=initial_state,
),
)
- self._state._tx_add_set(self._state.executed, new_node.id)
+ self._state._mark_exec_node_executed(new_node.id)
self._state._set_prepared_exec_state(new_node.id, "executed")
return new_node.id
@@ -250,13 +250,18 @@ class _ExecutionMaterializer:
state: "LoopState",
iteration_path: tuple[int, ...],
) -> str:
+ """Prepare a For iteration, taking ownership of the remaining collection.
+
+ The caller clears the completed For node before handing over this list. Bypassing Pydantic assignment
+ validation is intentional: validation would rebuild the list and restore quadratic scheduling cost.
+ """
node = self._state.graph.get_node(source_for_id)
if not isinstance(node, ForInvocation):
raise TypeError(f"Expected source ForInvocation, got {type(node).__name__}")
new_node = self._create_execution_node_copy(node, source_for_id, iteration_index, deep_copy=False)
assert isinstance(new_node, ForInvocation)
- self._state._tx_set_attr(new_node, "collection", copydeep(collection))
+ object.__setattr__(new_node, COLLECTION_FIELD, collection)
self._state._tx_set_attr(new_node, "state", copydeep(state))
self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)
self._initialize_execution_node(new_node.id)
@@ -1019,6 +1024,7 @@ class _ExecutionMaterializer:
def _mark_source_node_empty(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> None:
self._state._tx_set_mapping(self._state.source_prepared_mapping, source_node_id, set())
+ self._state._reset_unexecuted_prepared(source_node_id)
self._state._mark_source_executed(source_node_id)
if isinstance(self._state.graph.get_node(source_node_id), IterateInvocation):
self._state._record_empty_iterate_stream(source_node_id, iteration_path)
diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.py
index d593a728b0..e35b370194 100644
--- a/invokeai/app/services/shared/graph_scheduler.py
+++ b/invokeai/app/services/shared/graph_scheduler.py
@@ -52,12 +52,10 @@ class _ExecutionScheduler:
self.remove_from_ready_queues(exec_node_id)
self._state._set_prepared_exec_state(exec_node_id, "skipped")
- self._state._tx_add_set(self._state.executed, exec_node_id)
+ self._state._mark_exec_node_executed(exec_node_id)
- registry = self._state._prepared_registry()
- source_node_id = registry.get_source_node_id(exec_node_id)
- prepared_nodes = registry.get_prepared_ids(source_node_id)
- if all(node_id in self._state.executed for node_id in prepared_nodes):
+ source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
+ if self._state._count_unexecuted_prepared(source_node_id) == 0:
if source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
self.mark_skipped(exec_node_id)
@@ -90,7 +88,7 @@ class _ExecutionScheduler:
def _record_completed_node(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
self._state._set_prepared_exec_state(exec_node_id, "executed")
- self._state._tx_add_set(self._state.executed, exec_node_id)
+ self._state._mark_exec_node_executed(exec_node_id)
self._state._tx_set_mapping(self._state.results, exec_node_id, output)
# Keep the generic stream ledger in sync while the materializer remains
# the compatibility authority for runtime node creation.
@@ -108,11 +106,7 @@ class _ExecutionScheduler:
def _mark_source_node_complete(self, exec_node_id: str) -> None:
registry = self._state._prepared_registry()
source_node_id = registry.get_source_node_id(exec_node_id)
- prepared_nodes = registry.get_prepared_ids(source_node_id)
- if (
- all(node_id in self._state.executed for node_id in prepared_nodes)
- and source_node_id not in self._state.executed
- ):
+ if self._state._count_unexecuted_prepared(source_node_id) == 0 and source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:
@@ -378,11 +372,10 @@ class _GenericGraphSchedulerAdapter:
return
self._remove_projected(exec_node_id)
self._state._set_prepared_exec_state(exec_node_id, "skipped")
- self._state._tx_add_set(self._state.executed, exec_node_id)
+ self._state._mark_exec_node_executed(exec_node_id)
self._scheduler.discard(exec_node_id)
source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)
- prepared_nodes = self._state._prepared_registry().get_prepared_ids(source_node_id)
- if all(node_id in self._state.executed for node_id in prepared_nodes):
+ if self._state._count_unexecuted_prepared(source_node_id) == 0:
if source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
@@ -422,12 +415,18 @@ class _GenericGraphSchedulerAdapter:
self._discard_rejected_node(exec_node_id)
def _sync_executed_state(self, excluded: Iterable[str] = ()) -> None:
+ """Synchronize externally completed plan nodes without rebuilding on every normal completion."""
excluded_ids = set(excluded)
- self._scheduler.executed.update(
+ newly_executed = {
exec_node_id
for exec_node_id in self._state.results
- if exec_node_id not in excluded_ids and exec_node_id in self._scheduler.plan.nodes
- )
+ if exec_node_id not in excluded_ids
+ and exec_node_id in self._scheduler.plan.nodes
+ and exec_node_id not in self._scheduler.executed
+ }
+ if not newly_executed:
+ return
+ self._scheduler.executed.update(newly_executed)
self._scheduler.rebuild_ready()
self._sync_indegree()
@@ -541,7 +540,7 @@ class _GenericGraphSchedulerAdapter:
def _record_completed_node(self, exec_node_id: str, output: BaseInvocationOutput) -> None:
node = self._state.execution_graph.nodes.get(exec_node_id)
self._state._set_prepared_exec_state(exec_node_id, "executed")
- self._state._tx_add_set(self._state.executed, exec_node_id)
+ self._state._mark_exec_node_executed(exec_node_id)
self._state._tx_set_mapping(self._state.results, exec_node_id, output)
if isinstance(node, ForInvocation) and node.index >= 0:
self._state._for_continuation(exec_node_id)
@@ -553,11 +552,7 @@ class _GenericGraphSchedulerAdapter:
def _mark_source_node_complete(self, exec_node_id: str) -> None:
registry = self._state._prepared_registry()
source_node_id = registry.get_source_node_id(exec_node_id)
- prepared_nodes = registry.get_prepared_ids(source_node_id)
- if (
- all(node_id in self._state.executed for node_id in prepared_nodes)
- and source_node_id not in self._state.executed
- ):
+ if self._state._count_unexecuted_prepared(source_node_id) == 0 and source_node_id not in self._state.executed:
self._state._mark_source_executed(source_node_id)
def complete(
diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.py
index 8b11e09f27..5515fc3057 100644
--- a/tests/app/services/shared/test_for_scheduler_performance.py
+++ b/tests/app/services/shared/test_for_scheduler_performance.py
@@ -47,6 +47,16 @@ def test_loop_scheduler_overhead_is_linear(loop_type: str) -> None:
assert per_node[1200] < per_node[300] * 1.5, f"{loop_type}: {per_node}"
+def test_for_loop_scheduler_overhead_is_linear_with_wall_clock() -> None:
+ """Use wall clock for the For guard so Windows' coarse process clock cannot quantize the baseline."""
+ timings: dict[int, list[float]] = {count: [] for count in (300, 1200)}
+ for _ in range(5):
+ for count in (1200, 300):
+ timings[count].append(_run_trivial_loop("for", count) / count)
+ per_node = {count: min(samples) for count, samples in timings.items()}
+ assert per_node[1200] < per_node[300] * 1.5, f"for: {per_node}"
+
+
@pytest.mark.parametrize("loop_type", ["for", "iterate"])
def test_trivial_loop_scheduler_overhead(loop_type: str) -> None:
elapsed = _run_trivial_loop(loop_type, 600)
diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.py
index cdf545e2cc..68cdcd990a 100644
--- a/tests/test_graph_execution_state.py
+++ b/tests/test_graph_execution_state.py
@@ -2303,33 +2303,82 @@ def test_graph_for_rematerialized_body_carries_returned_state():
assert for_1.state == LoopState(values={"count": 1})
-def test_graph_for_iteration_does_not_deep_copy_collection_twice():
- class DeepCopyCounter:
+def test_graph_for_iteration_does_not_copy_collection_per_iteration():
+ """Scheduling an iteration hands collection to next For node instead of copying it.
+
+ Copying collection per iteration makes loop scheduling quadratic in item count. Only per-iteration deep copy
+ left is single item handed to loop body.
+ """
+
+ class DeepCopyCounter(int):
copies = 0
+ def __new__(cls, value: int) -> "DeepCopyCounter":
+ return int.__new__(cls, value)
+
def __deepcopy__(self, memo):
type(self).copies += 1
- return self
+ return type(self)(self)
- item = DeepCopyCounter()
+ items = [DeepCopyCounter(index) for index in range(4)]
graph = Graph()
- graph.add_node(ForInvocation(id="for", collection=[item, "last"]))
+ graph.add_node(ForInvocation(id="for", collection=list(items)))
graph.add_node(ForReturnInvocation(id="return"))
graph.add_edge(create_edge("for", "item", "return", "output"))
state = GraphExecutionState(graph=add_test_loop_linkages(graph))
- for_0 = state.next()
- assert isinstance(for_0, ForInvocation)
+ node = state.next()
+ assert isinstance(node, ForInvocation)
+ first_iteration_items = list(node.collection)
DeepCopyCounter.copies = 0
- state.complete(for_0.id, for_0.invoke(Mock(InvocationContext)))
- return_0 = state.next()
- assert isinstance(return_0, ForReturnInvocation)
- state.complete(return_0.id, ForReturnInvocationOutput(output="first", state=LoopState()))
- for_1 = state.next()
- assert isinstance(for_1, ForInvocation)
- assert for_1.collection[0] is item
- assert DeepCopyCounter.copies == 2
+ scheduled_collections: list[list[Any]] = []
+ while node is not None:
+ if isinstance(node, ForInvocation):
+ scheduled_collections.append(list(node.collection))
+ state.complete(node.id, node.invoke(Mock(InvocationContext)))
+ elif isinstance(node, ForReturnInvocation):
+ state.complete(node.id, ForReturnInvocationOutput(output=node.output, state=LoopState()))
+ else:
+ state.complete(node.id, node.invoke(Mock(InvocationContext)))
+ node = state.next()
+
+ assert state.is_complete()
+ assert len(scheduled_collections) == len(items)
+ assert all(
+ all(actual is expected for actual, expected in zip(collection, first_iteration_items, strict=True))
+ for collection in scheduled_collections
+ )
+
+
+def test_graph_for_scheduling_keeps_prepared_completion_counts_consistent():
+ """Incremental pending-prepared counts must agree with full rescan at every scheduling step."""
+ graph = Graph()
+ graph.add_node(ForInvocation(id="for", collection=["alpha", "beta", "charlie"]))
+ graph.add_node(AnyTypeTestInvocation(id="body"))
+ graph.add_node(ForReturnInvocation(id="return"))
+ graph.add_edge(create_edge("for", "item", "body", "value"))
+ graph.add_edge(create_edge("body", "value", "return", "output"))
+
+ state = GraphExecutionState(graph=add_test_loop_linkages(graph))
+
+ def assert_counts_match_rescan() -> None:
+ for source_node_id, prepared_ids in state.source_prepared_mapping.items():
+ expected = sum(1 for exec_node_id in prepared_ids if exec_node_id not in state.executed)
+ assert state._count_unexecuted_prepared(source_node_id) == expected, source_node_id
+
+ node = state.next()
+ while node is not None:
+ assert_counts_match_rescan()
+ if isinstance(node, ForReturnInvocation):
+ state.complete(node.id, ForReturnInvocationOutput(output=node.output, state=LoopState()))
+ else:
+ state.complete(node.id, node.invoke(Mock(InvocationContext)))
+ assert_counts_match_rescan()
+ node = state.next()
+
+ assert state.is_complete()
+ assert_counts_match_rescan()
def test_graph_for_body_state_helper_updates_state_for_next_iteration_and_final_output():