doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
call_method(method_name, args=None, kwargs=None, type_expr=None) [source] Insert a call_method Node into the Graph. A call_method node represents a call to a given method on the 0th element of args. Parameters method_name (str) – The name of the method to apply to the self argument. For example, if args[0] is a Node representing a Tensor, then to call relu() on that Tensor, pass relu to method_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().
torch.fx#torch.fx.Graph.call_method
call_module(module_name, args=None, kwargs=None, type_expr=None) [source] Insert a call_module Node into the Graph. A call_module node represents a call to the forward() function of a Module in the Module hierarchy. Parameters module_name (str) – The qualified name of the Module in the Module hierarchy to be called. For example, if the traced Module has a submodule named foo, which has a submodule named bar, the qualified name foo.bar should be passed as module_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().
torch.fx#torch.fx.Graph.call_module
create_node(op, target, args=None, kwargs=None, name=None, type_expr=None) [source] Create a Node and add it to the Graph at the current insert-point. Note that the current insert-point can be set via Graph.inserting_before() and Graph.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.
torch.fx#torch.fx.Graph.create_node
erase_node(to_erase) [source] Erases a Node from the Graph. Throws an exception if there are still users of that node in the Graph. Parameters to_erase (Node) – The Node to erase from the Graph.
torch.fx#torch.fx.Graph.erase_node
get_attr(qualified_name, type_expr=None) [source] Insert a get_attr node into the Graph. A get_attr Node represents the fetch of an attribute from the Module 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 named bar, which has an attribute named baz, the qualified name foo.bar.baz should be passed as qualified_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.
torch.fx#torch.fx.Graph.get_attr
graph_copy(g, val_map) [source] Copy all nodes from a given graph into self. Parameters g (Graph) – The source graph from which to copy Nodes. val_map (Dict[Node, Node]) – a dictionary that will be populated with a mapping from nodes in g to nodes in self. Note that val_map can be passed in with values in it already to override copying of certain values. Returns The value in self that is now equivalent to the output value in g, if g had an output node. None otherwise.
torch.fx#torch.fx.Graph.graph_copy
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__.
torch.fx#torch.fx.Graph.inserting_after
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__.
torch.fx#torch.fx.Graph.inserting_before
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 in root 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 a GraphModule.
torch.fx#torch.fx.Graph.lint
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.
torch.fx#torch.fx.Graph.nodes
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’s args and kwargs into the equivalent argument in self. In the simplest case, this should retrieve a value out of a table mapping Nodes in the original graph to self.
torch.fx#torch.fx.Graph.node_copy
output(result, type_expr=None) [source] Insert an output Node into the Graph. An output node represents a return 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.
torch.fx#torch.fx.Graph.output
placeholder(name, type_expr=None) [source] Insert a placeholder node into the Graph. A placeholder 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.
torch.fx#torch.fx.Graph.placeholder
print_tabular() [source] Prints the intermediate representation of the graph in tabular format.
torch.fx#torch.fx.Graph.print_tabular
python_code(root_module) [source] Turn this Graph into valid Python code. Parameters root_module (str) – The name of the root module on which to look-up qualified name targets. This is usually ‘self’. Returns The string source code generated from this Graph.
torch.fx#torch.fx.Graph.python_code
__init__() [source] Construct an empty Graph.
torch.fx#torch.fx.Graph.__init__
class torch.fx.GraphModule(root, graph, class_name='GraphModule') [source] GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a graph attribute, as well as code and forward attributes generated from that graph. Warning When graph is reassigned, code and forward will be automatically regenerated. However, if you edit the contents of the graph without reassigning the graph attribute itself, you must call recompile() to update the generated code. __init__(root, graph, class_name='GraphModule') [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 that root 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 within root’s Module hierarchy into the GraphModule’s module hierarchy. In the case that root is a dict, the qualified name found in a Node’s target 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 name (str) – name denotes the name of this GraphModule for debugging purposes. If it’s unset, all error messages will report as originating from GraphModule. It may be helpful to set this to root’s original name or a name that makes sense within the context of your transform. property code Return the Python code generated from the Graph underlying this GraphModule. property graph Return the Graph underlying this GraphModule recompile() [source] Recompile this GraphModule from its graph attribute. This should be called after editing the contained graph, otherwise the generated code of this GraphModule will be out of date. to_folder(folder, module_name='FxModule') [source] Dumps out module to folder with module_name so that it can be imported with from <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
torch.fx#torch.fx.GraphModule
property code Return the Python code generated from the Graph underlying this GraphModule.
torch.fx#torch.fx.GraphModule.code
property graph Return the Graph underlying this GraphModule
torch.fx#torch.fx.GraphModule.graph
recompile() [source] Recompile this GraphModule from its graph attribute. This should be called after editing the contained graph, otherwise the generated code of this GraphModule will be out of date.
torch.fx#torch.fx.GraphModule.recompile
to_folder(folder, module_name='FxModule') [source] Dumps out module to folder with module_name so that it can be imported with from <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
torch.fx#torch.fx.GraphModule.to_folder
__init__(root, graph, class_name='GraphModule') [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 that root 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 within root’s Module hierarchy into the GraphModule’s module hierarchy. In the case that root is a dict, the qualified name found in a Node’s target 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 name (str) – name denotes the name of this GraphModule for debugging purposes. If it’s unset, all error messages will report as originating from GraphModule. It may be helpful to set this to root’s original name or a name that makes sense within the context of your transform.
torch.fx#torch.fx.GraphModule.__init__
class torch.fx.Interpreter(module) [source] An Interpreter executes an FX graph Node-by-Node. This pattern can be useful for many things, including writing code transformations as well as analysis passes. Methods in the Interpreter class can be overridden to customize the behavior of execution. The map of overrideable methods in terms of call hierarchy: run() +-- run_node +-- placeholder() +-- get_attr() +-- call_function() +-- call_method() +-- call_module() +-- output() Example Suppose we want to swap all instances of torch.neg with torch.sigmoid and vice versa (including their Tensor method equivalents). We could subclass Interpreter like so: class NegSigmSwapInterpreter(Interpreter): def call_function(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : Target, args : Tuple, kwargs : Dict) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) input = torch.randn(3, 4) result = NegSigmSwapInterpreter(gm).run(input) torch.testing.assert_allclose(result, torch.neg(input).sigmoid()) Parameters module (GraphModule) – The module to be executed call_function(target, args, kwargs) [source] Execute a call_function node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the function invocation call_method(target, args, kwargs) [source] Execute a call_method node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the method invocation call_module(target, args, kwargs) [source] Execute a call_module node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the module invocation fetch_args_kwargs_from_env(n) [source] Fetch the concrete values of args and kwargs of node n from the current execution environment. Parameters n (Node) – The node for which args and kwargs should be fetched. Returns args and kwargs with concrete values for n. Return type Tuple[Tuple, Dict] fetch_attr(target) [source] Fetch an attribute from the Module hierarchy of self.module. Parameters target (str) – The fully-qualfiied name of the attribute to fetch Returns The value of the attribute. Return type Any get_attr(target, args, kwargs) [source] Execute a get_attr node. Will retrieve an attribute value from the Module hierarchy of self.module. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The value of the attribute that was retrieved Return type Any map_nodes_to_values(args, n) [source] Recursively descend through args and look up the concrete value for each Node in the current execution environment. Parameters args (Argument) – Data structure within which to look up concrete values n (Node) – Node to which args belongs. This is only used for error reporting. output(target, args, kwargs) [source] Execute an output node. This really just retrieves the value referenced by the output node and returns it. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The return value referenced by the output node Return type Any placeholder(target, args, kwargs) [source] Execute a placeholder node. Note that this is stateful: Interpreter maintains an internal iterator over arguments passed to run and this method returns next() on that iterator. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The argument value that was retrieved. Return type Any run(*args, initial_env=None) [source] Run module via interpretation and return the result. Parameters *args – The arguments to the Module to run, in positional order initial_env (Optional[Dict[Node, Any]]) – An optional starting environment for execution. This is a dict mapping Node to any value. This can be used, for example, to pre-populate results for certain Nodes so as to do only partial evaluation within the interpreter. Returns The value returned from executing the Module Return type Any run_node(n) [source] Run a specific node n and return the result. Calls into placeholder, get_attr, call_function, call_method, call_module, or output depending on node.op Parameters n (Node) – The Node to execute Returns The result of executing n Return type Any
torch.fx#torch.fx.Interpreter
call_function(target, args, kwargs) [source] Execute a call_function node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the function invocation
torch.fx#torch.fx.Interpreter.call_function
call_method(target, args, kwargs) [source] Execute a call_method node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the method invocation
torch.fx#torch.fx.Interpreter.call_method
call_module(target, args, kwargs) [source] Execute a call_module node and return the result. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Return Any: The value returned by the module invocation
torch.fx#torch.fx.Interpreter.call_module
fetch_args_kwargs_from_env(n) [source] Fetch the concrete values of args and kwargs of node n from the current execution environment. Parameters n (Node) – The node for which args and kwargs should be fetched. Returns args and kwargs with concrete values for n. Return type Tuple[Tuple, Dict]
torch.fx#torch.fx.Interpreter.fetch_args_kwargs_from_env
fetch_attr(target) [source] Fetch an attribute from the Module hierarchy of self.module. Parameters target (str) – The fully-qualfiied name of the attribute to fetch Returns The value of the attribute. Return type Any
torch.fx#torch.fx.Interpreter.fetch_attr
get_attr(target, args, kwargs) [source] Execute a get_attr node. Will retrieve an attribute value from the Module hierarchy of self.module. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The value of the attribute that was retrieved Return type Any
torch.fx#torch.fx.Interpreter.get_attr
map_nodes_to_values(args, n) [source] Recursively descend through args and look up the concrete value for each Node in the current execution environment. Parameters args (Argument) – Data structure within which to look up concrete values n (Node) – Node to which args belongs. This is only used for error reporting.
torch.fx#torch.fx.Interpreter.map_nodes_to_values
output(target, args, kwargs) [source] Execute an output node. This really just retrieves the value referenced by the output node and returns it. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The return value referenced by the output node Return type Any
torch.fx#torch.fx.Interpreter.output
placeholder(target, args, kwargs) [source] Execute a placeholder node. Note that this is stateful: Interpreter maintains an internal iterator over arguments passed to run and this method returns next() on that iterator. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation Returns The argument value that was retrieved. Return type Any
torch.fx#torch.fx.Interpreter.placeholder
run(*args, initial_env=None) [source] Run module via interpretation and return the result. Parameters *args – The arguments to the Module to run, in positional order initial_env (Optional[Dict[Node, Any]]) – An optional starting environment for execution. This is a dict mapping Node to any value. This can be used, for example, to pre-populate results for certain Nodes so as to do only partial evaluation within the interpreter. Returns The value returned from executing the Module Return type Any
torch.fx#torch.fx.Interpreter.run
run_node(n) [source] Run a specific node n and return the result. Calls into placeholder, get_attr, call_function, call_method, call_module, or output depending on node.op Parameters n (Node) – The Node to execute Returns The result of executing n Return type Any
torch.fx#torch.fx.Interpreter.run_node
class torch.fx.Node(graph, name, op, target, args, kwargs, type=None) [source] Node is the data structure that represents individual operations within a Graph. 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). Each Node has a function specified by its op property. The Node semantics for each value of op are as follows: placeholder represents a function input. The name 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 and kwargs are don’t-care call_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 and kwargs represent the arguments to the function, following the Python calling convention call_module applies a module in the module hierarchy’s forward() method to given arguments. name is as previous. target is the fully-qualified name of the module in the module hierarchy to call. args and kwargs 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 the self argument. args and kwargs represent the arguments to invoke the module on, including the self argument output contains the output of the traced function in its args[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 and kwargs and only collecting the values that are Nodes. Returns List of Nodes that appear in the args and kwargs of this Node, 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 the Node 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 the Node 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. replace_all_uses_with(replace_with) [source] Replace all uses of self in the Graph with the Node replace_with. Parameters replace_with (Node) – The node to replace all uses of self with. Returns The list of Nodes on which this change was made.
torch.fx#torch.fx.Node
property all_input_nodes Return all Nodes that are inputs to this Node. This is equivalent to iterating over args and kwargs and only collecting the values that are Nodes. Returns List of Nodes that appear in the args and kwargs of this Node, in that order.
torch.fx#torch.fx.Node.all_input_nodes
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.
torch.fx#torch.fx.Node.append
property args The tuple of arguments to this Node. The interpretation of arguments depends on the node’s opcode. See the Node docstring for more information. Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
torch.fx#torch.fx.Node.args
property kwargs The dict of keyword arguments to this Node. The interpretation of arguments depends on the node’s opcode. See the Node docstring for more information. Assignment to this property is allowed. All accounting of uses and users is updated automatically on assignment.
torch.fx#torch.fx.Node.kwargs
property next Returns the next Node in the linked list of Nodes. Returns The next Node in the linked list of Nodes.
torch.fx#torch.fx.Node.next
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.
torch.fx#torch.fx.Node.prepend
property prev Returns the previous Node in the linked list of Nodes. Returns The previous Node in the linked list of Nodes.
torch.fx#torch.fx.Node.prev
replace_all_uses_with(replace_with) [source] Replace all uses of self in the Graph with the Node replace_with. Parameters replace_with (Node) – The node to replace all uses of self with. Returns The list of Nodes on which this change was made.
torch.fx#torch.fx.Node.replace_all_uses_with
class torch.fx.Proxy(node, tracer=None) [source] Proxy objects are Node wrappers that flow through the program during symbolic tracing and record all the operations (torch function calls, method calls, operators) that they touch into the growing FX Graph. If you’re doing graph transforms, you can wrap your own Proxy method around a raw Node so that you can use the overloaded operators to add additional things to a Graph.
torch.fx#torch.fx.Proxy
torch.fx.replace_pattern(gm, pattern, replacement) [source] Matches all possible non-overlapping sets of operators and their data dependencies (pattern) in the Graph of a GraphModule (gm), then replaces each of these matched subgraphs with another subgraph (replacement). Parameters gm – The GraphModule that wraps the Graph to operate on pattern – The subgraph to match in gm for replacement replacement – The subgraph to replace pattern with Returns A list of Match objects representing the places in the original graph that pattern was matched to. The list is empty if there are no matches. Match is defined as: class Match(NamedTuple): # Node from which the match was found anchor: Node # Maps nodes in the pattern subgraph to nodes in the larger graph nodes_map: Dict[Node, Node] Return type List[Match] Examples: import torch from torch.fx import symbolic_trace, subgraph_rewriter class M(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, w1, w2): m1 = torch.cat([w1, w2]).sum() m2 = torch.cat([w1, w2]).sum() return x + torch.max(m1) + torch.max(m2) def pattern(w1, w2): return torch.cat([w1, w2]).sum() def replacement(w1, w2): return torch.stack([w1, w2]) traced_module = symbolic_trace(M()) subgraph_rewriter.replace_pattern(traced_module, pattern, replacement) The above code will first match pattern in the forward method of traced_module. Pattern-matching is done based on use-def relationships, not node names. For example, if you had p = torch.cat([a, b]) in pattern, you could match m = torch.cat([a, b]) in the original forward function, despite the variable names being different (p vs m). The return statement in pattern is matched based on its value only; it may or may not match to the return statement in the larger graph. In other words, the pattern doesn’t have to extend to the end of the larger graph. When the pattern is matched, it will be removed from the larger function and replaced by replacement. If there are multiple matches for pattern in the larger function, each non-overlapping match will be replaced. In the case of a match overlap, the first found match in the set of overlapping matches will be replaced. (“First” here being defined as the first in a topological ordering of the Nodes’ use-def relationships. In most cases, the first Node is the parameter that appears directly after self, while the last Node is whatever the function returns.) One important thing to note is that the parameters of the pattern Callable must be used in the Callable itself, and the parameters of the replacement Callable must match the pattern. The first rule is why, in the above code block, the forward function has parameters x, w1, w2, but the pattern function only has parameters w1, w2. pattern doesn’t use x, so it shouldn’t specify x as a parameter. As an example of the second rule, consider replacing def pattern(x, y): return torch.neg(x) + torch.relu(y) with def replacement(x, y): return torch.relu(x) In this case, replacement needs the same number of parameters as pattern (both x and y), even though the parameter y isn’t used in replacement. After calling subgraph_rewriter.replace_pattern, the generated Python code looks like this: def forward(self, x, w1, w2): stack_1 = torch.stack([w1, w2]) sum_1 = stack_1.sum() stack_2 = torch.stack([w1, w2]) sum_2 = stack_2.sum() max_1 = torch.max(sum_1) add_1 = x + max_1 max_2 = torch.max(sum_2) add_2 = add_1 + max_2 return add_2
torch.fx#torch.fx.replace_pattern
torch.fx.symbolic_trace(root, concrete_args=None) [source] Symbolic tracing API Given an nn.Module or function instance root, this function will return a GraphModule constructed by recording operations seen while tracing through root. Parameters root (Union[torch.nn.Module, Callable]) – Module or function to be traced and converted into a Graph representation. concrete_args (Optional[Dict[str, any]]) – Concrete arguments that should not be treated as Proxies. Returns a Module created from the recorded operations from root. Return type GraphModule
torch.fx#torch.fx.symbolic_trace
class torch.fx.Tracer(autowrap_modules=(<module 'math' from '/home/matti/miniconda3/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>, )) [source] Tracer is the class that implements the symbolic tracing functionality of torch.fx.symbolic_trace. A call to symbolic_trace(m) is equivalent to Tracer().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 an nn.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 a call_module node referring to m in the Graph. Otherwise, call the Module normally, tracing through the operations in its forward 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 invoked args (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 a Proxy value. Otherwise, it is whatever value was returned from the Module 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 Parameter For 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 the Graph. Returns The value a converted into the appropriate Argument create_args_for_root(root_fn, is_module, concrete_args=None) [source] Create placeholder nodes corresponding to the signature of the root 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 m (Module) – The module being queried about module_qualified_name (str) – The path to root of this module. For example, if you have a module hierarchy where submodule foo contains submodule bar, which contains submodule baz, that module will appear with the qualified name foo.bar.baz here. path_of_module(mod) [source] Helper method to find the qualified name of mod in the Module hierarchy of root. For example, if root has a submodule named foo, which has a submodule named bar, passing bar into this function will return the string “foo.bar”. Parameters mod (str) – The Module to retrieve the qualified name for. trace(root, concrete_args=None) [source] Trace root and return the corresponding FX Graph representation. root can either be an nn.Module instance or a Python callable. Note that after this call, self.root may be different from the root passed in here. For example, when a free function is passed to trace(), we will create an nn.Module instance to use as the root and add embedded constants to. Parameters root (Union[Module, Callable]) – Either a Module or a function to be traced through. Returns A Graph representing the semantics of the passed-in root.
torch.fx#torch.fx.Tracer
call_module(m, forward, args, kwargs) [source] Method that specifies the behavior of this Tracer when it encounters a call to an nn.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 a call_module node referring to m in the Graph. Otherwise, call the Module normally, tracing through the operations in its forward 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 invoked args (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 a Proxy value. Otherwise, it is whatever value was returned from the Module invocation.
torch.fx#torch.fx.Tracer.call_module
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 Parameter For 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 the Graph. Returns The value a converted into the appropriate Argument
torch.fx#torch.fx.Tracer.create_arg
create_args_for_root(root_fn, is_module, concrete_args=None) [source] Create placeholder nodes corresponding to the signature of the root Module. This method introspects root’s signature and emits those nodes accordingly, also supporting *args and **kwargs.
torch.fx#torch.fx.Tracer.create_args_for_root
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 m (Module) – The module being queried about module_qualified_name (str) – The path to root of this module. For example, if you have a module hierarchy where submodule foo contains submodule bar, which contains submodule baz, that module will appear with the qualified name foo.bar.baz here.
torch.fx#torch.fx.Tracer.is_leaf_module
path_of_module(mod) [source] Helper method to find the qualified name of mod in the Module hierarchy of root. For example, if root has a submodule named foo, which has a submodule named bar, passing bar into this function will return the string “foo.bar”. Parameters mod (str) – The Module to retrieve the qualified name for.
torch.fx#torch.fx.Tracer.path_of_module
trace(root, concrete_args=None) [source] Trace root and return the corresponding FX Graph representation. root can either be an nn.Module instance or a Python callable. Note that after this call, self.root may be different from the root passed in here. For example, when a free function is passed to trace(), we will create an nn.Module instance to use as the root and add embedded constants to. Parameters root (Union[Module, Callable]) – Either a Module or a function to be traced through. Returns A Graph representing the semantics of the passed-in root.
torch.fx#torch.fx.Tracer.trace
class torch.fx.Transformer(module) [source] Transformer is a special type of interpreter that produces a new Module. It exposes a transform() method that returns the transformed Module. Transformer does not require arguments to run, as Interpreter does. Transformer works entirely symbolically. Example Suppose we want to swap all instances of torch.neg with torch.sigmoid and vice versa (including their Tensor method equivalents). We could subclass Transformer like so: class NegSigmSwapXformer(Transformer): def call_function(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any: if target == torch.sigmoid: return torch.neg(*args, **kwargs) return super().call_function(n) def call_method(self, target : 'Target', args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any: if target == 'neg': call_self, *args_tail = args return call_self.sigmoid(*args_tail, **kwargs) return super().call_method(n) def fn(x): return torch.sigmoid(x).neg() gm = torch.fx.symbolic_trace(fn) transformed : torch.nn.Module = NegSigmSwapXformer(gm).transform() input = torch.randn(3, 4) torch.testing.assert_allclose(transformed(input), torch.neg(input).sigmoid()) Parameters module (GraphModule) – The Module to be transformed. get_attr(target, args, kwargs) [source] Execute a get_attr node. In Transformer, this is overridden to insert a new get_attr node into the output graph. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation placeholder(target, args, kwargs) [source] Execute a placeholder node. In Transformer, this is overridden to insert a new placeholder into the output graph. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation transform() [source] Transform self.module and return the transformed GraphModule.
torch.fx#torch.fx.Transformer
get_attr(target, args, kwargs) [source] Execute a get_attr node. In Transformer, this is overridden to insert a new get_attr node into the output graph. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation
torch.fx#torch.fx.Transformer.get_attr
placeholder(target, args, kwargs) [source] Execute a placeholder node. In Transformer, this is overridden to insert a new placeholder into the output graph. Parameters target (Target) – The call target for this node. See Node for details on semantics args (Tuple) – Tuple of positional args for this invocation kwargs (Dict) – Dict of keyword arguments for this invocation
torch.fx#torch.fx.Transformer.placeholder
transform() [source] Transform self.module and return the transformed GraphModule.
torch.fx#torch.fx.Transformer.transform
torch.fx.wrap(fn_or_name) [source] This function can be called at module-level scope to register fn_or_name as a “leaf function”. A “leaf function” will be preserved as a CallFunction node in the FX trace instead of being traced through: # foo/bar/baz.py def my_custom_function(x, y): return x * x + y * y torch.fx.wrap('my_custom_function') def fn_to_be_traced(x, y): # When symbolic tracing, the below call to my_custom_function will be inserted into # the graph rather than tracing it. return my_custom_function(x, y) This function can also equivalently be used as a decorator: # foo/bar/baz.py @torch.fx.wrap def my_custom_function(x, y): return x * x + y * y A wrapped function can be thought of a “leaf function”, analogous to the concept of “leaf modules”, that is, they are functions that are left as calls in the FX trace rather than traced through. Parameters fn_or_name (Union[str, Callable]) – The function or name of the global function to insert into the graph when it’s called
torch.fx#torch.fx.wrap
torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 input and index must have the same number of dimensions. It is also required that index.size(d) <= input.size(d) for all dimensions d != dim. out will have the same shape as index. Note that input and index do not broadcast against each other. Parameters input (Tensor) – the source tensor dim (int) – the axis along which to index index (LongTensor) – the indices of elements to gather Keyword Arguments sparse_grad (bool, optional) – If True, gradient w.r.t. input will be a sparse tensor. out (Tensor, optional) – the destination tensor Example: >>> t = torch.tensor([[1, 2], [3, 4]]) >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) tensor([[ 1, 1], [ 4, 3]])
torch.generated.torch.gather#torch.gather
torch.gcd(input, other, *, out=None) → Tensor Computes the element-wise greatest common divisor (GCD) of input and other. Both input and other must have integer types. Note This defines gcd(0,0)=0gcd(0, 0) = 0 . Parameters input (Tensor) – the input tensor. other (Tensor) – the second input tensor Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.tensor([5, 10, 15]) >>> b = torch.tensor([3, 4, 5]) >>> torch.gcd(a, b) tensor([1, 2, 5]) >>> c = torch.tensor([3]) >>> torch.gcd(a, c) tensor([1, 1, 3])
torch.generated.torch.gcd#torch.gcd
torch.ge(input, other, *, out=None) → Tensor Computes input≥other\text{input} \geq \text{other} element-wise. The second argument can be a number or a tensor whose shape is broadcastable with the first argument. Parameters input (Tensor) – the tensor to compare other (Tensor or float) – the tensor or value to compare Keyword Arguments out (Tensor, optional) – the output tensor. Returns A boolean tensor that is True where input is greater than or equal to other and False elsewhere Example: >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[True, True], [False, True]])
torch.generated.torch.ge#torch.ge
class torch.Generator(device='cpu') → Generator Creates and returns a generator object that manages the state of the algorithm which produces pseudo random numbers. Used as a keyword argument in many In-place random sampling functions. Parameters device (torch.device, optional) – the desired device for the generator. Returns An torch.Generator object. Return type Generator Example: >>> g_cpu = torch.Generator() >>> g_cuda = torch.Generator(device='cuda') device Generator.device -> device Gets the current device of the generator. Example: >>> g_cpu = torch.Generator() >>> g_cpu.device device(type='cpu') get_state() → Tensor Returns the Generator state as a torch.ByteTensor. Returns A torch.ByteTensor which contains all the necessary bits to restore a Generator to a specific point in time. Return type Tensor Example: >>> g_cpu = torch.Generator() >>> g_cpu.get_state() initial_seed() → int Returns the initial seed for generating random numbers. Example: >>> g_cpu = torch.Generator() >>> g_cpu.initial_seed() 2147483647 manual_seed(seed) → Generator Sets the seed for generating random numbers. Returns a torch.Generator object. It is recommended to set a large seed, i.e. a number that has a good balance of 0 and 1 bits. Avoid having many 0 bits in the seed. Parameters seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed. Returns An torch.Generator object. Return type Generator Example: >>> g_cpu = torch.Generator() >>> g_cpu.manual_seed(2147483647) seed() → int Gets a non-deterministic random number from std::random_device or the current time and uses it to seed a Generator. Example: >>> g_cpu = torch.Generator() >>> g_cpu.seed() 1516516984916 set_state(new_state) → void Sets the Generator state. Parameters new_state (torch.ByteTensor) – The desired state. Example: >>> g_cpu = torch.Generator() >>> g_cpu_other = torch.Generator() >>> g_cpu.set_state(g_cpu_other.get_state())
torch.generated.torch.generator#torch.Generator
device Generator.device -> device Gets the current device of the generator. Example: >>> g_cpu = torch.Generator() >>> g_cpu.device device(type='cpu')
torch.generated.torch.generator#torch.Generator.device
get_state() → Tensor Returns the Generator state as a torch.ByteTensor. Returns A torch.ByteTensor which contains all the necessary bits to restore a Generator to a specific point in time. Return type Tensor Example: >>> g_cpu = torch.Generator() >>> g_cpu.get_state()
torch.generated.torch.generator#torch.Generator.get_state
initial_seed() → int Returns the initial seed for generating random numbers. Example: >>> g_cpu = torch.Generator() >>> g_cpu.initial_seed() 2147483647
torch.generated.torch.generator#torch.Generator.initial_seed
manual_seed(seed) → Generator Sets the seed for generating random numbers. Returns a torch.Generator object. It is recommended to set a large seed, i.e. a number that has a good balance of 0 and 1 bits. Avoid having many 0 bits in the seed. Parameters seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed. Returns An torch.Generator object. Return type Generator Example: >>> g_cpu = torch.Generator() >>> g_cpu.manual_seed(2147483647)
torch.generated.torch.generator#torch.Generator.manual_seed
seed() → int Gets a non-deterministic random number from std::random_device or the current time and uses it to seed a Generator. Example: >>> g_cpu = torch.Generator() >>> g_cpu.seed() 1516516984916
torch.generated.torch.generator#torch.Generator.seed
set_state(new_state) → void Sets the Generator state. Parameters new_state (torch.ByteTensor) – The desired state. Example: >>> g_cpu = torch.Generator() >>> g_cpu_other = torch.Generator() >>> g_cpu.set_state(g_cpu_other.get_state())
torch.generated.torch.generator#torch.Generator.set_state
torch.geqrf(input, *, out=None) -> (Tensor, Tensor) This is a low-level function for calling LAPACK directly. This function returns a namedtuple (a, tau) as defined in LAPACK documentation for geqrf . You’ll generally want to use torch.qr() instead. Computes a QR decomposition of input, but without constructing QQ and RR as explicit separate matrices. Rather, this directly calls the underlying LAPACK function ?geqrf which produces a sequence of ‘elementary reflectors’. See LAPACK documentation for geqrf for further details. Parameters input (Tensor) – the input matrix Keyword Arguments out (tuple, optional) – the output tuple of (Tensor, Tensor)
torch.generated.torch.geqrf#torch.geqrf
torch.ger(input, vec2, *, out=None) → Tensor Alias of torch.outer(). Warning This function is deprecated and will be removed in a future PyTorch release. Use torch.outer() instead.
torch.generated.torch.ger#torch.ger
torch.get_default_dtype() → torch.dtype Get the current default floating point torch.dtype. Example: >>> torch.get_default_dtype() # initial default for floating point is torch.float32 torch.float32 >>> torch.set_default_dtype(torch.float64) >>> torch.get_default_dtype() # default is now changed to torch.float64 torch.float64 >>> torch.set_default_tensor_type(torch.FloatTensor) # setting tensor type also affects this >>> torch.get_default_dtype() # changed to torch.float32, the dtype for torch.FloatTensor torch.float32
torch.generated.torch.get_default_dtype#torch.get_default_dtype
torch.get_num_interop_threads() → int Returns the number of threads used for inter-op parallelism on CPU (e.g. in JIT interpreter)
torch.generated.torch.get_num_interop_threads#torch.get_num_interop_threads
torch.get_num_threads() → int Returns the number of threads used for parallelizing CPU operations
torch.generated.torch.get_num_threads#torch.get_num_threads
torch.get_rng_state() [source] Returns the random number generator state as a torch.ByteTensor.
torch.generated.torch.get_rng_state#torch.get_rng_state
torch.greater(input, other, *, out=None) → Tensor Alias for torch.gt().
torch.generated.torch.greater#torch.greater
torch.greater_equal(input, other, *, out=None) → Tensor Alias for torch.ge().
torch.generated.torch.greater_equal#torch.greater_equal
torch.gt(input, other, *, out=None) → Tensor Computes input>other\text{input} > \text{other} element-wise. The second argument can be a number or a tensor whose shape is broadcastable with the first argument. Parameters input (Tensor) – the tensor to compare other (Tensor or float) – the tensor or value to compare Keyword Arguments out (Tensor, optional) – the output tensor. Returns A boolean tensor that is True where input is greater than other and False elsewhere Example: >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[False, True], [False, False]])
torch.generated.torch.gt#torch.gt
torch.hamming_window(window_length, periodic=True, alpha=0.54, beta=0.46, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor Hamming window function. w[n]=α−βcos⁡(2πnN−1),w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), where NN is the full window size. The input window_length is a positive integer controlling the returned window size. periodic flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like torch.stft(). Therefore, if periodic is true, the NN in above formula is in fact window_length+1\text{window\_length} + 1 . Also, we always have torch.hamming_window(L, periodic=True) equal to torch.hamming_window(L + 1, periodic=False)[:-1]). Note If window_length =1=1 , the returned window contains a single value 1. Note This is a generalized version of torch.hann_window(). Parameters window_length (int) – the size of returned window periodic (bool, optional) – If True, returns a window to be used as periodic function. If False, return a symmetric window. alpha (float, optional) – The coefficient α\alpha in the equation above beta (float, optional) – The coefficient β\beta in the equation above Keyword Arguments dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()). Only floating point types are supported. layout (torch.layout, optional) – the desired layout of returned window tensor. Only torch.strided (dense layout) is supported. device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. Returns A 1-D tensor of size (window_length,)(\text{window\_length},) containing the window Return type Tensor
torch.generated.torch.hamming_window#torch.hamming_window
torch.hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor Hann window function. w[n]=12[1−cos⁡(2πnN−1)]=sin⁡2(πnN−1),w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = \sin^2 \left( \frac{\pi n}{N - 1} \right), where NN is the full window size. The input window_length is a positive integer controlling the returned window size. periodic flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like torch.stft(). Therefore, if periodic is true, the NN in above formula is in fact window_length+1\text{window\_length} + 1 . Also, we always have torch.hann_window(L, periodic=True) equal to torch.hann_window(L + 1, periodic=False)[:-1]). Note If window_length =1=1 , the returned window contains a single value 1. Parameters window_length (int) – the size of returned window periodic (bool, optional) – If True, returns a window to be used as periodic function. If False, return a symmetric window. Keyword Arguments dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()). Only floating point types are supported. layout (torch.layout, optional) – the desired layout of returned window tensor. Only torch.strided (dense layout) is supported. device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False. Returns A 1-D tensor of size (window_length,)(\text{window\_length},) containing the window Return type Tensor
torch.generated.torch.hann_window#torch.hann_window
torch.heaviside(input, values, *, out=None) → Tensor Computes the Heaviside step function for each element in input. The Heaviside step function is defined as: heaviside(input,values)={0,if input < 0values,if input == 01,if input > 0\text{{heaviside}}(input, values) = \begin{cases} 0, & \text{if input < 0}\\ values, & \text{if input == 0}\\ 1, & \text{if input > 0} \end{cases} Parameters input (Tensor) – the input tensor. values (Tensor) – The values to use where input is zero. Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> input = torch.tensor([-1.5, 0, 2.0]) >>> values = torch.tensor([0.5]) >>> torch.heaviside(input, values) tensor([0.0000, 0.5000, 1.0000]) >>> values = torch.tensor([1.2, -2.0, 3.5]) >>> torch.heaviside(input, values) tensor([0., -2., 1.])
torch.generated.torch.heaviside#torch.heaviside
torch.histc(input, bins=100, min=0, max=0, *, out=None) → Tensor Computes the histogram of a tensor. The elements are sorted into equal width bins between min and max. If min and max are both zero, the minimum and maximum values of the data are used. Elements lower than min and higher than max are ignored. Parameters input (Tensor) – the input tensor. bins (int) – number of histogram bins min (int) – lower end of the range (inclusive) max (int) – upper end of the range (inclusive) Keyword Arguments out (Tensor, optional) – the output tensor. Returns Histogram represented as a tensor Return type Tensor Example: >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) tensor([ 0., 2., 1., 0.])
torch.generated.torch.histc#torch.histc
torch.hspmm(mat1, mat2, *, out=None) → Tensor Performs a matrix multiplication of a sparse COO matrix mat1 and a strided matrix mat2. The result is a (1 + 1)-dimensional hybrid COO matrix. Parameters mat1 (Tensor) – the first sparse matrix to be matrix multiplied mat2 (Tensor) – the second strided matrix to be matrix multiplied Keyword Arguments {out} –
torch.sparse#torch.hspmm
torch.hstack(tensors, *, out=None) → Tensor Stack tensors in sequence horizontally (column wise). This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. Parameters tensors (sequence of Tensors) – sequence of tensors to concatenate Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.tensor([1, 2, 3]) >>> b = torch.tensor([4, 5, 6]) >>> torch.hstack((a,b)) tensor([1, 2, 3, 4, 5, 6]) >>> a = torch.tensor([[1],[2],[3]]) >>> b = torch.tensor([[4],[5],[6]]) >>> torch.hstack((a,b)) tensor([[1, 4], [2, 5], [3, 6]])
torch.generated.torch.hstack#torch.hstack
torch.hub Pytorch Hub is a pre-trained model repository designed to facilitate research reproducibility. Publishing models Pytorch Hub supports publishing pre-trained models(model definitions and pre-trained weights) to a github repository by adding a simple hubconf.py file; hubconf.py can have multiple entrypoints. Each entrypoint is defined as a python function (example: a pre-trained model you want to publish). def entrypoint_name(*args, **kwargs): # args & kwargs are optional, for models which take positional/keyword arguments. ... How to implement an entrypoint? Here is a code snippet specifies an entrypoint for resnet18 model if we expand the implementation in pytorch/vision/hubconf.py. In most case importing the right function in hubconf.py is sufficient. Here we just want to use the expanded version as an example to show how it works. You can see the full script in pytorch/vision repo dependencies = ['torch'] from torchvision.models.resnet import resnet18 as _resnet18 # resnet18 is the name of entrypoint def resnet18(pretrained=False, **kwargs): """ # This docstring shows up in hub.help() Resnet18 model pretrained (bool): kwargs, load pretrained weights into the model """ # Call the model, load pretrained weights model = _resnet18(pretrained=pretrained, **kwargs) return model dependencies variable is a list of package names required to load the model. Note this might be slightly different from dependencies required for training a model. args and kwargs are passed along to the real callable function. Docstring of the function works as a help message. It explains what does the model do and what are the allowed positional/keyword arguments. It’s highly recommended to add a few examples here. Entrypoint function can either return a model(nn.module), or auxiliary tools to make the user workflow smoother, e.g. tokenizers. Callables prefixed with underscore are considered as helper functions which won’t show up in torch.hub.list(). Pretrained weights can either be stored locally in the github repo, or loadable by torch.hub.load_state_dict_from_url(). If less than 2GB, it’s recommended to attach it to a project release and use the url from the release. In the example above torchvision.models.resnet.resnet18 handles pretrained, alternatively you can put the following logic in the entrypoint definition. if pretrained: # For checkpoint saved in local github repo, e.g. <RELATIVE_PATH_TO_CHECKPOINT>=weights/save.pth dirname = os.path.dirname(__file__) checkpoint = os.path.join(dirname, <RELATIVE_PATH_TO_CHECKPOINT>) state_dict = torch.load(checkpoint) model.load_state_dict(state_dict) # For checkpoint saved elsewhere checkpoint = 'https://download.pytorch.org/models/resnet18-5c106cde.pth' model.load_state_dict(torch.hub.load_state_dict_from_url(checkpoint, progress=False)) Important Notice The published models should be at least in a branch/tag. It can’t be a random commit. Loading models from Hub Pytorch Hub provides convenient APIs to explore all available models in hub through torch.hub.list(), show docstring and examples through torch.hub.help() and load the pre-trained models using torch.hub.load(). torch.hub.list(github, force_reload=False) [source] List all entrypoints available in github hubconf. Parameters github (string) – a string with format “repo_owner/repo_name[:tag_name]” with an optional tag/branch. The default branch is master if not specified. Example: ‘pytorch/vision[:hub]’ force_reload (bool, optional) – whether to discard the existing cache and force a fresh download. Default is False. Returns a list of available entrypoint names Return type entrypoints Example >>> entrypoints = torch.hub.list('pytorch/vision', force_reload=True) torch.hub.help(github, model, force_reload=False) [source] Show the docstring of entrypoint model. Parameters github (string) – a string with format <repo_owner/repo_name[:tag_name]> with an optional tag/branch. The default branch is master if not specified. Example: ‘pytorch/vision[:hub]’ model (string) – a string of entrypoint name defined in repo’s hubconf.py force_reload (bool, optional) – whether to discard the existing cache and force a fresh download. Default is False. Example >>> print(torch.hub.help('pytorch/vision', 'resnet18', force_reload=True)) torch.hub.load(repo_or_dir, model, *args, **kwargs) [source] Load a model from a github repo or a local directory. Note: Loading a model is the typical use case, but this can also be used to for loading other objects such as tokenizers, loss functions, etc. If source is 'github', repo_or_dir is expected to be of the form repo_owner/repo_name[:tag_name] with an optional tag/branch. If source is 'local', repo_or_dir is expected to be a path to a local directory. Parameters repo_or_dir (string) – repo name (repo_owner/repo_name[:tag_name]), if source = 'github'; or a path to a local directory, if source = 'local'. model (string) – the name of a callable (entrypoint) defined in the repo/dir’s hubconf.py. *args (optional) – the corresponding args for callable model. source (string, optional) – 'github' | 'local'. Specifies how repo_or_dir is to be interpreted. Default is 'github'. force_reload (bool, optional) – whether to force a fresh download of the github repo unconditionally. Does not have any effect if source = 'local'. Default is False. verbose (bool, optional) – If False, mute messages about hitting local caches. Note that the message about first download cannot be muted. Does not have any effect if source = 'local'. Default is True. **kwargs (optional) – the corresponding kwargs for callable model. Returns The output of the model callable when called with the given *args and **kwargs. Example >>> # from a github repo >>> repo = 'pytorch/vision' >>> model = torch.hub.load(repo, 'resnet50', pretrained=True) >>> # from a local directory >>> path = '/some/local/path/pytorch/vision' >>> model = torch.hub.load(path, 'resnet50', pretrained=True) torch.hub.download_url_to_file(url, dst, hash_prefix=None, progress=True) [source] Download object at the given URL to a local path. Parameters url (string) – URL of the object to download dst (string) – Full path where object will be saved, e.g. /tmp/temporary_file hash_prefix (string, optional) – If not None, the SHA256 downloaded file should start with hash_prefix. Default: None progress (bool, optional) – whether or not to display a progress bar to stderr Default: True Example >>> torch.hub.download_url_to_file('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth', '/tmp/temporary_file') torch.hub.load_state_dict_from_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None) [source] Loads the Torch serialized object at the given URL. If downloaded file is a zip file, it will be automatically decompressed. If the object is already present in model_dir, it’s deserialized and returned. The default value of model_dir is <hub_dir>/checkpoints where hub_dir is the directory returned by get_dir(). Parameters url (string) – URL of the object to download model_dir (string, optional) – directory in which to save the object map_location (optional) – a function or a dict specifying how to remap storage locations (see torch.load) progress (bool, optional) – whether or not to display a progress bar to stderr. Default: True check_hash (bool, optional) – If True, the filename part of the URL should follow the naming convention filename-<sha256>.ext where <sha256> is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. Default: False file_name (string, optional) – name for the downloaded file. Filename from url will be used if not set. Example >>> state_dict = torch.hub.load_state_dict_from_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth') Running a loaded model: Note that *args and **kwargs in torch.hub.load() are used to instantiate a model. After you have loaded a model, how can you find out what you can do with the model? A suggested workflow is dir(model) to see all available methods of the model. help(model.foo) to check what arguments model.foo takes to run To help users explore without referring to documentation back and forth, we strongly recommend repo owners make function help messages clear and succinct. It’s also helpful to include a minimal working example. Where are my downloaded models saved? The locations are used in the order of Calling hub.set_dir(<PATH_TO_HUB_DIR>) $TORCH_HOME/hub, if environment variable TORCH_HOME is set. $XDG_CACHE_HOME/torch/hub, if environment variable XDG_CACHE_HOME is set. ~/.cache/torch/hub torch.hub.get_dir() [source] Get the Torch Hub cache directory used for storing downloaded models & weights. If set_dir() is not called, default path is $TORCH_HOME/hub where environment variable $TORCH_HOME defaults to $XDG_CACHE_HOME/torch. $XDG_CACHE_HOME follows the X Design Group specification of the Linux filesystem layout, with a default value ~/.cache if the environment variable is not set. torch.hub.set_dir(d) [source] Optionally set the Torch Hub directory used to save downloaded models & weights. Parameters d (string) – path to a local folder to save downloaded models & weights. Caching logic By default, we don’t clean up files after loading it. Hub uses the cache by default if it already exists in the directory returned by get_dir(). Users can force a reload by calling hub.load(..., force_reload=True). This will delete the existing github folder and downloaded weights, reinitialize a fresh download. This is useful when updates are published to the same branch, users can keep up with the latest release. Known limitations: Torch hub works by importing the package as if it was installed. There’re some side effects introduced by importing in Python. For example, you can see new items in Python caches sys.modules and sys.path_importer_cache which is normal Python behavior. A known limitation that worth mentioning here is user CANNOT load two different branches of the same repo in the same python process. It’s just like installing two packages with the same name in Python, which is not good. Cache might join the party and give you surprises if you actually try that. Of course it’s totally fine to load them in separate processes.
torch.hub
torch.hub.download_url_to_file(url, dst, hash_prefix=None, progress=True) [source] Download object at the given URL to a local path. Parameters url (string) – URL of the object to download dst (string) – Full path where object will be saved, e.g. /tmp/temporary_file hash_prefix (string, optional) – If not None, the SHA256 downloaded file should start with hash_prefix. Default: None progress (bool, optional) – whether or not to display a progress bar to stderr Default: True Example >>> torch.hub.download_url_to_file('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth', '/tmp/temporary_file')
torch.hub#torch.hub.download_url_to_file
torch.hub.get_dir() [source] Get the Torch Hub cache directory used for storing downloaded models & weights. If set_dir() is not called, default path is $TORCH_HOME/hub where environment variable $TORCH_HOME defaults to $XDG_CACHE_HOME/torch. $XDG_CACHE_HOME follows the X Design Group specification of the Linux filesystem layout, with a default value ~/.cache if the environment variable is not set.
torch.hub#torch.hub.get_dir
torch.hub.help(github, model, force_reload=False) [source] Show the docstring of entrypoint model. Parameters github (string) – a string with format <repo_owner/repo_name[:tag_name]> with an optional tag/branch. The default branch is master if not specified. Example: ‘pytorch/vision[:hub]’ model (string) – a string of entrypoint name defined in repo’s hubconf.py force_reload (bool, optional) – whether to discard the existing cache and force a fresh download. Default is False. Example >>> print(torch.hub.help('pytorch/vision', 'resnet18', force_reload=True))
torch.hub#torch.hub.help
torch.hub.list(github, force_reload=False) [source] List all entrypoints available in github hubconf. Parameters github (string) – a string with format “repo_owner/repo_name[:tag_name]” with an optional tag/branch. The default branch is master if not specified. Example: ‘pytorch/vision[:hub]’ force_reload (bool, optional) – whether to discard the existing cache and force a fresh download. Default is False. Returns a list of available entrypoint names Return type entrypoints Example >>> entrypoints = torch.hub.list('pytorch/vision', force_reload=True)
torch.hub#torch.hub.list
torch.hub.load(repo_or_dir, model, *args, **kwargs) [source] Load a model from a github repo or a local directory. Note: Loading a model is the typical use case, but this can also be used to for loading other objects such as tokenizers, loss functions, etc. If source is 'github', repo_or_dir is expected to be of the form repo_owner/repo_name[:tag_name] with an optional tag/branch. If source is 'local', repo_or_dir is expected to be a path to a local directory. Parameters repo_or_dir (string) – repo name (repo_owner/repo_name[:tag_name]), if source = 'github'; or a path to a local directory, if source = 'local'. model (string) – the name of a callable (entrypoint) defined in the repo/dir’s hubconf.py. *args (optional) – the corresponding args for callable model. source (string, optional) – 'github' | 'local'. Specifies how repo_or_dir is to be interpreted. Default is 'github'. force_reload (bool, optional) – whether to force a fresh download of the github repo unconditionally. Does not have any effect if source = 'local'. Default is False. verbose (bool, optional) – If False, mute messages about hitting local caches. Note that the message about first download cannot be muted. Does not have any effect if source = 'local'. Default is True. **kwargs (optional) – the corresponding kwargs for callable model. Returns The output of the model callable when called with the given *args and **kwargs. Example >>> # from a github repo >>> repo = 'pytorch/vision' >>> model = torch.hub.load(repo, 'resnet50', pretrained=True) >>> # from a local directory >>> path = '/some/local/path/pytorch/vision' >>> model = torch.hub.load(path, 'resnet50', pretrained=True)
torch.hub#torch.hub.load
torch.hub.load_state_dict_from_url(url, model_dir=None, map_location=None, progress=True, check_hash=False, file_name=None) [source] Loads the Torch serialized object at the given URL. If downloaded file is a zip file, it will be automatically decompressed. If the object is already present in model_dir, it’s deserialized and returned. The default value of model_dir is <hub_dir>/checkpoints where hub_dir is the directory returned by get_dir(). Parameters url (string) – URL of the object to download model_dir (string, optional) – directory in which to save the object map_location (optional) – a function or a dict specifying how to remap storage locations (see torch.load) progress (bool, optional) – whether or not to display a progress bar to stderr. Default: True check_hash (bool, optional) – If True, the filename part of the URL should follow the naming convention filename-<sha256>.ext where <sha256> is the first eight or more digits of the SHA256 hash of the contents of the file. The hash is used to ensure unique names and to verify the contents of the file. Default: False file_name (string, optional) – name for the downloaded file. Filename from url will be used if not set. Example >>> state_dict = torch.hub.load_state_dict_from_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')
torch.hub#torch.hub.load_state_dict_from_url
torch.hub.set_dir(d) [source] Optionally set the Torch Hub directory used to save downloaded models & weights. Parameters d (string) – path to a local folder to save downloaded models & weights.
torch.hub#torch.hub.set_dir
torch.hypot(input, other, *, out=None) → Tensor Given the legs of a right triangle, return its hypotenuse. outi=inputi2+otheri2\text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} The shapes of input and other must be broadcastable. Parameters input (Tensor) – the first input tensor other (Tensor) – the second input tensor Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) tensor([5.0000, 5.6569, 6.4031])
torch.generated.torch.hypot#torch.hypot
torch.i0(input, *, out=None) → Tensor Computes the zeroth order modified Bessel function of the first kind for each element of input. outi=I0(inputi)=∑k=0∞(inputi2/4)k(k!)2\text{out}_{i} = I_0(\text{input}_{i}) = \sum_{k=0}^{\infty} \frac{(\text{input}_{i}^2/4)^k}{(k!)^2} Parameters input (Tensor) – the input tensor Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> torch.i0(torch.arange(5, dtype=torch.float32)) tensor([ 1.0000, 1.2661, 2.2796, 4.8808, 11.3019])
torch.generated.torch.i0#torch.i0
torch.igamma(input, other, *, out=None) → Tensor Computes the regularized lower incomplete gamma function: outi=1Γ(inputi)∫0otheritinputi−1e−tdt\text{out}_{i} = \frac{1}{\Gamma(\text{input}_i)} \int_0^{\text{other}_i} t^{\text{input}_i-1} e^{-t} dt where both inputi\text{input}_i and otheri\text{other}_i are weakly positive and at least one is strictly positive. If both are zero or either is negative then outi=nan\text{out}_i=\text{nan} . Γ(⋅)\Gamma(\cdot) in the equation above is the gamma function, Γ(inputi)=∫0∞t(inputi−1)e−tdt.\Gamma(\text{input}_i) = \int_0^\infty t^{(\text{input}_i-1)} e^{-t} dt. See torch.igammac() and torch.lgamma() for related functions. Supports broadcasting to a common shape and float inputs. Note The backward pass with respect to input is not yet supported. Please open an issue on PyTorch’s Github to request it. Parameters input (Tensor) – the first non-negative input tensor other (Tensor) – the second non-negative input tensor Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a1 = torch.tensor([4.0]) >>> a2 = torch.tensor([3.0, 4.0, 5.0]) >>> a = torch.igammac(a1, a2) tensor([0.3528, 0.5665, 0.7350]) tensor([0.3528, 0.5665, 0.7350]) >>> b = torch.igamma(a1, a2) + torch.igammac(a1, a2) tensor([1., 1., 1.])
torch.generated.torch.igamma#torch.igamma
torch.igammac(input, other, *, out=None) → Tensor Computes the regularized upper incomplete gamma function: outi=1Γ(inputi)∫otheri∞tinputi−1e−tdt\text{out}_{i} = \frac{1}{\Gamma(\text{input}_i)} \int_{\text{other}_i}^{\infty} t^{\text{input}_i-1} e^{-t} dt where both inputi\text{input}_i and otheri\text{other}_i are weakly positive and at least one is strictly positive. If both are zero or either is negative then outi=nan\text{out}_i=\text{nan} . Γ(⋅)\Gamma(\cdot) in the equation above is the gamma function, Γ(inputi)=∫0∞t(inputi−1)e−tdt.\Gamma(\text{input}_i) = \int_0^\infty t^{(\text{input}_i-1)} e^{-t} dt. See torch.igamma() and torch.lgamma() for related functions. Supports broadcasting to a common shape and float inputs. Note The backward pass with respect to input is not yet supported. Please open an issue on PyTorch’s Github to request it. Parameters input (Tensor) – the first non-negative input tensor other (Tensor) – the second non-negative input tensor Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> a1 = torch.tensor([4.0]) >>> a2 = torch.tensor([3.0, 4.0, 5.0]) >>> a = torch.igammac(a1, a2) tensor([0.6472, 0.4335, 0.2650]) >>> b = torch.igamma(a1, a2) + torch.igammac(a1, a2) tensor([1., 1., 1.])
torch.generated.torch.igammac#torch.igammac
torch.imag(input) → Tensor Returns a new tensor containing imaginary values of the self tensor. The returned tensor and self share the same underlying storage. Warning imag() is only supported for tensors with complex dtypes. Parameters input (Tensor) – the input tensor. Example:: >>> x=torch.randn(4, dtype=torch.cfloat) >>> x tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) >>> x.imag tensor([ 0.3553, -0.7896, -0.0633, -0.8119])
torch.generated.torch.imag#torch.imag
torch.index_select(input, dim, index, *, out=None) → Tensor Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a LongTensor. The returned tensor has the same number of dimensions as the original tensor (input). The dimth dimension has the same size as the length of index; other dimensions have the same size as in the original tensor. Note The returned tensor does not use the same storage as the original tensor. If out has a different shape than expected, we silently change it to the correct shape, reallocating the underlying storage if necessary. Parameters input (Tensor) – the input tensor. dim (int) – the dimension in which we index index (IntTensor or LongTensor) – the 1-D tensor containing the indices to index Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> x = torch.randn(3, 4) >>> x tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], [-0.4664, 0.2647, -0.1228, -1.1068], [-1.1734, -0.6571, 0.7230, -0.6004]]) >>> indices = torch.tensor([0, 2]) >>> torch.index_select(x, 0, indices) tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], [-1.1734, -0.6571, 0.7230, -0.6004]]) >>> torch.index_select(x, 1, indices) tensor([[ 0.1427, -0.5414], [-0.4664, -0.1228], [-1.1734, 0.7230]])
torch.generated.torch.index_select#torch.index_select
torch.initial_seed() [source] Returns the initial seed for generating random numbers as a Python long.
torch.generated.torch.initial_seed#torch.initial_seed
torch.inner(input, other, *, out=None) → Tensor Computes the dot product for 1D tensors. For higher dimensions, sums the product of elements from input and other along their last dimension. Note If either input or other is a scalar, the result is equivalent to torch.mul(input, other). If both input and other are non-scalars, the size of their last dimension must match and the result is equivalent to torch.tensordot(input, other, dims=([-1], [-1])) Parameters input (Tensor) – First input tensor other (Tensor) – Second input tensor Keyword Arguments out (Tensor, optional) – Optional output tensor to write result into. The output shape is input.shape[:-1] + other.shape[:-1]. Example: # Dot product >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) tensor(7) # Multidimensional input tensors >>> a = torch.randn(2, 3) >>> a tensor([[0.8173, 1.0874, 1.1784], [0.3279, 0.1234, 2.7894]]) >>> b = torch.randn(2, 4, 3) >>> b tensor([[[-0.4682, -0.7159, 0.1506], [ 0.4034, -0.3657, 1.0387], [ 0.9892, -0.6684, 0.1774], [ 0.9482, 1.3261, 0.3917]], [[ 0.4537, 0.7493, 1.1724], [ 0.2291, 0.5749, -0.2267], [-0.7920, 0.3607, -0.3701], [ 1.3666, -0.5850, -1.7242]]]) >>> torch.inner(a, b) tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], [ 2.5671, 0.5452, -0.6912, -1.5509]], [[ 0.1782, 2.9843, 0.7366, 1.5672], [ 3.5115, -0.4864, -1.2476, -4.4337]]]) # Scalar input >>> torch.inner(a, torch.tensor(2)) tensor([[1.6347, 2.1748, 2.3567], [0.6558, 0.2469, 5.5787]])
torch.generated.torch.inner#torch.inner
torch.inverse(input, *, out=None) → Tensor Takes the inverse of the square matrix input. input can be batches of 2D square tensors, in which case this function would return a tensor composed of individual inverses. Supports real and complex input. Note torch.inverse() is deprecated. Please use torch.linalg.inv() instead. Note Irrespective of the original strides, the returned tensors will be transposed, i.e. with strides like input.contiguous().transpose(-2, -1).stride() Parameters input (Tensor) – the input tensor of size (∗,n,n)(*, n, n) where * is zero or more batch dimensions Keyword Arguments out (Tensor, optional) – the output tensor. Examples: >>> x = torch.rand(4, 4) >>> y = torch.inverse(x) >>> z = torch.mm(x, y) >>> z tensor([[ 1.0000, -0.0000, -0.0000, 0.0000], [ 0.0000, 1.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 1.0000, 0.0000], [ 0.0000, -0.0000, -0.0000, 1.0000]]) >>> torch.max(torch.abs(z - torch.eye(4))) # Max non-zero tensor(1.1921e-07) >>> # Batched inverse example >>> x = torch.randn(2, 3, 4, 4) >>> y = torch.inverse(x) >>> z = torch.matmul(x, y) >>> torch.max(torch.abs(z - torch.eye(4).expand_as(x))) # Max non-zero tensor(1.9073e-06) >>> x = torch.rand(4, 4, dtype=torch.cdouble) >>> y = torch.inverse(x) >>> z = torch.mm(x, y) >>> z tensor([[ 1.0000e+00+0.0000e+00j, -1.3878e-16+3.4694e-16j, 5.5511e-17-1.1102e-16j, 0.0000e+00-1.6653e-16j], [ 5.5511e-16-1.6653e-16j, 1.0000e+00+6.9389e-17j, 2.2204e-16-1.1102e-16j, -2.2204e-16+1.1102e-16j], [ 3.8858e-16-1.2490e-16j, 2.7756e-17+3.4694e-17j, 1.0000e+00+0.0000e+00j, -4.4409e-16+5.5511e-17j], [ 4.4409e-16+5.5511e-16j, -3.8858e-16+1.8041e-16j, 2.2204e-16+0.0000e+00j, 1.0000e+00-3.4694e-16j]], dtype=torch.complex128) >>> torch.max(torch.abs(z - torch.eye(4, dtype=torch.cdouble))) # Max non-zero tensor(7.5107e-16, dtype=torch.float64)
torch.generated.torch.inverse#torch.inverse