Skip to content

Commit e773a95

Browse files
authored
GraphBuilder: hoist placeholders to the front in get_graph_module
Differential Revision: D110269459 Pull Request resolved: #20656
1 parent e17700a commit e773a95

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

backends/test/graph_builder.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@
2323
from torch.utils import _pytree as pytree
2424

2525

26+
def _hoist_placeholders_to_front(graph: torch.fx.Graph) -> None:
27+
"""Move placeholders ahead of the graph body, preserving their relative order."""
28+
body_start: Optional[torch.fx.Node] = None
29+
for node in list(graph.nodes):
30+
if node.op != "placeholder":
31+
if body_start is None:
32+
body_start = node
33+
elif body_start is not None:
34+
body_start.prepend(node)
35+
36+
2637
class GraphBuilder(ExportPass):
2738
"""Utility class for creating a graph module with user-specified ops.
2839
@@ -76,6 +87,11 @@ def output(self, results: list[ProxyValue]) -> ProxyValue:
7687
return super().output(results, NodeMetadata({}))
7788

7889
def get_graph_module(self) -> torch.fx.GraphModule:
90+
# Callers may create placeholders at any point during building; FX requires
91+
# them before all other nodes, so normalize before handing back the module.
92+
# (Nodes are created at the tracer's cursor, so a placeholder made after an
93+
# op would otherwise sit after it and break lint / later passes.)
94+
_hoist_placeholders_to_front(self.tracer.graph)
7995
return torch.fx.GraphModule(self.tracer.root, self.tracer.graph)
8096

8197
def call_operator(

0 commit comments

Comments
 (0)