/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__/graph.cpython-36.pyc (40932B)
3 Egʿ@sUddlmZmZmZmZmZmZddljj Z ddl m Z ddl mZddlmZmZmZmZmZmZmZmZmZmZmZddlmZddlmZddlZddl Z ddl!Z!ddl"Z"ddl#Z#ddl$Z$ddl%Z%erdd l&m'Z'dd l(m)Z)e*ee+ee,ee-ee.eiZ/Gd d d eZ0iZ1ee2e0f1e2e2ed ddZ3e3dde$j4e3dde$j5e3dde6de3dde e3dde j7e3dde e3dde e2e8ddd Z9e2e2d!d"d#Z:ee8d$d%d&Z;Gd'd(d(Ze2e2e2d1d2d3Z?Gd4d5d5Z@Gd6d7d7ZAGd8d9d9eZBed)d*Gd:d;d;ZCdd?d@d@dAdBdCdDdEdFdGdHdIdJZDe+dKdLdMdNdOdPdQdRdSdT feDZEdS)U)NodeArgumentTargetmap_arg _type_repr_get_qualified_nameN)_pytree) compatibility) TYPE_CHECKINGCallableAnyListDict NamedTupleOptionalTupleSet FrozenSetType) dataclass)contextmanager) GraphModule)Tracerc@seZdZUdZeedS)_CustomBuiltinzAdditional objs that we add to every graph's globals. The repr() for some standard library objects is not valid Python code without an import. For common objects of this sort, we bundle them in the globals of every FX graph. N)__name__ __module__ __qualname____doc__str import_strr objr"r":/usr/local/lib64/python3.6/site-packages/torch/fx/graph.pyr s r)namer r!cCst||t|<dS)N)r_custom_builtins)r$r r!r"r"r#_register_custom_builtin/sr&infzfrom math import infnanzfrom math import nanZNoneTypezNoneType = type(None)torchz import torchdevicezfrom torch import device fx_pytreez$import torch.fx._pytree as fx_pytreepytreez$import torch.utils._pytree as pytree)xreturncCs|jdo|jdS)N__) startswithendswith)r-r"r"r# _is_magic<sr2)sr.cCsLg}d}x8|D]0}|r(|jr(|jd|j|j|j}qWdj|S)z Transforms the given string ``s`` to a Python-style variable name Examples: ``mod.snake_case`` -> ``mod.snake_case`` ``mod.pascalCase``-> ``mod.pascal_case`` ``mod.ALL_CAPS`` -> ``mod.all_caps`` F_)isupperappendlowerislowerjoin)r3charsZ prev_lowercr"r"r# _snake_case@s     r=)r!r.cCstt|dd}|dk r*|jdd}|dkSt|dd}|dk rp|dkrpx(ttjjgD]}t||d|krTdSqTWdS)Nr.rr)rTF)getattr partitionr)nnZ functional)r! module_name base_moduler$guessr"r"r#_is_from_torchSs  rEc@sPeZdZdZddZeeeedddZeeddd Z eee d d d Z d S) _NamespaceaA context for associating names uniquely with objects. The following invariants are enforced: - Each object gets a single name. - Each name is unique within a given namespace. - Names generated do not shadow builtins, unless the object is indeed that builtin. cCs0i|_t|_i|_tjd|_tjd|_dS)Nz[^0-9a-zA-Z_]+z (.*)_(\d+)$) _obj_to_nameset_unassociated_names _used_namesrecompile_illegal_char_regex_name_suffix_regex)selfr"r"r#__init__ks  z_Namespace.__init__) candidater!r.cCs|dk r||jkr|j|S|jjd|}|djr@d|}|jj|}|dkr^|}d}n|jdd\}}t|}|dkr|n |d|}|r|nd}x0||jks|j ||r|d7}|d|}qW|jj ||dkr|j j |n ||j|<|S)zCreate a unique name. Arguments: candidate: used as the basis for the unique name, relevant to the user. obj: If not None, an object that will be associated with the unique name. Nr4rr) rGrMsubisdigitrNmatchgroupintrJ_is_illegal_name setdefaultrIadd)rOrQr!rUbasenumZnum_strr"r"r# create_namess*       z_Namespace.create_name)r$r!cCs6||jkst||jkst||j|<|jj|dS)zpAssociate a unique name with an object. Neither `name` nor `obj` should be associated already. N)rGAssertionErrorrIremove)rOr$r!r"r"r#associate_name_with_objs z"_Namespace.associate_name_with_obj)r$r!r.cCs@|tjkrdS|tjkr&|tj|k S|tkr<|t|jk SdS)NTF)keywordkwlistbuiltins__dict__r%r!)rOr$r!r"r"r#rXs  z_Namespace._is_illegal_nameN) rrrrrPrrr r]r`boolrXr"r"r"r#rFcs & rFT)is_backward_compatiblec@s"eZdZUdZeeeefdS) PythonCodezZ Represents all the information necessary to exec or save a graph as Python code. N) rrrrrsrcrr globalsr"r"r"r#rgs rg.)argskwargsr.cCsJdjdd|D}djdd|jD}|rB|rB|d|S|pH|S)Nz, css|]}t|VqdS)N)repr).0ar"r"r# sz_format_args..css$|]\}}|dt|VqdS)z = N)rl)rmkvr"r"r#ros)r:items)rjrkZargs_sZkwargs_sr"r"r# _format_argss rs)r[targetr.cCsJ|jd}|}x6|D].}|js4d|d|d}q|d|}qW|S)Nr>zgetattr(z, "z"))split isidentifier)r[rtelemsrer"r"r#_format_targets  rzc@s$eZdZddZddZddZdS) _InsertPointcCs||_|j||_|_dS)N)graph_insert orig_insert)rOr|Z new_insertr"r"r#rPsz_InsertPoint.__init__cCsdS)Nr")rOr"r"r# __enter__sz_InsertPoint.__enter__cCs|j|j_dS)N)r~r|r})rOtypevaluetbr"r"r#__exit__sz_InsertPoint.__exit__N)rrrrPrrr"r"r"r#r{sr{c@s6eZdZd dedddZddZdd Zd d Zd S) _node_list_nextGraph)r| directioncCs|dks t||_||_dS)Nr_prev)rr)r^r|r)rOr|rr"r"r#rPs z_node_list.__init__cCs|jjS)N)r|_len)rOr"r"r#__len__sz_node_list.__len__ccsB|jj|j}}t||}x"||k r<|js0|Vt||}qWdS)N)r|_rootrr?_erased)rOrootrcurr"r"r#__iter__s   z_node_list.__iter__cCst|j|jdkrdndS)Nrr)rr|r)rOr"r"r# __reversed__sz_node_list.__reversed__N)r)rrrrrPrrrr"r"r"r#rsrc@s*eZdZUdZeeej e ej dS) _PyTreeInfoz= Contains extra info stored when we're using Pytrees N) rrrrrr orig_argsr,ZTreeSpecZin_specrout_specr"r"r"r#rs rc @s(eZdZdZedddRedeedddd Zed d Z e j edd d d Z ee dddZ edddSde eefddddZdTddddZedddUedeedVee edfeeeeedddZeddddZeddd d!Zeddedd"d#d$ZedddWeed%d&d'ZedddXeed%d(d)ZedddYeeeed*d+d,ZedddZeeeed-d.d/Zeddd[eeed\ee edfeeed0d1d2Zeddd]eeed^ee edfeeed3d4d5Zeddd_edefeed`ee edfeeed6d7d8Zeddd9d:feeegdfed;dd?d@Z!e"edAdBdCZ#eddee$dDdEdFZ%ee&e$dGdHdIZ'eddJdKZ(edddLdMZ)edddNdOZ*edddPdQZ+dS)braK ``Graph`` is the main data structure used in the FX Intermediate Representation. It consists of a series of ``Node`` s, each representing callsites (or other syntactic constructs). The list of ``Node`` s, taken together, constitute a valid Python function. For example, the following code .. code-block:: python import torch import torch.fx class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.param = torch.nn.Parameter(torch.rand(3, 4)) self.linear = torch.nn.Linear(4, 5) def forward(self, x): return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3) m = MyModule() gm = torch.fx.symbolic_trace(m) Will produce the following Graph:: print(gm.graph) .. code-block:: text graph(x): %linear_weight : [#users=1] = self.linear.weight %add_1 : [#users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {}) %linear_1 : [#users=1] = call_module[target=linear](args = (%add_1,), kwargs = {}) %relu_1 : [#users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {}) %sum_1 : [#users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1}) %topk_1 : [#users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {}) return topk_1 For the semantics of operations represented in the ``Graph``, please see :class:`Node`. T)rfNrr) owning_module tracer_clscCsNt|dddfi|_i|_|jj|_d|_t|_d|_||_ ||_ d|_ dS)z+ Construct an empty Graph. r5rrN) rrrJprependr}rrF_graph_namespace_owners_owning_module _tracer_cls _pytree_info)rOrrr"r"r#rP$s zGraph.__init__cCs|jS)z Return the module that owns this ``GraphModule``, if there is one, ``None`` if there is no owning module or if there are multiple owning modules. )r)rOr"r"r#r3szGraph.owning_module)modcCs&|r"|js|nd|_|jd7_dS)Nr)rr)rOrr"r"r#r<s)r.cCst|S)av 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. )r)rOr"r"r#nodesBs z Graph.nodesFzOptional[Argument])gval_mapr.cshxb|jD]X}|krq|jdkrHt|jdfdd}|s@|S||fS|j|fdd|<qWdS)aM Copy all nodes from a given graph into ``self``. Args: 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. outputrcs|S)Nr")n)rr"r#gsz"Graph.graph_copy..cs|S)Nr")r)rr"r#risN)roprrj node_copy)rOrrreturn_output_nodenodervr")rr# graph_copyQs  zGraph.graph_copycCsX|r|ni}t|jd}|j||dd}t|ts6t|\}}|j|t|ddd|S)a Explicitly implement __deepcopy__ to prevent excessive recursion depth from the default implementation. This uses graph_copy to copy the nodes in an iterative way, rather than recursive. It also populates the memoization table to prevent unnecessary copies (e.g. references to nodes or other parts of the Graph from a custom GraphModule implementation. )rT)rrrN) type_expr)rrr isinstancetupler^rr?)rOmemorZ output_valsZ output_valZold_output_valr"r"r# __deepcopy__ls  zGraph.__deepcopy__rr.)rrtrjrkr$rr.c Cs|d ks t|dkrfn|}|dkr(in|}t|ts>tdt|tsPtd |dk r\|n|j|}|jj|d}t|||||||}|jj|||j ||j d 7_ |S) a& Create a ``Node`` and add it to the ``Graph`` at the current insert-point. Note that the current insert-point can be set via :meth:`Graph.inserting_before` and :meth:`Graph.inserting_after`. Args: 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. call_function call_methodget_attr call_module placeholderrNzargs must be a tuplezkwargs must be a dictr)rrrrrr) r^rrdict_target_to_strrr]rr`r}r) rOrrtrjrkr$rrQrr"r"r# create_node|s  zGraph.create_nodecGstj|\}}|S)N)r,Z tree_flatten)rOrjZ flat_argsZ args_specr"r"r# flatten_inpsszGraph.flatten_inpscCs>|jdkr|St|ts|g}|jjdk s.ttj||jjS)N)rrlistrr^r,Ztree_unflatten)rOoutr"r"r#unflatten_outss   zGraph.unflatten_outs)to_eraser.cCst|jdkr2td|dt|jd|jd|jd|_|jd8_t|jdd }t|t slt ||_t|j d d }t|t st ||_ d S) z Erases a ``Node`` from the ``Graph``. Throws an exception if there are still users of that node in the ``Graph``. Args: to_erase (Node): The ``Node`` to erase from the ``Graph``. rzTried to erase Node z but it still had z users in the graph: !TrcSsdS)Nr")rr"r"r#rsz"Graph.erase_node..cSsdS)Nr")rr"r"r#rsN) lenusers RuntimeErrorZ_remove_from_listrrrrjrrr^rkr)rOrZnew_argsZ new_kwargsr"r"r# erase_nodes $zGraph.erase_node)rcCs2|dkr|j|jS|j|ks&tdt||jS)aSet 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 Args: 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__``. Nz&Node to insert before is not in graph.)inserting_afterrr|r^r{r)rOrr"r"r#inserting_befores zGraph.inserting_beforecCs2|dkr|j|jS|j|ks&tdt||jS)aSet 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 Args: 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__``. Nz%Node to insert after is not in graph.)rrr|r^r{r7)rOrr"r"r#rs zGraph.inserting_after)r$rr.cCs|jd||dS)a Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents a function input. Args: 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``. r)r)r)rOr$rr"r"r#rszGraph.placeholder)qualified_namerr.cCsDtjjttddd}|jr4||j| r4tjd|jd||dS)a Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the fetch of an attribute from the ``Module`` hierarchy. Args: 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``. )rrr.c Ss|jd\}}}y|j|}Wn&tk rDtjd|ddSXt||sTdSt||}t|tj j  rt|tj j  r||j krdSdS)Nr>zFailed to fetch module rFT) rpartition get_submoduleAttributeErrorwarningswarnhasattrr?rr)rAModule Parameter_buffers)rr module_pathr4r$Zsubmodresr"r"r#_get_attr_reference_exists1s   z2Graph.get_attr.._get_attr_reference_existsa Attempted to insert a get_attr Node with no underlying reference in the owning GraphModule! Call GraphModule.add_submodule to add the necessary submodule, GraphModule.add_parameter to add the necessary Parameter, or nn.Module.register_buffer to add the necessary bufferr)r) r)rArrrerrrr)rOrrrr"r"r#rs  zGraph.get_attr)rBrjrkrr.cCs4|jr |jj|dkr tjd|jd||||dS)a 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. Args: 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 :meth:`Graph.create_node`. NzAttempted to insert a call_module Node with no underlying reference in the owning GraphModule! Call GraphModule.add_submodule to add the necessary submoduler)r)rrrrr)rOrBrjrkrr"r"r#rSs$ zGraph.call_module) method_namerjrkrr.cCs|jd||||dS)aj 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``. Args: 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 :meth:`Graph.create_node`. r)r)r)rOrrjrkrr"r"r#rs!zGraph.call_method) the_functionrjrkrr.cCs|jd||||dS)a/ Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node represents a call to a Python callable, specified by ``the_function``. ``the_function`` can be Args: the_function (Callable[..., Any]): The function to be called. Can be any PyTorch operator, Python function, or member of the ``builtins`` or ``operator`` namespaces. args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed to the called function. kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed to the called function type_expr (Optional[Any]): an optional type annotation representing the Python type the output of this node will have. Returns The newly created and inserted ``call_function`` node. .. note:: The same insertion point and type expression rules apply for this method as :meth:`Graph.create_node`. r)r)r)rOrrjrkrr"r"r#rs"zGraph.call_functioncCs|S)Nr")r-r"r"r#rszGraph.)r arg_transformr.cCsbt|j|}t|j|}t|ts&tt|ts4t|j|j|j |||j |j }t j |j |_ |S)ay 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]) Args: 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``. )rrjrkrrr^rrrrtr$rcopymeta)rOrrrjrkZ result_noder"r"r#rs  zGraph.node_copy)resultrcCs|jdd|f|dS)a5 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. Args: 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``. r)rrtrjr)r)rOrrr"r"r#rsz Graph.output)rtr.cCsBt|r|j}n&t|tst|}t|r6|dd}t|}|S)NrR)callablerrrr^r2r=)rOrtrr"r"r#rs zGraph._target_to_str) root_moduler.c sNttdfdd ttdfdd }|||j|SQRXdS)a Turn this ``Graph`` into valid Python code. Args: root_module (str): The name of the root module on which to look-up qualified name targets. This is usually 'self'. Returns: A PythonCode object, consisting of two fields: src: the Python source code representing the object globals: a dictionary of global names in `src` -> the objects that they reference. )rcsj|j|S)N)r]r$)r) namespacer"r# node_repr1sz$Graph.python_code..node_repr)r|c 3sPi}x|jD]}|j||<|_q Wz dVWdx|jD]}|||_q8WXdS)N)rZ_repr_fn)r|Z orig_repr_fnsr)rr"r#override_node_repr4s     z-Graph.python_code..override_node_reprN)rFrrr _python_code)rOrrr")rrr# python_codes $ zGraph.python_code)rrr.c sNggiidgttdfdd x"tjD]\}\}}||q6Wtd fdd ii ttd fd d x>t jD]0tjfd d tj fd d qWtd fdd }td fdd }x jD]||qWt dkr.j d j dk r j j }|ddk} | r`jddt dkrjddjddj|dn}t dkrΈdtjj dj fddD} nd} t |dks|ddkr|jdddj} djdd| jdD} d| d dj|d!dd"| } t| S)#Nr5) name_hintr!csNt|r|tjkrt|Sj||}|krB||ks>t|S||<|S)a Add an obj to be tracked as a global. We call this for names that reference objects external to the Graph, like functions or types. Returns: the global name that should be used to reference 'obj' in generated source. )rEr)r*rr]r^)rr! global_name)globals_rr"r# add_globalMs z&Graph._python_code..add_global)ocsp|fkr dSt|}t|drftj|j|j}t||}fdd|jD}|ddj|dS||S)Nz() __origin__csg|] }|qSr"r")rmarg) type_reprr"r# usz9Graph._python_code..type_repr..[,])rr_origin_type_mapgetr__args__r:)rtypenameZ origin_typeZorigin_typenamerj)rrr"r#rhs z%Graph._python_code..type_repr)rusercs&|kr"||<j|gj|dS)N)rYr7)rr)node_to_last_useuser_to_last_usesr"r#register_last_usessz.Graph._python_code..register_last_usescs |S)Nr")r)rrr"r#rsz$Graph._python_code..cs |S)Nr")r)rrr"r#rs)rcsv|jdkrdS|jdkr&jddSj|g}t|rhdjdd|Ddg}jd |dn jddS) z Delete values after their last use. This ensures that values that are not used in the remainder of the code are freed and the memory usage of the code is optimal. rNr z = cSsg|] }t|qSr")rl)rmrr"r"r#rszDGraph._python_code..delete_unused_values..Nonez; )rr7rrr:)rZnodes_to_deleteZ to_delete_str)bodyrr"r#delete_unused_valuess    z0Graph._python_code..delete_unused_values)rc s|jdkrdnd|j}|jdkrt|jts8t|jsBdndt|jd}j|j|||jj dd}|t|krjt|d|ddS|jdkrt|jtstjt||dt t|jd|jd t |jd d|j d dS|jd krtt |js*t|jjd kr|jjtkrt|jtsXtjt||dt|jjjdd|jDdSt|j}||j}|dkr(t|jtr(t|jd tr(|jd jr(t|jdkr(jt||dt t|jd|jd dSjt||d|d t |j|j d |jjddrpj|dS|jdkrt|jtstjt||dt |jd t |j|j d dS|jdkrt|jtstjt||dt |jdS|jdkr|jdk r>d|jd<jdkrfjdt|jdnjdt|jdddStd|jd|jdS)Nr5z : rz = r*rr(r)r _operatorcss|]}t|VqdS)N)rl)rmrnr"r"r#rosz8Graph._python_code..emit_node..r?rRZ is_wrappedFrrrz -> zreturn zreturn pytree.tree_unflatten(z, self._out_spec)znode:  )rrrrtrr^rjrlr7replacerzrsrkrrr magic_methodsrformatrrvrrrrYrNotImplementedError)rZmaybe_type_annotationZmaybe_default_argraw_namerr)rr free_varsmaybe_return_annotationrrOr wrapped_fnsr"r# emit_nodesb   D 6   2.  6 $   z%Graph._python_code..emit_noderzpass rOz, z!, = fx_pytree.tree_flatten_spec([z], self._in_spec) wraprcsg|]}d|dqS)z("z")r")rmr$) wrap_namer"r#rsz&Graph._python_code..css|]}d|VqdS)z Nr")rmliner"r"r#rosz%Graph._python_code..z def forward(rz: )rr r%rrrreversedrrrjrkrr7rrinsertr:r)Zfxrrurg) rOrrr$r4r!rrrZ has_orig_selfZ wrap_stmtscodeZfn_coder")rrrrrrrrrrrOrrrrr#rDsP :      &  &zGraph._python_codecs`gdg}fdd|jD}dj}d|d|dd}x|D]}|rD|d |7}qDW|S) zl Return a human-readable (not machine-readable) string representation of this Graph r5csg|]}|jqSr")Z format_node)rmr)placeholder_namesr"r#r sz!Graph.__str__..z, zgraph(rr:z )rr:)rOZmaybe_return_typenameZ node_strsZ param_strr3Znode_strr")r r#__str__s  z Graph.__str__cCs\yddlm}Wntk r,tdYnXdd|jD}t||dddd d gd d S) z Prints the intermediate representation of the graph in tabular format. Note that this API requires the ``tabulate`` module to be installed. r)tabulatez`print_tabular` relies on the library `tabulate`, which could not be found on this machine. Run `pip install tabulate` to install the library.cSs$g|]}|j|j|j|j|jgqSr")rr$rtrjrk)rmrr"r"r#r sz'Graph.print_tabular..opcoder$rtrjrk)headersN)r  ImportErrorprintr)rOr Z node_specsr"r"r# print_tabulars zGraph.print_tabularc sdtttddfdd t}txjD]jdkrXtd d jd jk rrtddtjfddtj fddj j |krtdj d |j j q2Wj rxjD]jdkr,t js`td djdtjjdn4tjts`td djdtjjdjd krjjd}j }xt|D]\}}t||d}dj|d|}|dkrtd djd|d|jdkr t|tjj r td djd|d|d nhjd krt|tjj rt|tjj r||jkrtjd djd|d|d n|}qWqWdS)!aJ 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 this Graph has an owning GraphModule, checks that targets exist in that GraphModule N)rrr.cs^|rd|dnd}|jk r8td|d|d|krZtd|d|ddS)Nz of Node 'z' rz Argument ''zdoes not belong to this Graph, but was used as an argument! If you are copying nodes from another graph, make sure to use ``arg_transform`` on node_copy() to remap values zdwas used before it has been defined! Please check that Nodes in the graph are topologically ordered )r|r)rrZ context_str) seen_valuesrOr"r# check_arg1s  zGraph.lint..check_argrrrrrrzNode z had unknown opcode rzNode 'z ' does not belong to this Graph!cs |S)Nr")r)rrr"r#rBszGraph.lint..cs |S)Nr")r)rrr"r#rCszNode redefined name z target z has type z but a Callable is expectedz but a str is expectedr>z" references nonexistent attribute z of rz does not reference an nn.Modulezj does not reference an nn.Module, nn.Parameter, or buffer, which is what 'get_attr' Nodes typically target)N)rrrrrr)rr)rrrHrrrr|rrjrkrZr$rrrt ValueErrorr)rrrru enumerater?r:rArrrrr)rOZ seen_namesZ target_atomsZm_itriZatomZ new_m_itrZ seen_qualnamer")rrrrOr#lint%sL         (&    " &  (z Graph.lintcCsJ|jd}x8t|jD]*}|j rt|jdkr|j|d}qW|S)a7 Remove all dead code from the graph, based on each node's number of users, and whether the nodes have any side effects. The graph must be topologically sorted before calling. Returns: bool: Whether the graph was changed as a result of the pass. Example: Before dead code is eliminated, `a` from `a = x + 1` below has no users and thus can be eliminated from the graph without having an effect. .. code-block:: python def forward(self, x): a = x + 1 return x + self.attr_1 After dead code is eliminated, `a = x + 1` has been removed, and the rest of `forward` remains. .. code-block:: python def forward(self, x): return x + self.attr_1 FrT)rrrZ is_impurerrr)rOchangedrr"r"r#eliminate_dead_codels zGraph.eliminate_dead_code)NN)F)N)NNNN)r.)N)N)N)N)NNN)r.)NNN)r.)NNN)r.)N),rrrrr rrrPpropertyrsetterrrrrrrrrr rrrrrrrrrrr rrrrrrgrrFrr rrrr"r"r"r#rsj+  :* :2(2:& =>Grz{} + {}z{} - {}z{} * {}z{} // {}z{} / {}z{} % {}z{} ** {}z{} << {}z{} >> {}z{} & {}z{} | {}z{} ^ {}z{}[{}]z{} @ {})rZrSmulfloordivtruedivdivrpowlshiftrshiftand_or_xorgetitemmatmulz{} == {}z{} != {}z{} < {}z{} > {}z{} <= {}z{} >= {}z+{}z-{}z~{}) eqneltgtlegeposneginvert)FrrrrrrrZtorch.utils._pytreeutilsr r,r5r+Z_compatibilityr typingr r r rrrrrrrrZ dataclassesr contextlibrrr)rarKrcmathrZ graph_modulerZ_symbolic_tracerrrrH frozensetrrrr%rr&r'r(rr*rer2r=rErFrgrsrzr{rrrZreflectable_magic_methodsrr"r"r"r#s    4        P "  *