if isinstance(node, fx.Node)
):
return None, graph_module
flat_nodes: list = []
def build(node: fx.Node) -> tuple:
"""Emit ``getitem`` leaves for a nested value, else record the leaf."""
val = node.meta.get("val")
if isinstance(val, (tuple, list)) and val:
children = []
for index, element in enumerate(val):
sub = graph.call_function(operator.getitem, (node, index))
sub.meta["val"] = element
children.append(build(sub))
kind = "tuple" if isinstance(val, tuple) else "list"
return kind, tuple(children)
flat_nodes.append(node)
return "leaf", len(flat_nodes) - 1
with graph.inserting_before(output):
spec = tuple(build(node) for node in returned)
output.args = (tuple(flat_nodes),)
graph.lint()
graph_module.recompile()
return spec, graph_module
def _rebuild_nested_output(spec: tuple, flat: Sequence[Any]) -> list:
"""Rebuild the original output structure from ``spec`` and flat leaves."""
leaves = iter(flat)
rebuilt = []
for kind, payload in spec:
if kind == "leaf":
rebuilt.append(next(leaves))
else:
children = _rebuild_nested_output(payload, leaves)
rebuilt.append(tuple(children) if kind == "tuple" else children)
return rebuilt
class _NestedOutputWrapper(nn.Module):
"""Thin wrapper restoring a compiled graph's nested output structure."""