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
Preserve nested Iterate value scope (#9677)
Jonathan08fe73237cf4
diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.pyindex fe9a564b0f..33f5f84074 100644--- a/invokeai/app/services/shared/graph_materializer.py+++ b/invokeai/app/services/shared/graph_materializer.py@@ -62,8 +62,7 @@ class _ExecutionNodeBuilder:iteration_node_map: list[tuple[str, str]],input_edges: Optional[list[Edge]] = None,) -> Optional[tuple[int, ...]]:- parent_paths: list[tuple[int, ...]] = []- parent_iteration_axes: list[tuple[str, ...]] = []+ parent_contexts: list[tuple[tuple[int, ...], tuple[str, ...]]] = []registry = self._state._prepared_registry()input_edges_by_source: dict[str, list[Edge]] = {}for edge in input_edges or []:@@ -79,25 +78,21 @@ class _ExecutionNodeBuilder:key=lambda path: (len(path), path),)if parent_path:- parent_paths.append(parent_path)- parent_iteration_axes.append(self._get_iteration_axes(source_node_id))+ parent_contexts.append((parent_path, self._get_iteration_axes(source_node_id)))- unique_parent_paths = set(parent_paths)- paths_share_iteration_axes = len(set(parent_iteration_axes)) <= 1+ deepest_path = max((path for path, _ in parent_contexts), key=len, default=())+ deepest_axes = max((axes for _, axes in parent_contexts), key=len, default=())+ compatible_parent_contexts = all(+ deepest_path[: len(path)] == path and deepest_axes[: len(axes)] == axes for path, axes in parent_contexts+ )+ if not compatible_parent_contexts:+ return None# Materialized iteration boundaries use non-negative indexes; ordinary execution nodes use -1. Keeping this# generic allows other scheduler-managed loop nodes to reuse the same path cache.if iteration_index >= 0:- if len(unique_parent_paths) > 1 or not paths_share_iteration_axes:- return None- parent_path = next(iter(unique_parent_paths), ())- return (*parent_path, iteration_index)-- if not unique_parent_paths:- return ()- if len(unique_parent_paths) == 1 and paths_share_iteration_axes:- return next(iter(unique_parent_paths))- return None+ return (*deepest_path, iteration_index)+ return deepest_pathdef _get_iterator_iteration_count(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> int:input_collection_edge = next(iter(self._state.graph._get_input_edges(node_id, COLLECTION_FIELD)))@@ -1409,8 +1404,8 @@ class _ExecutionNodeBuilder:new_node = self._create_execution_node_copy(node, node_id, iteration_index)if new_node_iteration_path is not None:self._state._prepared_registry().set_iteration_path(new_node.id, new_node_iteration_path)- self._state._record_activation_dependencies(new_node.id)attached_edges = self._attach_execution_edges(new_node.id, new_edges)+ self._state._record_activation_dependencies(new_node.id)self._initialize_execution_node(new_node.id, attached_edges)new_nodes.append(new_node.id)diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 54ce83e2a7..ce89287c31 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -42,6 +42,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContextDatfrom tests.test_nodes import (AnyTypeTestInvocation,ErrorInvocation,+ FixedCollectionTestInvocation,MarkedAnyTypeTestInvocation,PolymorphicStringTestInvocation,UnionCollectionTestInvocation,@@ -834,6 +835,104 @@ def _nested_iterate_chain_graph(*, outer_collection: list[list[str]] | None = Noreturn graph+def _nested_iterate_add_collect_graph() -> Graph:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="outer_iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="inner_source"))+ graph.add_node(IterateInvocation(id="inner_iterate"))+ graph.add_node(AddInvocation(id="add"))+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_node(AnyTypeTestInvocation(id="sink"))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))++ connect("outer_source", "collection", "outer_iterate", "collection")+ connect("outer_iterate", "item", "inner_source", "value")+ connect("inner_source", "collection", "inner_iterate", "collection")+ connect("outer_iterate", "item", "add", "a")+ connect("inner_iterate", "item", "add", "b")+ connect("add", "value", "collect", "item")+ connect("collect", "collection", "sink", "value")+ return graph+++def _add_unrelated_if(graph: Graph) -> Graph:+ graph.add_node(BooleanInvocation(id="unrelated_condition", value=True))+ graph.add_node(AddInvocation(id="unrelated_true", a=1, b=2))+ graph.add_node(AddInvocation(id="unrelated_false", a=3, b=4))+ graph.add_node(IfInvocation(id="unrelated_if"))+ graph.add_node(AddInvocation(id="unrelated_sink", b=1))+ graph.add_edge(create_edge("unrelated_condition", "value", "unrelated_if", "condition"))+ graph.add_edge(create_edge("unrelated_true", "value", "unrelated_if", "true_input"))+ graph.add_edge(create_edge("unrelated_false", "value", "unrelated_if", "false_input"))+ graph.add_edge(create_edge("unrelated_if", "value", "unrelated_sink", "a"))+ return graph+++def _iterate_if_collect_inner_iterate_graph() -> Graph:+ """Build a validated nested Iterate graph with If output buffered through Collect.collection."""+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="outer_iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="true_source"))+ graph.add_node(FixedCollectionTestInvocation(id="false_source"))+ graph.add_node(IfInvocation(id="select_inner"))+ graph.add_node(CollectInvocation(id="selected_collection"))+ graph.add_node(IterateInvocation(id="inner_iterate"))+ graph.add_node(AddInvocation(id="add"))+ graph.add_node(CollectInvocation(id="results"))+ graph.add_node(AnyTypeTestInvocation(id="sink"))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))++ connect("outer_source", "collection", "outer_iterate", "collection")+ connect("outer_iterate", "item", "true_source", "value")+ connect("outer_iterate", "item", "false_source", "value")+ connect("true_source", "condition", "select_inner", "condition")+ connect("true_source", "collection", "select_inner", "true_input")+ connect("false_source", "collection", "select_inner", "false_input")+ connect("select_inner", "value", "selected_collection", "collection")+ connect("selected_collection", "collection", "inner_iterate", "collection")+ connect("outer_iterate", "item", "add", "a")+ connect("inner_iterate", "item", "add", "b")+ connect("add", "value", "results", "item")+ connect("results", "collection", "sink", "value")+ return graph+++def _chained_sibling_iterates_with_unrelated_if_graph() -> Graph:+ graph = Graph()+ graph.add_node(CollectionConcatInvocation(id="outer_source", first=[1, 2]))+ graph.add_node(IterateInvocation(id="outer_iterate"))+ graph.add_node(FixedCollectionTestInvocation(id="first_inner_source"))+ graph.add_node(FixedCollectionTestInvocation(id="second_inner_source"))+ graph.add_node(IterateInvocation(id="first_inner_iterate"))+ graph.add_node(IterateInvocation(id="second_inner_iterate"))+ graph.add_node(AddInvocation(id="first_add"))+ graph.add_node(AddInvocation(id="second_add"))+ graph.add_node(CollectInvocation(id="results"))+ graph.add_node(AnyTypeTestInvocation(id="sink"))++ def connect(source: str, source_field: str, destination: str, destination_field: str) -> None:+ graph.add_edge(create_edge(source, source_field, destination, destination_field))++ connect("outer_source", "collection", "outer_iterate", "collection")+ connect("outer_iterate", "item", "first_inner_source", "value")+ connect("outer_iterate", "item", "second_inner_source", "value")+ connect("first_inner_source", "collection", "first_inner_iterate", "collection")+ connect("second_inner_source", "collection", "second_inner_iterate", "collection")+ connect("outer_iterate", "item", "first_add", "a")+ connect("first_inner_iterate", "item", "first_add", "b")+ connect("first_add", "value", "second_add", "a")+ connect("second_inner_iterate", "item", "second_add", "b")+ connect("second_add", "value", "results", "item")+ connect("results", "collection", "sink", "value")+ return _add_unrelated_if(graph)++def _three_level_nested_iterate_chain_graph(*, outer_collection: list[list[list[str]]] | None = None) -> Graph:"""Exact three-level serial nested-iterator shape."""graph = Graph()@@ -3119,6 +3218,64 @@ def test_nested_iterate_chain_matches_compatibility() -> None:assert _state_projection(generic_state) == _state_projection(compatibility_state)[email protected]("force_compatibility_scheduler", [False, True])+def test_nested_iterate_keeps_values_in_outer_frame_with_unrelated_if(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _add_unrelated_if(_nested_iterate_add_collect_graph())+ graph.validate_self()++ trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)++ assert trace.count("sink") == 2+ sinks_by_outer_path = {+ state._get_iteration_path(exec_id): state.results[exec_id].value+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ }+ assert sinks_by_outer_path == {(0,): [1, 2], (1,): [2, 3]}+ assert state.is_complete()++[email protected]("force_compatibility_scheduler", [False, True])+def test_if_collect_collection_inner_iterate_keeps_values_in_outer_frame(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _iterate_if_collect_inner_iterate_graph()+ graph.validate_self()++ trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)++ assert trace.count("sink") == 2+ sinks_by_outer_path = {+ state._get_iteration_path(exec_id): state.results[exec_id].value+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ }+ assert sinks_by_outer_path == {(0,): [1, 2], (1,): [2, 3]}+ assert state.is_complete()++[email protected]("force_compatibility_scheduler", [False, True])+def test_chained_sibling_iterates_keep_each_outer_and_inner_frame(+ force_compatibility_scheduler: bool,+) -> None:+ graph = _chained_sibling_iterates_with_unrelated_if_graph()+ graph.validate_self()++ trace, state = _run(GraphExecutionState(graph=graph), force_compatibility_scheduler=force_compatibility_scheduler)++ sinks_by_iteration_path = {+ state._get_iteration_path(exec_id): state.results[exec_id].value+ for exec_id in state._prepared_registry().get_prepared_ids("sink")+ }+ assert sinks_by_iteration_path == {+ (0, 0): [1, 2],+ (0, 1): [2, 3],+ (1, 0): [2, 3],+ (1, 1): [3, 4],+ }+ assert state.is_complete()++def test_nested_iterate_chain_closes_empty_inner_frame() -> None:graph = _nested_iterate_chain_graph(outer_collection=[[], ["c"]])with patch.object(diff --git a/tests/test_nodes.py b/tests/test_nodes.pyindex 7b7d869465..6368e416c1 100644--- a/tests/test_nodes.py+++ b/tests/test_nodes.py@@ -97,6 +97,20 @@ class AnyTypeTestInvocation(BaseInvocation):return AnyTypeTestInvocationOutput(value=self.value)+@invocation_output("test_fixed_collection_output")+class FixedCollectionTestInvocationOutput(BaseInvocationOutput):+ condition: bool = OutputField()+ collection: list[Any] = OutputField()+++@invocation("test_fixed_collection", version="1.0.0")+class FixedCollectionTestInvocation(BaseInvocation):+ value: Any = InputField()++ def invoke(self, context: InvocationContext) -> FixedCollectionTestInvocationOutput:+ return FixedCollectionTestInvocationOutput(condition=bool(self.value), collection=[0, 1])++@invocation("test_marked_any", version="1.0.0")class MarkedAnyTypeTestInvocation(AnyTypeTestInvocation):marker: str = InputField(default="")