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.

refactor(execution): plan two Iterate downstream consumers

JPPhotobb1287e4e460
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.py
index 145bc7c65a..d41f61b7ef 100644
--- a/invokeai/app/services/shared/graph.py
+++ b/invokeai/app/services/shared/graph.py
@@ -4401,7 +4401,8 @@ class Graph(BaseModel):
# TODO: Cache this?
g = nx.DiGraph()
g.add_nodes_from(list(self.nodes.keys()))
- g.add_edges_from({(e.source.node_id, e.destination.node_id) for e in self.edges if e.type == "default"})
+ edges = dict.fromkeys((e.source.node_id, e.destination.node_id) for e in self.edges if e.type == "default")
+ g.add_edges_from(edges)
return g
def nx_graph_flat(self, nx_graph: Optional["nx.DiGraph"] = None) -> "nx.DiGraph":
@@ -4411,8 +4412,8 @@ class Graph(BaseModel):
# Add all nodes from this graph except graph/iteration nodes
g.add_nodes_from([n.id for n in self.nodes.values()])
- unique_edges = {(e.source.node_id, e.destination.node_id) for e in self.edges if e.type == "default"}
- g.add_edges_from(unique_edges)
+ edges = dict.fromkeys((e.source.node_id, e.destination.node_id) for e in self.edges if e.type == "default")
+ g.add_edges_from(edges)
return g
@@ -6679,12 +6680,12 @@ class GraphExecutionState(BaseModel):
return next_node
- def _get_direct_iterate_collect_nodes(self) -> Optional[tuple[str, str, str, str, str | None]]:
- """Return the direct planner nodes, including one optional ordinary downstream consumer."""
+ def _get_direct_iterate_collect_nodes(self) -> Optional[tuple[str, str, str, str, tuple[str, ...]]]:
+ """Return direct planner nodes, including up to two ordinary downstream consumers."""
if (
self._legacy_snapshot_loaded
- or len(self.graph.nodes) not in {4, 5}
+ or len(self.graph.nodes) not in {4, 5, 6}
or len(self.graph.edges) != len(self.graph.nodes) - 1
):
return None
@@ -6739,23 +6740,22 @@ class GraphExecutionState(BaseModel):
if self.graph._get_input_edges(collector_id) != [item_edge]:
return None
- downstream_id: str | None = None
downstream_edges = self.graph._get_output_edges(collector_id, COLLECTION_FIELD)
- if len(self.graph.nodes) == 5:
- if len(downstream_edges) != 1:
- return None
- downstream_id = downstream_edges[0].destination.node_id
+ if len(downstream_edges) != len(self.graph.nodes) - 4:
+ return None
+ downstream_ids: list[str] = []
+ for downstream_edge in downstream_edges:
+ downstream_id = downstream_edge.destination.node_id
downstream = self.graph.get_node(downstream_id)
if downstream_id in {source_id, iterator_id, body_id, collector_id} or isinstance(
downstream, (ForInvocation, ForReturnInvocation, IfInvocation, IterateInvocation, CollectInvocation)
):
return None
- if self.graph._get_input_edges(downstream_id) != downstream_edges:
+ if self.graph._get_input_edges(downstream_id) != [downstream_edge]:
return None
- elif downstream_edges:
- return None
+ downstream_ids.append(downstream_id)
- return source_id, iterator_id, body_id, collector_id, downstream_id
+ return source_id, iterator_id, body_id, collector_id, tuple(downstream_ids)
def _can_use_direct_iterate_collect_planner(self) -> bool:
"""Use fresh planner ownership only for the exact direct stream shape."""
@@ -6837,7 +6837,7 @@ class GraphExecutionState(BaseModel):
node_ids = self._get_direct_iterate_collect_nodes()
if node_ids is None:
return
- source_id, iterator_id, body_id, collector_id, downstream_id = node_ids
+ source_id, iterator_id, body_id, collector_id, downstream_ids = node_ids
if source_id not in self.source_prepared_mapping:
source_node = self._create_direct_execution_node_copy(source_id)
@@ -6898,7 +6898,7 @@ class GraphExecutionState(BaseModel):
attached_collector_edges = self._attach_direct_execution_edges(collector_node.id, collector_edges)
self._initialize_direct_execution_node(collector_node.id, attached_collector_edges)
- if downstream_id is not None:
+ for downstream_id in downstream_ids:
downstream_node = self._create_direct_execution_node_copy(downstream_id)
downstream_edge = self.graph._get_input_edges(downstream_id)[0]
attached_downstream_edges = self._attach_direct_execution_edges(
diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.py
index d9d2deedad..ca2cdde8f1 100644
--- a/tests/app/services/shared/test_execution_engine_differential.py
+++ b/tests/app/services/shared/test_execution_engine_differential.py
@@ -248,7 +248,9 @@ def _nested_for_iterate_collect_graph(*, outer_collection: list[list[str]] | Non
return graph
-def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, with_after: bool = False) -> Graph:
+def _direct_iterate_body_collect_graph(
+ *, collection: list[Any] | None = None, with_after: bool = False, downstream_count: int | None = None
+) -> Graph:
graph = Graph()
graph.add_node(CollectionConcatInvocation(id="source", first=[] if collection is None else collection))
graph.add_node(IterateInvocation(id="iterate"))
@@ -272,12 +274,15 @@ def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, w
destination=EdgeConnection(node_id="collect", field="item"),
)
)
- if with_after:
- graph.add_node(AnyTypeTestInvocation(id="after"))
+ if downstream_count is None:
+ downstream_count = 1 if with_after else 0
+ for downstream_index in range(downstream_count):
+ downstream_id = "after" if downstream_count == 1 else f"after_{downstream_index + 1}"
+ graph.add_node(AnyTypeTestInvocation(id=downstream_id))
graph.add_edge(
Edge(
source=EdgeConnection(node_id="collect", field="collection"),
- destination=EdgeConnection(node_id="after", field="value"),
+ destination=EdgeConnection(node_id=downstream_id, field="value"),
)
)
return graph
@@ -1474,6 +1479,128 @@ def test_direct_iterate_body_collect_with_downstream_consumer_uses_private_plann
group_collector_inputs.assert_not_called()
+def test_direct_iterate_body_collect_two_downstream_consumers_admits_exact_shape() -> None:
+ state = GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))
+
+ assert len(state.graph.nodes) == 6
+ assert len(state.graph.edges) == 5
+ assert state._get_direct_iterate_collect_nodes() == (
+ "source",
+ "iterate",
+ "body",
+ "collect",
+ ("after_1", "after_2"),
+ )
+ assert state._can_use_direct_iterate_collect_planner()
+
+ assert not GraphExecutionState(
+ graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=3)
+ )._can_use_direct_iterate_collect_planner()
+
+
+def test_direct_iterate_body_collect_two_downstream_consumers_uses_private_planner() -> None:
+ with (
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "prepare",
+ side_effect=AssertionError("two direct downstream consumers must not use materializer.prepare"),
+ ) as prepare,
+ patch.object(
+ graph_module._ExecutionMaterializer,
+ "_get_collect_iteration_mapping_groups",
+ side_effect=AssertionError("two direct downstream consumers must not group collector inputs"),
+ ) as group_collector_inputs,
+ ):
+ trace, state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=["value"], downstream_count=2))
+ )
+
+ assert trace == ["source", "iterate", "body", "collect", "after_1", "after_2"]
+ assert _source_output(state, "after_1").value == ["value"]
+ assert _source_output(state, "after_2").value == ["value"]
+ assert state.is_complete()
+ prepare.assert_not_called()
+ group_collector_inputs.assert_not_called()
+
+
[email protected]("collection", [["first", None, "last"], []], ids=["ordered-none", "empty"])
+def test_direct_iterate_body_collect_two_downstream_consumers_matches_compatibility(
+ collection: list[Any],
+) -> None:
+ generic_trace, generic_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2))
+ )
+ compatibility_trace, compatibility_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),
+ force_compatibility_scheduler=True,
+ )
+
+ expected_trace = ["source"] + ["iterate"] * len(collection) + ["body"] * len(collection)
+ expected_trace += ["collect", "after_1", "after_2"]
+ assert generic_trace == expected_trace
+ assert generic_trace[:-2] == compatibility_trace[:-2]
+ assert sorted(generic_trace[-2:]) == sorted(compatibility_trace[-2:]) == ["after_1", "after_2"]
+ for state in (generic_state, compatibility_state):
+ assert _source_output(state, "collect").collection == collection
+ assert _source_output(state, "after_1").value == collection
+ assert _source_output(state, "after_2").value == collection
+ assert state.is_complete()
+
+
+def test_direct_iterate_body_collect_two_downstream_consumers_rolls_back_partial_expansion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ state = GraphExecutionState(
+ graph=_direct_iterate_body_collect_graph(collection=["first", "last"], downstream_count=2)
+ )
+ source_node = state.next()
+ assert source_node is not None
+ state.complete(source_node.id, source_node.invoke(Mock()))
+
+ original_create = GraphExecutionState._create_direct_execution_node_copy
+
+ def fail_at_second_downstream(self: GraphExecutionState, source_node_id: str, *args: Any, **kwargs: Any):
+ if source_node_id == "after_2":
+ raise RuntimeError("injected second downstream planner failure")
+ return original_create(self, source_node_id, *args, **kwargs)
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", fail_at_second_downstream)
+ with pytest.raises(RuntimeError, match="injected second downstream planner failure"):
+ state.next()
+
+ assert set(state.source_prepared_mapping) == {"source"}
+ assert len(state.execution_graph.nodes) == 1
+ assert not state.execution_graph.edges
+
+ monkeypatch.setattr(GraphExecutionState, "_create_direct_execution_node_copy", original_create)
+ trace, state = _run_graph(state)
+
+ assert trace == ["iterate", "iterate", "body", "body", "collect", "after_1", "after_2"]
+ assert _source_output(state, "after_1").value == ["first", "last"]
+ assert _source_output(state, "after_2").value == ["first", "last"]
+ assert state.is_complete()
+
+
+def test_direct_iterate_body_collect_two_downstream_consumers_checkpoint_rehydrates() -> None:
+ collection = ["first", None, "last"]
+ expected_trace, expected_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2))
+ )
+ partial_trace, partial_state = _run_graph(
+ GraphExecutionState(graph=_direct_iterate_body_collect_graph(collection=collection, downstream_count=2)),
+ stop_after=3,
+ )
+
+ resumed_trace, resumed_state = _run_graph(load_execution_state(dump_execution_state(partial_state)))
+
+ assert partial_trace + resumed_trace == expected_trace
+ assert _source_output(resumed_state, "collect").collection == collection
+ assert _source_output(resumed_state, "after_1").value == collection
+ assert _source_output(resumed_state, "after_2").value == collection
+ assert resumed_state.is_complete()
+ assert _state_projection(resumed_state) == _state_projection(expected_state)
+
+
def test_direct_iterate_body_collect_with_downstream_consumer_matches_forced_compatibility_scheduler() -> None:
generic_trace, generic_state = _run_graph(
GraphExecutionState(