/usr/local/lib64/python3.6/site-packages/torch/fx/__pycache__
NameSizeModeActions
annotate.cpython-36.pyc7860644editdlrm
graph.cpython-36.pyc409320644editdlrm
graph_module.cpython-36.pyc209680644editdlrm
immutable_collections.cpython-36.pyc14320644editdlrm
interpreter.cpython-36.pyc176600644editdlrm
node.cpython-36.pyc221700644editdlrm
operator_schemas.cpython-36.pyc130440644editdlrm
proxy.cpython-36.pyc144270644editdlrm
subgraph_rewriter.cpython-36.pyc112570644editdlrm
tensor_type.cpython-36.pyc37390644editdlrm
_compatibility.cpython-36.pyc11460644editdlrm
_pytree.cpython-36.pyc26510644editdlrm
_symbolic_trace.cpython-36.pyc317270644editdlrm
__init__.cpython-36.pyc40180644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/fx/__pycache__/interpreter.cpython-36.pyc (17660B)
3 EgmH@sddlmZddlmZddlmZmZmZmZm Z ddl m Z ddl m Z ddlmZddlmZmZmZmZmZmZmZed d Gd d d Zed d Gd ddeZdS)) GraphModule)Graph)ArgumentNodeTargetmap_arg map_aggregate)Proxy)Tracer) compatibility)AnyDictIteratorListOptionalTupleUnionT)is_backward_compatiblec@seZdZdZeddd&eedddZeddddee e e fe d d d Z edde e d d dZ edddeedfe ee fe dddZedddeedfe ee fe dddZedddeedfe ee fe dddZedddeedfe ee fe dddZedddeedfe ee fe dddZedddeedfe ee fe dddZeddeddd Zedde eee fd d!d"Zeddee ed#d$d%ZdS)' Interpretera 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()) Args: module (GraphModule): The module to be executed garbage_collect_values (bool): Whether to delete values after their last use within the Module's execution. This ensures optimal memory usage during execution. This can be disabled to, for example, examine all of the intermediate values in the execution by looking at the ``Interpreter.env`` attribute. T)r)modulegarbage_collect_valuescst|tst|_tjj_i_|_jrii_ t t dfdd xBt jj j D]0tjfddtjfddqfWdS)N)nusercs(|kr$||<jj|gj|dS)N)user_to_last_uses setdefaultappend)rr)node_to_last_useself@/usr/local/lib64/python3.6/site-packages/torch/fx/interpreter.pyregister_last_usesQsz0Interpreter.__init__..register_last_usescs |S)Nr)r)noder!rr Wsz&Interpreter.__init__..cs |S)Nr)r)r"r!rr r#Xs) isinstancerAssertionErrorrdictZ named_modulesZ submodulesenvrrrreversedgraphnodesrargskwargs)rrrr)r"rr!rr __init__@szInterpreter.__init__N) initial_env)r.returncGs|r|ni|_t||_xl|jjjD]^}||jkr4q$|j||j|<|jrjx|jj |gD] }|j|=qZW|j dkr$|j|}|Sq$WdS)a: Run `module` via interpretation and return the result. Args: *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: Any: The value returned from executing the Module outputN) r'iter args_iterrr)r*run_noderrgetop)rr.r+r"Z to_deleteZ output_valrrr runZs     zInterpreter.run)rr/cCs@|j|\}}t|tstt|ts*tt||j|j||S)aB 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`` Args: n (Node): The Node to execute Returns: Any: The result of executing ``n`` )fetch_args_kwargs_from_envr$tupler%r&getattrr5target)rrr+r,rrr r3szInterpreter.run_noder.)r:r+r,r/cCs0t|tst|jdr"t|jSt|jSdS)a 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. Args: 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: Any: The argument value that was retrieved. *N)r$strr% startswithlistr2next)rr:r+r,rrr placeholders  zInterpreter.placeholdercCst|tst|j|S)a2 Execute a ``get_attr`` node. Will retrieve an attribute value from the ``Module`` hierarchy of ``self.module``. Args: 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 of the attribute that was retrieved )r$r<r% fetch_attr)rr:r+r,rrr get_attrszInterpreter.get_attrcCst|t st|||S)a Execute a ``call_function`` node and return the result. Args: 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 )r$r<r%)rr:r+r,rrr call_functionszInterpreter.call_functioncCs&|^}}t|tstt||||S)a Execute a ``call_method`` node and return the result. Args: 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 )r$r<r%r9)rr:r+r,Zself_objZ args_tailrrr call_methodszInterpreter.call_methodcCs"t|tst|j|}|||S)a Execute a ``call_module`` node and return the result. Args: 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 )r$r<r%rA)rr:r+r,submodrrr call_modules zInterpreter.call_modulecCs|dS)a6 Execute an ``output`` node. This really just retrieves the value referenced by the ``output`` node and returns it. Args: 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 return value referenced by the output node r r)rr:r+r,rrr r0szInterpreter.output)r:cCsZ|jd}|j}xDt|D]8\}}t||sHtddj|d|t||}qW|S)z Fetch an attribute from the ``Module`` hierarchy of ``self.module``. Args: target (str): The fully-qualfiied name of the attribute to fetch Return: Any: The value of the attribute. .z#Node referenced nonexistent target N)splitr enumeratehasattr RuntimeErrorjoinr9)rr:Z target_atomsZattr_itriZatomrrr rAs  zInterpreter.fetch_attrcCs@|j|j|}t|tst|j|j|}t|ts8t||fS)aP Fetch the concrete values of ``args`` and ``kwargs`` of node ``n`` from the current execution environment. Args: n (Node): The node for which ``args`` and ``kwargs`` should be fetched. Return: Tuple[Tuple, Dict]: ``args`` and ``kwargs`` with concrete values for ``n``. )map_nodes_to_valuesr+r$r8r%r,r&)rrr+r,rrr r7*s z&Interpreter.fetch_args_kwargs_from_env)r+rr/cs ttdfdd }t||S)aV Recursively descend through ``args`` and look up the concrete value for each ``Node`` in the current execution environment. Args: 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. )n_argr/cs*|jkr tdd|dj|S)NzNode z referenced nonexistent value z*! Run Graph.lint() to diagnose such issues)r'rK)rO)rrrr load_argGs z1Interpreter.map_nodes_to_values..load_arg)rr r)rr+rrPr)rrr rN<s zInterpreter.map_nodes_to_values)T)__name__ __module__ __qualname____doc__r rboolr-rrrr r6r3rrr<r@rBrCrDrFr0rAr7rNrrrr r s26$'&&&&&&rcseZdZdZeddfddZedddeedfee e fe dd d Z edddeedfee e fe dd d Z edddeedfee e fe dd dZedddeedfee e fe dddZeddedfdd ZZS) Transformera9 ``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()) Args: module (GraphModule): The ``Module`` to be transformed. T)rcs<tj|t|_Gdddt}||j|_||j_dS)Ncs0eZdZedfdd ZedddZZS)z/Transformer.__init__..TransformerTracer)r)cstj||_dS)N)superr-r))rr)) __class__rr r-|s z8Transformer.__init__..TransformerTracer.__init__)r/cSsdS)NTr)r___rrr is_leaf_modulesz>Transformer.__init__..TransformerTracer.is_leaf_module)rQrRrSrr-rUr[ __classcell__rr)rXr TransformerTracer{sr])rWr-r new_graphr tracerroot)rrr])rXrr r-vs   zTransformer.__init__r.)r:r+r,r/cCs"t|tstt|jj||jS)a Execute a ``placeholder`` node. In ``Transformer``, this is overridden to insert a new ``placeholder`` into the output graph. Args: 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 )r$r<r%r r^r@r_)rr:r+r,rrr r@szTransformer.placeholdercCs"t|tstt|jj||jS)a Execute a ``get_attr`` node. In ``Transformer``, this is overridden to insert a new ``get_attr`` node into the output graph. Args: 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 )r$r<r%r r^rBr_)rr:r+r,rrr rBszTransformer.get_attrcCs,t|tst|j|}|jj||j||S)N)r$r<r%rAr_rFZforward)rr:r+r,rErrr rFs zTransformer.call_modulecCs|jjd|||S)NrC)r_Z create_proxy)rr:r+r,rrr rCszTransformer.call_function)r/csJtj}|dk r.strip_proxy) rWr6rrr r r^r0rrr)rresultrb)rXrr transforms  zTransformer.transform)rQrRrSrTr r-rrrr<r r r@rBrFrCrrdr\rr)rXr rVNs&&&&&rVN)Z graph_modulerr)rr"rrrrrproxyr Z_symbolic_tracer Z_compatibilityr typingr rrrrrrrrVrrrr s     $G