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): extract If activation controller
JPPhotod0003a7801a0
diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex 6bce607f73..50591216d7 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -84,6 +84,7 @@ from invokeai.app.services.shared.execution_engine.scheduler import (ExecutionPlan,ExecutionScheduler,)+from invokeai.app.services.shared.graph_if_activation import _IfActivationControllerfrom invokeai.app.services.shared.graph_models import (Edge, # noqa: F401EdgeConnection, # noqa: F401@@ -164,131 +165,6 @@ class _BodyIterateCollectFanIn:collector_id: str-class _IfActivationController:- """Own activation admission for concrete execution nodes.-- Unlike the legacy compiler, this controller does not lower or cache a- branch projection. It answers one readiness question for one prepared- execution node from the current source graph and durable execution frame.- """-- def __init__(self, state: "GraphExecutionState") -> None:- self._state = state- self._branch_sources_cache: dict[tuple[str, str], frozenset[str]] = {}-- def _branch_sources(self, if_node_id: str, branch_field: str, source_graph: "nx.DiGraph") -> set[str]:- cache_key = (if_node_id, branch_field)- cached = self._branch_sources_cache.get(cache_key)- if cached is not None:- return set(cached)-- direct_sources = {edge.source.node_id for edge in self._state.graph._get_input_edges(if_node_id, branch_field)}- branch_sources = set(direct_sources)- for source_node_id in direct_sources:- branch_sources.update(nx.ancestors(source_graph, source_node_id))-- changed = True- while changed:- changed = False- for source_node_id in tuple(branch_sources):- if all(- edge.destination.node_id in branch_sources- or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)- for edge in self._state.graph._get_output_edges(source_node_id)- ):- continue- branch_sources.remove(source_node_id)- changed = True- self._branch_sources_cache[cache_key] = frozenset(branch_sources)- return branch_sources-- def get_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:- """Return activation requirements for one concrete prepared node."""-- source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)- if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):- return ()- return self.get_source_dependencies(source_node_id, self._state._get_iteration_path(exec_node_id))-- def get_source_dependencies(- self, source_node_id: str, iteration_path: tuple[int, ...] = ()- ) -> tuple[ActivationDependency, ...]:- """Return branch requirements before a source node is materialized."""-- if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):- return ()- source_graph = self._state._get_source_graph_flat()- dependencies: list[ActivationDependency] = []- for source_if_id, source_if_node in self._state.graph.nodes.items():- if not isinstance(source_if_node, IfInvocation):- continue-- matching_fields = tuple(- branch_field- for branch_field in ("true_input", "false_input")- if source_node_id in self._branch_sources(source_if_id, branch_field, source_graph)- )- if len(matching_fields) != 1:- continue- dependencies.append(- ActivationDependency(- owner_id=source_if_id,- branch=matching_fields[0],- frame=iteration_path,- )- )- return tuple(dependencies)-- def is_source_admitted(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- dependencies = self.get_source_dependencies(source_node_id, iteration_path)- return bool(- not dependencies- or all(self._state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)- )-- def is_source_rejected(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- return any(- self._state._is_activation_dependency_rejected(dependency)- for dependency in self.get_source_dependencies(source_node_id, iteration_path)- )-- def is_source_inactive(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:- """Return whether a source belongs exclusively to a rejected If branch."""-- if iteration_path:- return self.is_source_rejected(source_node_id, iteration_path)-- source_graph = self._state._get_source_graph_flat()- relevant_if_ids = {- if_node_id- for if_node_id, if_node in self._state.graph.nodes.items()- if isinstance(if_node, IfInvocation)- and any(- source_node_id in self._branch_sources(if_node_id, branch_field, source_graph)- for branch_field in ("true_input", "false_input")- )- }- if not relevant_if_ids:- return False-- frames: set[tuple[int, ...]] = set()- for if_node_id in relevant_if_ids:- frames.update(- self._state._get_iteration_path(exec_node_id)- for exec_node_id in self._state._prepared_registry().get_prepared_ids(if_node_id)- )- if not frames:- return False-- for frame in frames:- dependencies = self.get_source_dependencies(source_node_id, frame)- if dependencies and not any(- self._state._is_activation_dependency_rejected(dependency) for dependency in dependencies- ):- return False- return True--class _ExecutionMaterializer:"""Expands source-graph nodes into concrete execution-graph nodes for the current runtime state.diff --git a/invokeai/app/services/shared/graph_if_activation.py b/invokeai/app/services/shared/graph_if_activation.pynew file mode 100644index 0000000000..d9e08c32e2--- /dev/null+++ b/invokeai/app/services/shared/graph_if_activation.py@@ -0,0 +1,135 @@+# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)++from typing import TYPE_CHECKING++from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.services.shared.execution_engine.scheduler import ActivationDependency+from invokeai.app.services.shared.graph_validation import nx++if TYPE_CHECKING:+ from invokeai.app.services.shared.graph import GraphExecutionState+++class _IfActivationController:+ """Own activation admission for concrete execution nodes.++ Unlike the legacy compiler, this controller does not lower or cache a+ branch projection. It answers one readiness question for one prepared+ execution node from the current source graph and durable execution frame.+ """++ def __init__(self, state: "GraphExecutionState") -> None:+ self._state = state+ self._branch_sources_cache: dict[tuple[str, str], frozenset[str]] = {}++ def _branch_sources(self, if_node_id: str, branch_field: str, source_graph: "nx.DiGraph") -> set[str]:+ cache_key = (if_node_id, branch_field)+ cached = self._branch_sources_cache.get(cache_key)+ if cached is not None:+ return set(cached)++ direct_sources = {edge.source.node_id for edge in self._state.graph._get_input_edges(if_node_id, branch_field)}+ branch_sources = set(direct_sources)+ for source_node_id in direct_sources:+ branch_sources.update(nx.ancestors(source_graph, source_node_id))++ changed = True+ while changed:+ changed = False+ for source_node_id in tuple(branch_sources):+ if all(+ edge.destination.node_id in branch_sources+ or (edge.destination.node_id == if_node_id and edge.destination.field == branch_field)+ for edge in self._state.graph._get_output_edges(source_node_id)+ ):+ continue+ branch_sources.remove(source_node_id)+ changed = True+ self._branch_sources_cache[cache_key] = frozenset(branch_sources)+ return branch_sources++ def get_dependencies(self, exec_node_id: str) -> tuple[ActivationDependency, ...]:+ """Return activation requirements for one concrete prepared node."""++ source_node_id = self._state._prepared_registry().get_source_node_id(exec_node_id)+ if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):+ return ()+ return self.get_source_dependencies(source_node_id, self._state._get_iteration_path(exec_node_id))++ def get_source_dependencies(+ self, source_node_id: str, iteration_path: tuple[int, ...] = ()+ ) -> tuple[ActivationDependency, ...]:+ """Return branch requirements before a source node is materialized."""++ if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):+ return ()+ source_graph = self._state._get_source_graph_flat()+ dependencies: list[ActivationDependency] = []+ for source_if_id, source_if_node in self._state.graph.nodes.items():+ if not isinstance(source_if_node, IfInvocation):+ continue++ matching_fields = tuple(+ branch_field+ for branch_field in ("true_input", "false_input")+ if source_node_id in self._branch_sources(source_if_id, branch_field, source_graph)+ )+ if len(matching_fields) != 1:+ continue+ dependencies.append(+ ActivationDependency(+ owner_id=source_if_id,+ branch=matching_fields[0],+ frame=iteration_path,+ )+ )+ return tuple(dependencies)++ def is_source_admitted(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:+ dependencies = self.get_source_dependencies(source_node_id, iteration_path)+ return bool(+ not dependencies+ or all(self._state._is_activation_dependency_satisfied(dependency) for dependency in dependencies)+ )++ def is_source_rejected(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:+ return any(+ self._state._is_activation_dependency_rejected(dependency)+ for dependency in self.get_source_dependencies(source_node_id, iteration_path)+ )++ def is_source_inactive(self, source_node_id: str, iteration_path: tuple[int, ...] = ()) -> bool:+ """Return whether a source belongs exclusively to a rejected If branch."""++ if iteration_path:+ return self.is_source_rejected(source_node_id, iteration_path)++ source_graph = self._state._get_source_graph_flat()+ relevant_if_ids = {+ if_node_id+ for if_node_id, if_node in self._state.graph.nodes.items()+ if isinstance(if_node, IfInvocation)+ and any(+ source_node_id in self._branch_sources(if_node_id, branch_field, source_graph)+ for branch_field in ("true_input", "false_input")+ )+ }+ if not relevant_if_ids:+ return False++ frames: set[tuple[int, ...]] = set()+ for if_node_id in relevant_if_ids:+ frames.update(+ self._state._get_iteration_path(exec_node_id)+ for exec_node_id in self._state._prepared_registry().get_prepared_ids(if_node_id)+ )+ if not frames:+ return False++ for frame in frames:+ dependencies = self.get_source_dependencies(source_node_id, frame)+ if dependencies and not any(+ self._state._is_activation_dependency_rejected(dependency) for dependency in dependencies+ ):+ return False+ return Truediff --git a/tests/app/services/shared/test_graph_if_activation.py b/tests/app/services/shared/test_graph_if_activation.pynew file mode 100644index 0000000000..a496eb6592--- /dev/null+++ b/tests/app/services/shared/test_graph_if_activation.py@@ -0,0 +1,150 @@+from __future__ import annotations++import subprocess+import sys+import textwrap+from types import SimpleNamespace+from typing import Any++import pytest++from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.services.shared import graph as graph_module+from invokeai.app.services.shared.execution_engine import ActivationDependency+from invokeai.app.services.shared.graph_if_activation import _IfActivationController+++def _edge(source: str, destination: str, field: str) -> Any:+ return SimpleNamespace(+ source=SimpleNamespace(node_id=source),+ destination=SimpleNamespace(node_id=destination, field=field),+ )+++class _Graph:+ def __init__(self) -> None:+ self.nodes = {+ "if": IfInvocation(id="if"),+ "true": object(),+ "false": object(),+ "outside": object(),+ }+ self._input_edges = {+ ("if", "true_input"): [_edge("true", "if", "true_input")],+ ("if", "false_input"): [_edge("false", "if", "false_input")],+ }+ self._output_edges = {+ "true": self._input_edges[("if", "true_input")],+ "false": self._input_edges[("if", "false_input")],+ "outside": [],+ }++ def _get_input_edges(self, node_id: str, field: str) -> list[Any]:+ return self._input_edges.get((node_id, field), [])++ def _get_output_edges(self, node_id: str) -> list[Any]:+ return self._output_edges.get(node_id, [])+++class _Registry:+ def get_source_node_id(self, exec_node_id: str) -> str:+ return exec_node_id++ def get_prepared_ids(self, source_node_id: str) -> list[str]:+ return [source_node_id] if source_node_id == "if" else []+++class _State:+ def __init__(self) -> None:+ self.graph = _Graph()+ self.admitted: set[ActivationDependency] = set()+ self.rejected: set[ActivationDependency] = set()++ def _prepared_registry(self) -> _Registry:+ return _Registry()++ def _get_iteration_path(self, _: str) -> tuple[int, ...]:+ return ()++ def _get_source_graph_flat(self) -> object:+ return object()++ def _is_activation_dependency_satisfied(self, dependency: ActivationDependency) -> bool:+ return dependency in self.admitted++ def _is_activation_dependency_rejected(self, dependency: ActivationDependency) -> bool:+ return dependency in self.rejected+++def test_standalone_import_does_not_import_graph() -> None:+ script = """+ import builtins+ import sys++ real_import = builtins.__import__++ def blocked_import(name, globals=None, locals=None, fromlist=(), level=0):+ if name == "invokeai.app.services.shared.graph" or name.startswith("invokeai.app.services.shared.graph."):+ raise ModuleNotFoundError("graph import blocked")+ return real_import(name, globals, locals, fromlist, level)++ builtins.__import__ = blocked_import+ import invokeai.app.services.shared.graph_if_activation++ assert "invokeai.app.services.shared.graph" not in sys.modules+ """+ result = subprocess.run(+ [sys.executable, "-c", textwrap.dedent(script)],+ capture_output=True,+ text=True,+ timeout=300,+ check=False,+ )+ assert result.returncode == 0, result.stderr+++def test_graph_reexports_controller_class() -> None:+ assert graph_module._IfActivationController is _IfActivationController+++def test_graph_nx_patch_seam_and_branch_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []++ class _NetworkX:+ def ancestors(self, _graph: object, node_id: str) -> set[str]:+ calls.append(node_id)+ return set()++ monkeypatch.setattr(graph_module, "nx", _NetworkX())+ controller = _IfActivationController(_State())++ assert controller._branch_sources("if", "true_input", object()) == {"true"}+ assert controller._branch_sources("if", "true_input", object()) == {"true"}+ assert calls == ["true"]+++def test_controller_dependencies_admission_rejection_and_inactive(monkeypatch: pytest.MonkeyPatch) -> None:+ class _NetworkX:+ def ancestors(self, _graph: object, _node_id: str) -> set[str]:+ return set()++ monkeypatch.setattr(graph_module, "nx", _NetworkX())+ state = _State()+ controller = _IfActivationController(state)+ true_dependency = ActivationDependency(owner_id="if", branch="true_input", frame=())+ false_dependency = ActivationDependency(owner_id="if", branch="false_input", frame=())++ assert controller.get_source_dependencies("true") == (true_dependency,)+ assert controller.get_source_dependencies("false") == (false_dependency,)+ assert controller.get_source_dependencies("outside") == ()+ assert not controller.is_source_admitted("true")+ assert not controller.is_source_rejected("true")+ assert not controller.is_source_inactive("true")++ state.admitted.add(true_dependency)+ assert controller.is_source_admitted("true")++ state.rejected.add(true_dependency)+ assert controller.is_source_rejected("true")+ state.rejected.add(ActivationDependency(owner_id="if", branch="true_input", frame=(1,)))+ assert controller.is_source_inactive("true", (1,))