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
refactor(execution): support four-level nested iterates
JPPhoto13b7667a54ad
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex e4b84579cb..090cd46e39 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -108,8 +108,11 @@ The exact seven-node/six-edge serial nested-`Iterate` chain extends thisbounded planner by adding one ordinary preparation/`Iterate` pair between theouter iterator and body. It owns three-component frame paths, orderedexpansion, empty outer and intermediate streams, source completion, checkpoint-rehydration, and failure parity. Four-level or deeper chains and all other-expanded, fan-in, sibling, mixed, `For`, `Collect`, and legacy shapes remain+rehydration, and failure parity. The exact nine-node/eight-edge serial chain+extends the same planner to four `Iterate` nodes and four-component frame+paths, with the same empty-stream, checkpoint, source-completion, and failure+parity guarantees. Five-level or deeper chains and all other expanded,+fan-in, sibling, mixed, `For`, `Collect`, and legacy shapes remaincompatibility-owned.Three or more body-mediated branches, fan-in with four or more direct branches,broader or deeper nested iterators, and all mixed control flow retain materializer copy expansion,diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 99eb4f2f65..aedf204e2e 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -113,9 +113,11 @@ from invokeai.app.services.shared.graph_models import (WorkflowCallStatus, # noqa: F401)from invokeai.app.services.shared.graph_nested_iterate_planner import (+ can_use_four_level_nested_iterate_sequence_planner,can_use_nested_iterate_planner,can_use_nested_iterate_sequence_planner,can_use_three_level_nested_iterate_sequence_planner,+ prepare_four_level_nested_iterate_sequences,prepare_nested_iterate_bodies,prepare_nested_iterate_sequences,prepare_three_level_nested_iterate_sequences,@@ -2395,6 +2397,11 @@ class GraphExecutionState(BaseModel):) and can_use_three_level_nested_iterate_sequence_planner(self):prepare_three_level_nested_iterate_sequences(self)return self._get_next_node()+ if isinstance(+ self._scheduler(), _GenericGraphSchedulerAdapter+ ) and can_use_four_level_nested_iterate_sequence_planner(self):+ prepare_four_level_nested_iterate_sequences(self)+ return self._get_next_node()prepared_id = self._materializer().prepare(base_graph)diff --git a/invokeai/app/services/shared/graph_nested_iterate_planner.py b/invokeai/app/services/shared/graph_nested_iterate_planner.pyindex ea27b28d70..d6b58bfa15 100644--- a/invokeai/app/services/shared/graph_nested_iterate_planner.py+++ b/invokeai/app/services/shared/graph_nested_iterate_planner.py@@ -88,6 +88,15 @@ def can_use_three_level_nested_iterate_sequence_planner(state: "GraphExecutionSt)+def can_use_four_level_nested_iterate_sequence_planner(state: "GraphExecutionState") -> bool:+ """Check the exact four-level Iterate-only chain before generic admission."""+ return (+ not state._legacy_snapshot_loaded+ and state.graph._get_supported_nested_iterate_sequence(state._get_source_graph_flat(), iterate_count=4)+ is not None+ )++def _outer_iteration_path(state: "GraphExecutionState", prepared_for_id: str) -> tuple[int, ...]:path = state._get_iteration_path(prepared_for_id)prepared_for = state.execution_graph.get_node(prepared_for_id)@@ -540,3 +549,9 @@ def prepare_three_level_nested_iterate_sequences(state: "GraphExecutionState") -"""Prepare the exact three-level nested Iterate chain."""if can_use_three_level_nested_iterate_sequence_planner(state):_prepare_nested_iterate_sequence(state, iterate_count=3)+++def prepare_four_level_nested_iterate_sequences(state: "GraphExecutionState") -> None:+ """Prepare the exact four-level nested Iterate chain."""+ if can_use_four_level_nested_iterate_sequence_planner(state):+ _prepare_nested_iterate_sequence(state, iterate_count=4)diff --git a/invokeai/app/services/shared/graph_scheduler.py b/invokeai/app/services/shared/graph_scheduler.pyindex 3e30ad423c..b6fac9cad1 100644--- a/invokeai/app/services/shared/graph_scheduler.py+++ b/invokeai/app/services/shared/graph_scheduler.py@@ -13,9 +13,11 @@ from invokeai.app.services.shared.execution_engine.scheduler import (ExecutionScheduler,)from invokeai.app.services.shared.graph_nested_iterate_planner import (+ can_use_four_level_nested_iterate_sequence_planner,can_use_nested_iterate_planner,can_use_nested_iterate_sequence_planner,can_use_three_level_nested_iterate_sequence_planner,+ prepare_four_level_nested_iterate_sequences,prepare_nested_iterate_bodies,prepare_nested_iterate_sequences,prepare_three_level_nested_iterate_sequences,@@ -623,9 +625,11 @@ class _GenericGraphSchedulerAdapter:self._remove_projected(exec_node_id)self._record_completed_node(exec_node_id, output)finalized_for_exec_node_id = self._state._apply_generic_for_continuation(exec_node_id, output)- nested_iterate_sequence = can_use_nested_iterate_sequence_planner(- self._state- ) or can_use_three_level_nested_iterate_sequence_planner(self._state)+ nested_iterate_sequence = (+ can_use_nested_iterate_sequence_planner(self._state)+ or can_use_three_level_nested_iterate_sequence_planner(self._state)+ or can_use_four_level_nested_iterate_sequence_planner(self._state)+ )if not nested_iterate_sequence:self._mark_source_node_complete(exec_node_id)# A condition may become resolvable when this node completes. Resolve it@@ -650,6 +654,8 @@ class _GenericGraphSchedulerAdapter:prepare_nested_iterate_sequences(self._state)elif can_use_three_level_nested_iterate_sequence_planner(self._state):prepare_three_level_nested_iterate_sequences(self._state)+ elif can_use_four_level_nested_iterate_sequence_planner(self._state):+ prepare_four_level_nested_iterate_sequences(self._state)else:self._try_materialize_deferred_nested_for_body(exec_node_id)if finalized_for_exec_node_id is None:diff --git a/tests/app/services/shared/test_execution_engine_differential.py b/tests/app/services/shared/test_execution_engine_differential.pyindex 68e1ae109c..84ea8c6c0f 100644--- a/tests/app/services/shared/test_execution_engine_differential.py+++ b/tests/app/services/shared/test_execution_engine_differential.py@@ -653,6 +653,38 @@ def _three_level_nested_iterate_chain_graph(*, outer_collection: list[list[list[return graph+def _four_level_nested_iterate_chain_graph(*, outer_collection: list[list[list[list[str]]]] | None = None) -> Graph:+ """Exact four-level serial nested-iterator shape."""+ graph = Graph()+ graph.add_node(+ CollectionConcatInvocation(+ id="outer_source",+ first=[[[["a", "b"], ["c"]], [["d"]]], [[["e"]]]] if outer_collection is None else outer_collection,+ )+ )+ graph.add_node(IterateInvocation(id="outer_iterate"))+ graph.add_node(CollectionConcatInvocation(id="level1_collection"))+ graph.add_node(IterateInvocation(id="level1_iterate"))+ graph.add_node(CollectionConcatInvocation(id="level2_collection"))+ graph.add_node(IterateInvocation(id="level2_iterate"))+ graph.add_node(CollectionConcatInvocation(id="level3_collection"))+ graph.add_node(IterateInvocation(id="level3_iterate"))+ graph.add_node(AnyTypeTestInvocation(id="body"))++ 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", "level1_collection", "first")+ connect("level1_collection", "collection", "level1_iterate", "collection")+ connect("level1_iterate", "item", "level2_collection", "first")+ connect("level2_collection", "collection", "level2_iterate", "collection")+ connect("level2_iterate", "item", "level3_collection", "first")+ connect("level3_collection", "collection", "level3_iterate", "collection")+ connect("level3_iterate", "item", "body", "value")+ return graph++def _direct_iterate_body_collect_graph(*, collection: list[Any] | None = None, with_after: bool = False, downstream_count: int | None = None) -> Graph:@@ -2370,6 +2402,132 @@ def test_three_level_nested_iterate_failure_matches_compatibility() -> None:assert _state_projection(generic_state) == _state_projection(compatibility_state)+def test_four_level_nested_iterate_matches_compatibility() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert generic_trace == (+ ["outer_source"]+ + ["outer_iterate"] * 2+ + ["level1_collection"] * 2+ + ["level1_iterate"] * 3+ + ["level2_collection"] * 3+ + ["level2_iterate"] * 4+ + ["level3_collection"] * 4+ + ["level3_iterate"] * 5+ + ["body"] * 5+ )+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert _direct_iterate_fan_in_stream_projection(generic_state) == _direct_iterate_fan_in_stream_projection(+ compatibility_state+ )+ assert sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ ) == [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0)]+++ ("outer_collection", "expected_body_paths"),+ [+ ([], []),+ (+ [+ [],+ [+ [+ [+ "c",+ ]+ ]+ ],+ ],+ [(1, 0, 0, 0)],+ ),+ ([[[]]], []),+ ([[[], []]], []),+ ],+ ids=["outer-empty", "mixed-empty", "deepest-empty", "all-empty"],+)+def test_four_level_nested_iterate_closes_empty_frames(+ outer_collection: list[list[list[list[str]]]], expected_body_paths: list[tuple[int, ...]]+) -> None:+ graph = _four_level_nested_iterate_chain_graph(outer_collection=outer_collection)+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run(GraphExecutionState(graph=graph))+ compatibility_trace, compatibility_state = _run(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ )++ assert generic_trace == compatibility_trace+ assert generic_state.is_complete()+ assert compatibility_state.is_complete()+ assert _state_projection(generic_state) == _state_projection(compatibility_state)+ assert (+ sorted(+ generic_state._get_iteration_path(exec_id)+ for exec_id in generic_state._prepared_registry().get_prepared_ids("body")+ )+ == expected_body_paths+ )+++def test_four_level_nested_iterate_rehydrates_without_replay() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ expected_trace, expected_state = _run(GraphExecutionState(graph=graph))+ partial_trace, partial_state = _run(GraphExecutionState(graph=graph), stop_after=12)++ resumed_trace, resumed_state = _run(load_execution_state(dump_execution_state(partial_state)))++ assert partial_trace + resumed_trace == expected_trace+ assert resumed_state.is_complete()+ assert _state_projection(resumed_state) == _state_projection(expected_state)+ assert _direct_iterate_fan_in_stream_projection(resumed_state) == _direct_iterate_fan_in_stream_projection(+ expected_state+ )+++def test_four_level_nested_iterate_failure_matches_compatibility() -> None:+ graph = _four_level_nested_iterate_chain_graph()+ with patch.object(+ graph_module._ExecutionMaterializer,+ "prepare",+ side_effect=AssertionError("four-level nested Iterate used compatibility materializer"),+ ):+ generic_trace, generic_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ fail_source_id="body",+ )+ compatibility_trace, compatibility_state = _run_graph_with_effects(+ GraphExecutionState(graph=graph),+ force_compatibility_scheduler=True,+ fail_source_id="body",+ )++ assert generic_trace == compatibility_trace+ assert generic_state.has_error() and compatibility_state.has_error()+ assert generic_state.is_complete() and compatibility_state.is_complete()+ assert generic_trace.count("body") == 1+ assert _state_projection(generic_state) == _state_projection(compatibility_state)++@pytest.mark.parametrize("values", [[1, None, 1], []], ids=["ordered-duplicates-and-none", "empty"])def test_input_driven_iterate_collect_uses_generic_stream_ownership(values: list[Any]) -> None:compatibility_state = GraphExecutionState(graph=_input_driven_iterate_body_collect_graph(values))