torch.fx¶
Overview¶
This feature is experimental and its stability is not currently guaranteed. Proceed at your own risk
FX is a toolkit for capturing and transforming functional PyTorch programs. It
consists of GraphModule and a corresponding intermediate representation (IR). When GraphModule is constructed
with an nn.Module
instance as its argument, GraphModule will trace through the computation of that Module’s
forward
method symbolically and record those operations in the FX intermediate representation.
import torch
import torch.fx
class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.param = torch.nn.Parameter(torch.rand(3, 4))
self.linear = torch.nn.Linear(4, 5)
def forward(self, x):
return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3)
m = MyModule()
gm = torch.fx.symbolic_trace(m)
The Intermediate Representation centers around a 5-opcode format:
print(gm.graph)
graph(x):
%linear_weight : [#users=1] = self.linear.weight
%add_1 : [#users=1] = call_function[target=<built-in function add>](args = (%x, %linear_weight), kwargs = {})
%linear_1 : [#users=1] = call_module[target=linear](args = (%add_1,), kwargs = {})
%relu_1 : [#users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {})
%sum_1 : [#users=1] = call_function[target=<built-in method sum of type object at 0x7ff2da9dc300>](args = (%relu_1,), kwargs = {dim: -1}) # noqa: B950
%topk_1 : [#users=1] = call_function[target=<built-in method topk of type object at 0x7ff2da9dc300>](args = (%sum_1, 3), kwargs = {}) # noqa: B950
return topk_1
The Node semantics are as follows:
placeholder
represents a function input. Thename
attribute specifies the name this value will take on.target
is similarly the name of the argument.args
holds either: 1) nothing, or 2) a single argument denoting the default parameter of the function input.kwargs
is don’t-care. Placeholders correspond to the function parameters (e.g.x
) in the graph printout.get_attr
retrieves a parameter from the module hierarchy.name
is similarly the name the result of the fetch is assigned to.target
is the fully-qualified name of the parameter’s position in the module hierarchy.args
andkwargs
are don’t-carecall_function
applies a free function to some values.name
is similarly the name of the value to assign to.target
is the function to be applied.args
andkwargs
represent the arguments to the function, following the Python calling conventioncall_module
applies a module in the module hierarchy’sforward()
method to given arguments.name
is as previous.target
is the fully-qualified name of the module in the module hierarchy to call.args
andkwargs
represent the arguments to invoke the module on, including the self argument.call_method
calls a method on a value.name
is as similar.target
is the string name of the method to apply to theself
argument.args
andkwargs
represent the arguments to invoke the module on, including the self argumentoutput
contains the output of the traced function in itsargs[0]
attribute. This corresponds to the “return” statement in the Graph printout.
GraphModule automatically generates Python code for the operations it symbolically observed:
print(gm.code)
import torch
def forward(self, x):
linear_weight = self.linear.weight
add_1 = x + linear_weight
x = linear_weight = None
linear_1 = self.linear(add_1)
add_1 = None
relu_1 = linear_1.relu()
linear_1 = None
sum_1 = torch.sum(relu_1, dim = -1)
relu_1 = None
topk_1 = torch.topk(sum_1, 3)
sum_1 = None
return topk_1
topk_1 = None
Because this code is valid PyTorch code, the resulting GraphModule
can be used in any context another
nn.Module
can be used, including in TorchScript tracing/compilation.
API Reference¶
-
torch.fx.
symbolic_trace
(root)[source]¶ Symbolic tracing API
Given an
nn.Module
or function instanceroot
, this function will return aGraphModule
constructed by recording operations seen while tracing throughroot
.- Parameters
root (Union[torch.nn.Module, Callable]) – Module or function to be traced and converted into a Graph representation.
- Returns
a Module created from the recorded operations from
root
.- Return type
-
class
torch.fx.
GraphModule
(root, graph)[source]¶ GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a
graph
attribute, as well ascode
andforward
attributes generated from thatgraph
.Warning
When
graph
is reassigned,code
andforward
will be automatically regenerated. However, if you edit the contents of thegraph
without reassigning thegraph
attribute itself, you must callrecompile()
to update the generated code.-
__init__
(root, graph)[source]¶ Construct a GraphModule.
- Parameters
root (Union[torch.nn.Module, Dict[str, Any]) –
root
can either be an nn.Module instance or a Dict mapping strings to any attribute type. In the case thatroot
is a Module, any references to Module-based objects (via qualified name) in the Graph’s Nodes’target
field will be copied over from the respective place withinroot
’s Module hierarchy into the GraphModule’s module hierarchy. In the case thatroot
is a dict, the qualified name found in a Node’starget
will be looked up directly in the dict’s keys. The object mapped to by the Dict will be copied over into the appropriate place within the GraphModule’s module hierarchy.graph (Graph) –
graph
contains the nodes this GraphModule should use for code generation
-
property
code
¶ Return the Python code generated from the
Graph
underlying thisGraphModule
.
-
property
graph
¶ Return the
Graph
underlying thisGraphModule
-
recompile
()[source]¶ Recompile this GraphModule from its
graph
attribute. This should be called after editing the containedgraph
, otherwise the generated code of thisGraphModule
will be out of date.
-
to_folder
(folder, module_name='FxModule')[source]¶ Dumps out module to
folder
withmodule_name
so that it can be imported withfrom <folder> import <module_name>
- Parameters
folder (Union[str, os.PathLike]) – The folder to write the code out to
module_name (str) – Top-level name to use for the
Module
while writing out the code
-
-
class
torch.fx.
Graph
[source]¶ Graph
is the main data structure used in the FX Intermediate Representation. It consists of a series ofNode
s, each representing callsites (or other syntactic constructs). The list ofNode
s, taken together, constitute a valid Python function.For example, the following code
import torch import torch.fx class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3) m = MyModule() gm = torch.fx.symbolic_trace(m)
Will produce the following Graph:
print(gm.graph)
graph(x): %linear_weight : [#users=1] = self.linear.weight %add_1 : [#users=1] = call_function[target=<built-in function add>](args = (%x, %linear_weight), kwargs = {}) %linear_1 : [#users=1] = call_module[target=linear](args = (%add_1,), kwargs = {}) %relu_1 : [#users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {}) %sum_1 : [#users=1] = call_function[target=<built-in method sum of type object at 0x7ff2da9dc300>](args = (%relu_1,), kwargs = {dim: -1}) # noqa: B950 %topk_1 : [#users=1] = call_function[target=<built-in method topk of type object at 0x7ff2da9dc300>](args = (%sum_1, 3), kwargs = {}) # noqa: B950 return topk_1
For the semantics of operations represented in the
Graph
, please seeNode
.-
call_function
(the_function, args=None, kwargs=None, type_expr=None)[source]¶ Insert a
call_function
Node
into theGraph
. Acall_function
node represents a call to a Python callable, specified bythe_function
.the_function
can be- Parameters
the_function (Callable[.., Any]) – The function to be called. Can be any PyTorch operator, Python function, or member of the
builtins
oroperator
namespaces.args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called function.
kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called function
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
Returns
The newly created and inserted
call_function
node.Note
The same insertion point and type expression rules apply for this method as
Graph.create_node()
.
-
call_method
(method_name, args=None, kwargs=None, type_expr=None)[source]¶ Insert a
call_method
Node
into theGraph
. Acall_method
node represents a call to a given method on the 0th element ofargs
.- Parameters
method_name (str) – The name of the method to apply to the self argument. For example, if args[0] is a
Node
representing aTensor
, then to callrelu()
on thatTensor
, passrelu
tomethod_name
.args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called method. Note that this should include a
self
argument.kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called method
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly created and inserted
call_method
node.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node()
.
-
call_module
(module_name, args=None, kwargs=None, type_expr=None)[source]¶ Insert a
call_module
Node
into theGraph
. Acall_module
node represents a call to the forward() function of aModule
in theModule
hierarchy.- Parameters
module_name (str) – The qualified name of the
Module
in theModule
hierarchy to be called. For example, if the tracedModule
has a submodule namedfoo
, which has a submodule namedbar
, the qualified namefoo.bar
should be passed asmodule_name
to call that module.args (Optional[Tuple[Argument, ..]]) – The positional arguments to be passed to the called method. Note that this should not include a
self
argument.kwargs (Optional[Dict[str, Argument]]) – The keyword arguments to be passed to the called method
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted
call_module
node.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node()
.
-
create_node
(op, target, args=None, kwargs=None, name=None, type_expr=None)[source]¶ Create a
Node
and add it to theGraph
at the current insert-point. Note that the current insert-point can be set viaGraph.inserting_before()
andGraph.inserting_after()
.- Parameters
op (str) – the opcode for this Node. One of ‘call_function’, ‘call_method’, ‘get_attr’, ‘call_module’, ‘placeholder’, or ‘output’. The semantics of these opcodes are described in the
Graph
docstring.args (Optional[Tuple[Argument, ..]]) – is a tuple of arguments to this node.
kwargs (Optional[Dict[str, Argument]]) – the kwargs of this Node
name (Optional[str]) – an optional string name for the
Node
. This will influence the name of the value assigned to in the Python generated code.type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted node.
-
erase_node
(to_erase)[source]¶ Erases a
Node
from theGraph
. Throws an exception if there are still users of that node in theGraph
.- Parameters
to_erase (Node) – The
Node
to erase from theGraph
.
-
get_attr
(qualified_name, type_expr=None)[source]¶ Insert a
get_attr
node into the Graph. Aget_attr
Node
represents the fetch of an attribute from theModule
hierarchy.- Parameters
qualified_name (str) – the fully-qualified name of the attribute to be retrieved. For example, if the traced Module has a submodule named
foo
, which has a submodule namedbar
, which has an attribute namedbaz
, the qualified namefoo.bar.baz
should be passed asqualified_name
.type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
- Returns
The newly-created and inserted
get_attr
node.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node
.
-
graph_copy
(g, val_map)[source]¶ Copy all nodes from a given graph into
self
.- Parameters
- Returns
The value in
self
that is now equivalent to the output value ing
, ifg
had anoutput
node.None
otherwise.
-
inserting_after
(n=None)[source]¶ Set the point at which create_node and companion methods will insert into the graph. When used within a ‘with’ statement, this will temporary set the insert point and then restore it when the with statement exits:
with g.inserting_after(n): ... # inserting after node n ... # insert point restored to what it was previously g.inserting_after(n) # set the insert point permanently
- Parameters
n (Optional[Node]) – The node before which to insert. If None this will insert after the beginning of the entire graph.
- Returns
A resource manager that will restore the insert point on
__exit__
.
-
inserting_before
(n=None)[source]¶ Set the point at which create_node and companion methods will insert into the graph. When used within a ‘with’ statement, this will temporary set the insert point and then restore it when the with statement exits:
with g.inserting_before(n): ... # inserting before node n ... # insert point restored to what it was previously g.inserting_before(n) # set the insert point permanently
- Parameters
n (Optional[Node]) – The node before which to insert. If None this will insert before the beginning of the entire graph.
- Returns
A resource manager that will restore the insert point on
__exit__
.
-
lint
(root=None)[source]¶ Runs various checks on this Graph to make sure it is well-formed. In particular: - Checks Nodes have correct ownership (owned by this graph) - Checks Nodes appear in topological order - If
root
is provided, checks that targets exist inroot
- Parameters
root (Optional[torch.nn.Module]) – The root module with which to check for targets. This is equivalent to the
root
argument that is passed when constructing aGraphModule
.
-
node_copy
(node, arg_transform=<function Graph.<lambda>>)[source]¶ Copy a node from one graph into another.
arg_transform
needs to transform arguments from the graph of node to the graph of self. Example:# Copying all the nodes in `g` into `new_graph` g : torch.fx.Graph = ... new_graph = torch.fx.graph() value_remap = {} for node in g.nodes: value_remap[node] = new_graph.node_copy(node, lambda n : value_remap[n])
- Parameters
node (Node) – The node to copy into
self
.arg_transform (Callable[[Node], Argument]) – A function that transforms
Node
arguments in node’sargs
andkwargs
into the equivalent argument inself
. In the simplest case, this should retrieve a value out of a table mapping Nodes in the original graph toself
.
-
property
nodes
¶ Get the list of Nodes that constitute this Graph.
Note that this
Node
list representation is a doubly-linked list. Mutations during iteration (e.g. delete a Node, add a Node) are safe.- Returns
A doubly-linked list of Nodes. Note that
reversed
can be called on this list to switch iteration order.
-
output
(result, type_expr=None)[source]¶ Insert an
output
Node
into theGraph
. Anoutput
node represents areturn
statement in Python code.result
is the value that should be returned.- Parameters
result (Argument) – The value to be returned.
type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have.
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node
.
-
placeholder
(name, type_expr=None)[source]¶ Insert a
placeholder
node into the Graph. Aplaceholder
represents a function input.- Parameters
name (str) – A name for the input value. This corresponds to the name of the positional argument to the function this
Graph
represents.type_expr (Optional[Any]) – an optional type annotation representing the Python type the output of this node will have. This is needed in some cases for proper code generation (e.g. when the function is used subsequently in TorchScript compilation).
Note
The same insertion point and type expression rules apply for this method as
Graph.create_node
.
-
-
class
torch.fx.
Node
(graph, name, op, target, args, kwargs, type=None)[source]¶ Node
is the data structure that represents individual operations within aGraph
. For the most part, Nodes represent callsites to various entities, such as operators, methods, and Modules (some exceptions include nodes that specify function inputs and outputs). EachNode
has a function specified by itsop
property. TheNode
semantics for each value ofop
are as follows:placeholder
represents a function input. Thename
attribute specifies the name this value will take on.target
is similarly the name of the argument.args
holds either: 1) nothing, or 2) a single argument denoting the default parameter of the function input.kwargs
is don’t-care. Placeholders correspond to the function parameters (e.g.x
) in the graph printout.get_attr
retrieves a parameter from the module hierarchy.name
is similarly the name the result of the fetch is assigned to.target
is the fully-qualified name of the parameter’s position in the module hierarchy.args
andkwargs
are don’t-carecall_function
applies a free function to some values.name
is similarly the name of the value to assign to.target
is the function to be applied.args
andkwargs
represent the arguments to the function, following the Python calling conventioncall_module
applies a module in the module hierarchy’sforward()
method to given arguments.name
is as previous.target
is the fully-qualified name of the module in the module hierarchy to call.args
andkwargs
represent the arguments to invoke the module on, including the self argument.call_method
calls a method on a value.name
is as similar.target
is the string name of the method to apply to theself
argument.args
andkwargs
represent the arguments to invoke the module on, including the self argumentoutput
contains the output of the traced function in itsargs[0]
attribute. This corresponds to the “return” statement in the Graph printout.
-
property
all_input_nodes
¶ Return all Nodes that are inputs to this Node. This is equivalent to iterating over
args
andkwargs
and only collecting the values that are Nodes.- Returns
List of
Nodes
that appear in theargs
andkwargs
of thisNode
, in that order.
-
append
(x)[source]¶ Insert x after this node in the list of nodes in the graph. Equvalent to
self.next.prepend(x)
- Parameters
x (Node) – The node to put after this node. Must be a member of the same graph.
-
property
args
¶ The tuple of arguments to this
Node
. The interpretation of arguments depends on the node’s opcode. See theNode
docstring for more information.Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
-
property
kwargs
¶ The dict of keyword arguments to this
Node
. The interpretation of arguments depends on the node’s opcode. See theNode
docstring for more information.Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
-
property
next
¶ Returns the next
Node
in the linked list of Nodes.- Returns
The next
Node
in the linked list of Nodes.
-
prepend
(x)[source]¶ Insert x before this node in the list of nodes in the graph. Example:
Before: p -> self bx -> x -> ax After: p -> x -> self bx -> ax
- Parameters
x (Node) – The node to put before this node. Must be a member of the same graph.
-
property
prev
¶ Returns the previous
Node
in the linked list of Nodes.- Returns
The previous
Node
in the linked list of Nodes.
-
class
torch.fx.
Tracer
[source]¶ Tracer
is the class that implements the symbolic tracing functionality oftorch.fx.symbolic_trace
. A call tosymbolic_trace(m)
is equivalent toTracer().trace(m)
.Tracer can be subclassed to override various behaviors of the tracing process. The different behaviors that can be overridden are described in the docstrings of the methods on this class.
-
call_module
(m, forward, args, kwargs)[source]¶ Method that specifies the behavior of this
Tracer
when it encounters a call to annn.Module
instance.By default, the behavior is to check if the called module is a leaf module via
is_leaf_module
. If it is, emit acall_module
node referring tom
in theGraph
. Otherwise, call theModule
normally, tracing through the operations in itsforward
function.This method can be overridden to–for example–create nested traced GraphModules, or any other behavior you would want while tracing across
Module
boundaries.Module
boundaries.- Parameters
m (Module) – The module for which a call is being emitted
forward (Callable) – The forward() method of the
Module
to be invokedargs (Tuple) – args of the module callsite
kwargs (Dict) – kwargs of the module callsite
- Returns
The return value from the Module call. In the case that a
call_module
node was emitted, this is aProxy
value. Otherwise, it is whatever value was returned from theModule
invocation.
-
create_arg
(a)[source]¶ A method to specify the behavior of tracing when preparing values to be used as arguments to nodes in the
Graph
.By default, the behavior includes:
Iterate through collection types (e.g. tuple, list, dict) and recursively call
create_args
on the elements.Given a Proxy object, return a reference to the underlying IR
Node
Given a non-Proxy Tensor object, emit IR for various cases:
For a Parameter, emit a
get_attr
node referring to that ParameterFor a non-Parameter Tensor, store the Tensor away in a special attribute referring to that attribute.
This method can be overridden to support more types.
- Parameters
a (Any) – The value to be emitted as an
Argument
in theGraph
.- Returns
The value
a
converted into the appropriateArgument
-
create_args_for_root
(root_fn, is_module)[source]¶ Create
placeholder
nodes corresponding to the signature of theroot
Module. This method introspects root’s signature and emits those nodes accordingly, also supporting*args
and**kwargs
.
-
is_leaf_module
(m, module_qualified_name)[source]¶ A method to specify whether a given
nn.Module
is a “leaf” module.Leaf modules are the atomic units that appear in the IR, referenced by
call_module
calls. By default, Modules in the PyTorch standard library namespace (torch.nn) are leaf modules. All other modules are traced through and their constituent ops are recorded, unless specified otherwise via this parameter.- Parameters
-
path_of_module
(mod)[source]¶ Helper method to find the qualified name of
mod
in the Module hierarchy ofroot
. For example, ifroot
has a submodule namedfoo
, which has a submodule namedbar
, passingbar
into this function will return the string “foo.bar”.- Parameters
mod (str) – The
Module
to retrieve the qualified name for.
-
trace
(root)[source]¶ Trace
root
and return the corresponding FXGraph
representation.root
can either be annn.Module
instance or a Python callable.- Parameters
root (Union[Module, Callable]) – Either a
Module
or a function to be traced through.- Returns
A
Graph
representing the semantics of the passed-inroot
.
-