U
    9%e                     @   s8  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZmZ d dlmZmZmZmZmZmZmZmZmZmZ d dlZd dlm  mZ d dlmZ ddl m!Z! ddl"m#Z#m$Z$m%Z% dd	l&m'Z' dd
l(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1 ej2ej3B Z4ej5j6j7Z8ee9d< ej5j6j:Z;ee9d< i Z<eedf e9d< da=dd Z>e!ddG dd de?Z@eeAedddZBe!ddG dd dZCeC ZDe!ddG dd deCZEe!ddG dd de/ZFi ZGeeeAeHf eIf e9d< g ZJeee?eHf  e9d < ejKLd!d"kr8eJMejNd#f d$d% ZOd&d' ZPd(d) ZQG d*d+ d+eZRG d,d- d-eRZSG d.d/ d/eRZTG d0d1 d1eRZUG d2d3 d3ZVeVd4d5d6ZWeVeeHef eeA d7d8d9ZXe!ddeeHef d:d;d<ZYe!dddCeej5j6ed=ef f eeeHef  e'd>d?d@ZZeYdAdB Z[dS )D    N)chain)CodeTypeFunctionType
ModuleType)
AnyCallableDictList
NamedTupleOptionalSetTupleTypeUnion)ScriptObject   )compatibility)_PyTreeCodeGen_PyTreeInfoGraph)GraphModule)Argument
base_typesmap_aggregate)ParameterProxyProxy
TracerBaseScopeScopeContextManager_orig_module_call_orig_module_getattr_proxyable_classesFc                   C   s   t S N)_is_fx_tracing_flag r$   r$   W/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/fx/_symbolic_trace.pyis_fx_tracing-   s    r&   TZis_backward_compatiblec                       s(   e Zd ZdZ fddZdd Z  ZS )ProxyableClassMetaa  
    ProxyableClassMeta allows you to make construction of a given Python class
    symbolically traceable. For example::

        import torch
        import torch.fx

        class TensorPair(metaclass=torch.fx.ProxyableClassMeta):
            def __init__(self, left, right):
                self.left, self.right = left, right

            def add(self, other):
                l = self.left + other.left
                r = self.right + other.right
                return TensorPair(l, r)

            def mul(self, other):
                l = self.left * other.left
                r = self.right * other.right
                return TensorPair(l, r)

        def use_tensor_pair_ctor(x : TensorPair, y : torch.Tensor):
            s = x.add(TensorPair(y, y))
            return s.mul(x)

        x = TensorPair(torch.randn(5, 3), torch.randn(5, 3))
        y = torch.randn(5, 3)
        ref_out = use_tensor_pair_ctor(x, y)

        traced = torch.fx.symbolic_trace(use_tensor_pair_ctor)
        print(traced.code)
        '''
        def forward(self, x : __main___TensorPair, y : torch.Tensor):
            tensor_pair = __main___TensorPair(y, y);  y = None
            add = x.add(tensor_pair);  tensor_pair = None
            mul = add.mul(x);  add = x = None
            return mul
        '''

    From this example, we can see that construction of a class (``TensorPair``)
    defined with ``ProxyableClassMeta`` as metaclass can be recorded in symbolic
    tracing.
    c                    s   t |  t ||| d S r"   )r!   
setdefaultsuper__init__)clsnamebasesattrs	__class__r$   r%   r+   ^   s    
zProxyableClassMeta.__init__c                    sn   |  | }g   fdd}t|| t|| t dkrT d j}|d| ||S | j|f|| |S d S )Nc                    s   t | tr |  d S r"   )
isinstancer   append)aZfound_proxiesr$   r%   check_proxyg   s    
z0ProxyableClassMeta.__call__.<locals>.check_proxyr   call_function)__new__r   lentracercreate_proxyr+   )r,   argskwargsinstancer6   r:   r$   r5   r%   __call__b   s    



zProxyableClassMeta.__call__)__name__
__module____qualname____doc__r+   r?   __classcell__r$   r$   r0   r%   r(   0   s   ,r(   )fnnargsreturnc                 C   s  | j }|jt @ }t|drb|dd|j|j||j|j|j|j	|j
|j|j|j|j|j|j|jf}nt|dr|dd|j|j||j|j|j|j	|j
|j|j|j|j|jf}n:|d|j|j||j|j|j|j	|j
|j|j|j|j|jf}t| }t|| j| j| j| jS )Nco_qualnamer   co_posonlyargcount)__code__co_flagsHAS_VARSTUFFhasattr
co_nlocalsco_stacksizeco_code	co_constsco_namesco_varnamesco_filenameco_namerH   co_firstlineno	co_lnotabZco_exceptiontableco_freevarsco_cellvarsr   r   __globals__r@   __defaults____closure__)rE   rF   corK   Zco_argsZnew_coder$   r$   r%   _patch_functionv   s    

    r^   c                   @   s   e Zd ZdZdd ZdS )PHBaseE
    Object representing an input placeholder to `concrete_args`
    c                 C   s   dS )NPHr$   selfr$   r$   r%   __repr__   s    zPHBase.__repr__N)r@   rA   rB   rC   rd   r$   r$   r$   r%   r_      s   r_   c                       s,   e Zd ZdZdee d fddZ  ZS )
PHWithMetar`   N)ph_keyc                    s   t    || _d S r"   )r*   r+   rf   )rc   rf   r0   r$   r%   r+      s    
zPHWithMeta.__init__)N)r@   rA   rB   rC   r   strr+   rD   r$   r$   r0   r%   re      s   re   c                       sb  e Zd ZdZeddefddfee eedf e	dd fd	d
Z
eddedd fddZeddejjee	dddZeddejjedddZeddejjedef eedf eeef edddZeddeeeeef dddZeddd"ddZeddd#eejjedef f eeeef  edddZd d! Z  ZS )$Tracera  Tracer(autowrap_modules=(math,), autowrap_functions=())

    ``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.
    Tr'   r$   F.N)autowrap_modulesautowrap_functionsparam_shapes_constantrG   c                    sz   t    dd tdd |D  D | _| jdd |D  t|| _|| _d| _d| _	t
dd| _t | _i | _dS )a  
        Construct a Tracer object.

        Args:

            autowrap_modules (Tuple[ModuleType]): defaults to `(math, )`,
                Python modules whose functions should be wrapped automatically
                without needing to use fx.wrap(). Backward-compatibility for
                this parameter is guaranteed.

            autowrap_functions (Tuple[Callable, ...]): defaults to `()`,
                Python functions that should be wrapped automatically without
                needing to use fx.wrap(). Backward compatibility for this
                parameter is guaranteed.

            param_shapes_constant (bool): When this flag is set,  calls to shape,
                size and a few other shape like attributes of a module's parameter
                will be evaluated directly, rather than returning a new Proxy value
                for an attribute access. Backward compatibility for this parameter
                is guaranteed.
        c                 S   s*   h | ]"\}}| d st|rt|qS )_)
startswithcallableid).0r-   valuer$   r$   r%   	<setcomp>  s   
 z"Tracer.__init__.<locals>.<setcomp>c                 S   s   g | ]}|j  qS r$   )__dict__items)rp   mr$   r$   r%   
<listcomp>  s     z#Tracer.__init__.<locals>.<listcomp>c                 S   s   h | ]}t |qS r$   )ro   )rp   fr$   r$   r%   rr     s     N )r*   r+   r   _autowrap_function_idsupdatelist_autowrap_searchrk   submodule_pathsroot_module_namer   scopecollectionsOrderedDictmodule_stackZnode_name_to_scope)rc   ri   rj   rk   r0   r$   r%   r+      s    !


zTracer.__init__r   )r4   rG   c           	         s  t |tjjrH j D ]$\}}||kr d|di   S qtdn|t |tjr j	 D ]$\}}||kr^ d|di   S q^n>t |tjj
rĈ j D ]$\}}||kr d|di   S qt |trt|drt fdd|D } d|j|i S t |tjtfr| j|}|sld}d	| }t j|sHqT|d
7 }q,| j|< t j||  d|di S t|tkrd}d|jj d| }t j|sq|d
7 }qt j||  d|di S t |S )a  
        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.

        Args:

            a (Any): The value to be emitted as an ``Argument`` in the ``Graph``.


        Returns:

            The value ``a`` converted into the appropriate ``Argument``
        get_attrr$   z(parameter is not a member of this module_fieldsc                 3   s   | ]}  |V  qd S r"   )
create_arg)rp   elemrb   r$   r%   	<genexpr>W  s     z$Tracer.create_arg.<locals>.<genexpr>r7   r   Z_tensor_constantr   rl   Z
_constant_)r2   torchnn	Parameterrootnamed_parameterscreate_node	NameErrorTensornamed_buffersModulenamed_modulestuplerM   r1   r   tensor_attrsgetsetattrtyper!   r@   r*   r   )	rc   r4   npZn_Zp_r<   qualnameir0   rb   r%   r   '  sH     
	

zTracer.create_arg)ru   module_qualified_namerG   c                 C   s(   |j ds|j do&t|tjj S )aF  
        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.

        Args:

            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.
        ztorch.nnztorch.ao.nn)rA   rm   r2   r   r   Z
Sequential)rc   ru   r   r$   r$   r%   is_leaf_module  s    zTracer.is_leaf_module)modrG   c                 C   sd   | j r4| j |}|dkr"tdt|ts0t|S | j D ]\}}||kr>|  S q>tddS )a~  
        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".

        Args:

            mod (str): The ``Module`` to retrieve the qualified name for.
        Nz&module is not installed as a submodule)r}   r   r   r2   rg   AssertionErrorr   r   )rc   r   pathr   r   r$   r$   r%   path_of_module  s    
zTracer.path_of_module)ru   forwardr<   r=   rG   c           
   	   C   s   |  |}t| jt|t|f}|j| j|j< | ||sH|||}n| 	d|||}| jj
dd\}}	||jkstd| W 5 Q R X |S )a  
        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.

        Args:

            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

        Return:

            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.
        call_moduleT)lastz Unexpected key )r   r   r   r   r   module_typer   module_pathr   r;   popitemr   )
rc   ru   r   r<   r=   r   Z_scopeZret_valkeyrl   r$   r$   r%   r     s    "
"zTracer.call_module)attrattr_valparameter_proxy_cachec                    sl    fdd}t |tjjr8|| j |}|dk	r8|S  jrht |tjrh|| j |}|dk	rh|S |S )a  
        Method that specifies the behavior of this ``Tracer`` when we call getattr
        on a call to an ``nn.Module`` instance.

        By default, the behavior is to return a proxy value for the attribute. It
        also stores the proxy value in the ``parameter_proxy_cache``, so that future
        calls will reuse the proxy rather than creating a new one.

        This method can be overridden to --for example-- not return proxies when
        querying parameters.

        Args:

            attr (str): The name of the attribute being queried
            attr_val (Any): The value of the attribute
            parameter_proxy_cache (Dict[str, Any]): A cache of attr names to proxies

        Return:

            The return value from the getattr call.
        c                    s~   |D ]t\} |kr|krli }dt jjkrPjs<d n fdd|d< jddi f|}||< |   S qd S )NZproxy_factory_fnc                    s   t |  S r"   )r   )node)r   r   rc   r$   r%   <lambda>  s
      zBTracer.getattr.<locals>.maybe_get_proxy_for_attr.<locals>.<lambda>r   r$   )inspect	signaturer;   
parametersrk   )r   Zcollection_to_searchr   r   r=   Z	val_proxyrb   )r   r   r%   maybe_get_proxy_for_attr  s     z0Tracer.getattr.<locals>.maybe_get_proxy_for_attrN)	r2   r   r   r   r   r   Zproxy_buffer_attributesr   r   )rc   r   r   r   r   Zmaybe_parameter_proxyZmaybe_buffer_proxyr$   rb   r%   getattr  s$        zTracer.getattrc                    s  t j}|j|j }t|j}t|jg }d}|rd|dkrLtdd}t	 |
j t td fddfddt||D }	t trt|	t krtd	t|	 d
t  dtt|	  |fdd|	D  |jdks|jt@ rj|jt j@ r8|
dt	  |jt j@ r\|
dt	  tt|tt|\}
tdd jD rtt|d| dj _!fdd}||
fS |fS )z
        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``.
        r   z4``self`` argument cannot be part of *args expansion!r   )r-   c              	      s   d k	r6kr6d  fdd}t | S d dkrHd}n$j }|jtjjkrddn|jf}jd|i j	d dS )Nr   c                    s    d7  j  }|jtjjkr$dn|jf}d dt  |i }t| trvdd }| t	krr|| |j
d |S t| tkst| tkrt| tjkrt|| k d|  d	 nBt| td kr| d
f}dt|i  ntd d | S )Nr   r$   placeholderrl   c                 S   sD   t | D ]6}t| |}t|s|dst||st||| qd S )N__)dirr   rn   rm   rM   r   )frto	attr_namer   r$   r$   r%   transfer_attrsT  s    
zbTracer.create_args_for_root.<locals>.proxy_placeholder.<locals>.replace_ph.<locals>.transfer_attrs)r   r   z$ has been specialized to have value z but got another valuez> has been specialized to have value None but got another valuer7   z9Was not able to add assertion to guarantee correct input z to specialized function. It is up to the user to make sure that your inputs match the inputs you specialized the function with.)r   defaultr   r   emptyr;   rg   r2   r_   ra   r   r   boolr   r   r   Z_assert_assert_is_nonewarningswarn)xparamr   outr   r<   )cntr-   rc   sigr$   r%   
replace_phG  sH    
   




zJTracer.create_args_for_root.<locals>.proxy_placeholder.<locals>.replace_ph*r$   r   Z	type_expr)
pytreeZtree_mapr   r   r   r   r   r;   __annotations__r   )r-   r   r   r   )concrete_argsfn_for_analysisrc   r   )r   r-   r%   proxy_placeholderC  s    ;
z6Tracer.create_args_for_root.<locals>.proxy_placeholderc                    s   g | ]}t  qS r$   )next)rp   idx)
names_iterr$   r%   rv     s     z/Tracer.create_args_for_root.<locals>.<listcomp>zTracing expected z arguments but got z concrete argumentsc                 3   s   | ]} |V  qd S r"   r$   )rp   names)r   r$   r%   r     s     z.Tracer.create_args_for_root.<locals>.<genexpr>r   z**c                 s   s   | ]}t |tj V  qd S r"   )r2   r   ZLeafSpec)rp   r   r$   r$   r%   r     s     Nc                     sT   t t|  }| }t |\}}tjjts8tjjj	j
|djj_	|S )N)out_spec)r   Ztree_unflattenr{   tree_flattenr2   graph_codegenr   r   Zpytree_info_replace)r<   Z	tree_argsZtree_outZout_argsr   )in_specroot_fnrc   r$   r%   
flatten_fn  s    z/Tracer.create_args_for_root.<locals>.flatten_fn)"r   unwraprJ   co_argcountco_kwonlyargcountr{   rS   iterRuntimeErrorr   r3   r   r   rg   ranger2   r   r9   dictzipextendrK   rL   
CO_VARARGSCO_VARKEYWORDSr^   r   r   anyZchildren_specsr   r   r   r   )rc   r   Z	is_moduler   r]   Z
total_args	orig_argsr<   Zskip_arg_idx	arg_namesZ	flat_argsr   r$   )r   r   r   r   r   r   rc   r   r%   create_args_for_root&  sN    



M

zTracer.create_args_for_rootr   r   rG   c              
      s  t }da zt|tjjr||_tt|jsLt	dj dt|j
 tt|j}| _dd | D _ntj _|}tdd}t|d_t|d	r|j}|j|j|jd
j_i _tjjtt d fdd  jg  t|ts
t	|j}|t|tjj|\}}i ttfdd}	tt fdd}
t! j"tjjd|	dd j"tjjd|
dd t# t$|j% j&D ]}t$|j'j% qj(dd)|| fi |j*+ddd W 5 Q R X d_W 5 |a X jS )a  
        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.


        Args:

            root (Union[Module, Callable]): Either a ``Module`` or a function to be
                traced through. Backwards-compatibility for this parameter is
                guaranteed.
            concrete_args (Optional[Dict[str, any]]): Concrete arguments that should
                not be treated as Proxies. This parameter is experimental and
                its backwards-compatibility is *NOT* guaranteed.

        Returns:

            A ``Graph`` representing the semantics of the passed-in ``root``.
        Tztraced_func_name=z doesn't exist in c                 S   s   i | ]\}}||qS r$   r$   )rp   r-   r   r$   r$   r%   
<dictcomp>  s      z Tracer.trace.<locals>.<dictcomp>r1   N)
tracer_clsrJ   )rU   rT   rV   )ru   prefix_atomsc                    s`   | j  D ].\}}t|tjtfr
d||g j|< q
|  D ]\}} |||g  qBd S )N.)	rs   rt   r2   r   r   r   joinr   Znamed_children)ru   r   kv)collect_tensor_attrsrc   r$   r%   r     s
    z*Tracer.trace.<locals>.collect_tensor_attrsc                    s   t | |}|| S r"   )r    r   )r   r   r   )r   rc   r$   r%   module_getattr_wrapper  s    
z,Tracer.trace.<locals>.module_getattr_wrapperc                    s:    fdd}t tt d di j  |||S )Nc                     s   t  f| |S r"   )r   )r<   r=   r   r$   r%   r     s    z:Tracer.trace.<locals>.module_call_wrapper.<locals>.forwardr   rZ   )_autowrap_checkr   ry   r   )r   r<   r=   r   )patcherrc   r   r%   module_call_wrapper  s    z)Tracer.trace.<locals>.module_call_wrapper__getattr__F)deduplicater?   outputrG   r   ),r#   r2   r   r   r   r   rM   r   Ztraced_func_namer   r@   r   Z	_get_namer~   r   r}   r   r   rJ   rU   rT   rV   Z
_co_fieldsr   r	   rg   r   rZ   r   	functoolswrapsr    r   _Patcherpatch_method_patch_wrapped_functionsr   ry   r|   rs   r   r   r   r   )rc   r   r   Zold_is_fx_tracing_flagrE   r   codeZ
fn_globalsr<   r   r   moduler$   )r   r   r   rc   r%   trace  s     



     
  
zTracer.tracec                 C   sL   t t }| j D ]2\}}|dkr0t|}nt||}||j|< q|S )N>   r|   )rh   r8   rs   rt   copydeepcopy)rc   memoZ
new_tracerr   r   Znew_objr$   r$   r%   __deepcopy__;  s    
zTracer.__deepcopy__)N)N)r@   rA   rB   rC   r   mathr   r   r   r   r+   r   r   r   r   r   rg   r   r   r   r   r   r   r   r   r   r   r  rD   r$   r$   r0   r%   rh      sL   
9[


/>   rh   _wrapped_fns_to_patch_wrapped_methods_to_patchZFX_PATCH_GETITEM1__getitem__c                     s   d  fdd}t | |  S )zh
    Recursively search a data structure for a Proxy() and return it,
    return None if not found.
    Nc                    s   t | tr|  d S r"   )r2   r   )r   proxyr$   r%   
find_proxyd  s    
z_find_proxy.<locals>.find_proxy)r   )Zobjects_to_searchr  r$   r
  r%   _find_proxy]  s    
r  c                    s   t   fdd}|S )Nc                     s>   t | |}|dk	r4|jd | |}d|jjd< |S  | |S )aN  
        Given an closed-over ``orig_function`` to invoke, search the args and kwargs for
        a Proxy object. If there is one, emit a ``call_function`` node to preserve the
        call to this leaf function directly. Otherwise, just return the results of
        this function call, as this function is not being traced.
        Nr7   TZ
is_wrapped)r  r:   r;   r   meta)r<   r=   r  Zreturn_proxyorig_fnr$   r%   wrappedn  s    
   z%_create_wrapped_func.<locals>.wrapped)r   r   )r  r  r$   r  r%   _create_wrapped_funcm  s    r  c                    s&   t |  t fdd}|S )Nc                     s.   t | |}|dk	r$|jd | |S | |S )a  
        Search the args and kwargs for a Proxy object. If there is one,
        emit a ``call_method`` node to preserve the call to this method
        directly. Otherwise, just return the results of this function
        call, as this function is not being traced.
        NZcall_method)r  r:   r;   )r<   r=   r  r-   r  r$   r%   r    s    
z'_create_wrapped_method.<locals>.wrapped)r   r   r   )r,   r-   r  r$   r  r%   _create_wrapped_method  s    
r  c                   @   s.   e Zd ZU eed< eed< eed< dd ZdS )
_PatchedFn
frame_dictfn_namer  c                 C   s
   t  d S r"   )NotImplementedErrorrb   r$   r$   r%   revert  s    z_PatchedFn.revertN)r@   rA   rB   r   r   rg   r  r$   r$   r$   r%   r    s   
r  c                   @   s   e Zd Zdd ZdS )_PatchedFnSetItemc                 C   s   | j | j| j< d S r"   )r  r  r  rb   r$   r$   r%   r    s    z_PatchedFnSetItem.revertNr@   rA   rB   r  r$   r$   r$   r%   r    s   r  c                   @   s   e Zd Zdd ZdS )_PatchedFnDelc                 C   s   | j | j= d S r"   )r  r  rb   r$   r$   r%   r    s    z_PatchedFnDel.revertNr  r$   r$   r$   r%   r    s   r  c                   @   s   e Zd Zdd ZdS )_PatchedFnSetAttrc                 C   s   t | j| j| j d S r"   )r   r  r  r  rb   r$   r$   r%   r    s    z_PatchedFnSetAttr.revertNr  r$   r$   r$   r%   r    s   r  c                       sn   e Zd Z fddZdeeef eeedddZ	de
eeeddd	Zed
ddZdd Zdd Z  ZS )r   c                    s   t    g | _t | _d S r"   )r*   r+   patches_madesetvisitedrb   r0   r$   r%   r+     s    
z_Patcher.__init__T)r  r-   new_fnr   c                 C   sf   ||_ ||kr.tt|r.| jt||d n,t|| ddrBdS | jt||||  |||< dS )zY
        Replace frame_dict[name] with new_fn until we exit the context manager.
        N__fx_already_patchedF)_Patcher__fx_already_patchedrM   builtinsr  r3   r  r   r  )rc   r  r-   r!  r   r$   r$   r%   patch  s    
z_Patcher.patch)r,   r-   r!  r   c                 C   sD   ||_ t||}t|ddr dS | jt||| t||| dS )z\
        Replace object_or_dict.name with new_fn until we exit the context manager.
        r"  FN)r#  r   r  r3   r  r   )rc   r,   r-   r!  r   r  r$   r$   r%   r     s    
z_Patcher.patch_method)thingc                 C   s&   t |}|| jkrdS | j| dS )z<Return True on the first call to with thing, otherwise falseFT)ro   r   add)rc   r&  r   r$   r$   r%   
visit_once  s
    
z_Patcher.visit_oncec                 C   s   | S r"   r$   rb   r$   r$   r%   	__enter__  s    z_Patcher.__enter__c                 C   s$   | j r| j    q | j  dS )zT
        Undo all the changes made via self.patch() and self.patch_method()
        N)r  popr  r   clear)rc   exc_typeexc_valexc_tbr$   r$   r%   __exit__  s    z_Patcher.__exit__)T)T)r@   rA   rB   r+   r   rg   r   r   r   r%  r   r   r(  r)  r/  rD   r$   r$   r0   r%   r     s$   
 
    r   )r   c                 C   st   t  D ]D\\}}}||kr2tt|r2tt|}n|| }| ||t| qtD ]\}}| ||t	|| qRdS )z
    Go through ``_wrapped_fn_patch_table`` and, for each frame object, wrap
    the listed global functions in the `_create_wrapped_func` wrapper.
    N)
r  rt   rM   r$  r   r%  r  r  r   r  )r   rl   r-   r  r  r,   r$   r$   r%   r     s    r   )r   r  function_idsc                 C   sP   |  |rL| D ]8\}}|dst|rt||kr| ||t| qdS )z
    Some methods, like `math.sqrt` are common enough we want to automatically wrap them as we see them.
    This method searches a scope for them and patches them if found.
    rl   N)r(  rt   rm   rn   ro   r%  r  )r   r  r0  r-   rq   r$   r$   r%   r     s    

r   )
fn_or_namec                 C   s   t | st| tstdt | r8t| tr0t| j}nt| tsJtd| }t }|dk	sbt|j}|dk	stt|j	j
dkrtd|jtt|j|f< | S )an  
    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.

    Args:

        fn_or_name (Union[str, Callable]): The function or name of the global function to insert into the
            graph when it's called
    zNUnsupported type for global function! Must be either a callable or string namez3fn_or_name must be a global function or string nameNz<module>z0wrap must be called at the top level of a module)rn   r2   rg   r   r   r@   r   currentframef_backf_coderU   r  	f_globalsr  ro   )r1  r  r2  rw   r$   r$   r%   wrap  s,    " r6  .r   c                 C   s<   t  }|| |}t| tjjr(| jjn| j}t|j	||S )a  
    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``.

    ``concrete_args`` allows you to partially specialize your function, whether it's to remove control flow or data structures.

    For example::

        def f(a, b):
            if b == True:
                return a
            else:
                return a*2

    FX can typically not trace through this due to the presence of control
    flow. However, we can use `concrete_args` to specialize on the value of
    `b` to trace through this::

        f = fx.symbolic_trace(f, concrete_args={'b': False})
        assert f(3, False)  == 6

    Note that although you can still pass in different values of `b`, they will be ignored.

    We can also use `concrete_args` to eliminate data-structure handling from
    our function. This will use pytrees to flatten your input. To avoid
    overspecializing, pass in `fx.PH` for values that shouldn't be
    specialized. For example::

        def f(x):
            out = 0
            for v in x.values():
                out += v
            return out
        f = fx.symbolic_trace(f, concrete_args={'x': {'a': fx.PH, 'b': fx.PH, 'c': fx.PH}})
        assert f({'a': 1, 'b': 2, 'c': 4}) == 7


    Args:
        root (Union[torch.nn.Module, Callable]): Module or function to be traced and converted
            into a Graph representation.
        concrete_args (Optional[Dict[str, any]]): Inputs to be partially specialized

    Returns:
        GraphModule: a Module created from the recorded operations from ``root``.
    )
rh   r   r2   r   r   r   r1   r@   r   r   )r   r   r:   r   r-   r$   r$   r%   symbolic_traceI  s
    4r7  c                 C   s   | d kst |d S r"   )r   )rq   msgr$   r$   r%   r     s    r   )N)\r$  r  r   r   r  osr   r   	itertoolsr   typesr   r   r   typingr   r   r   r	   r
   r   r   r   r   r   r   Ztorch.utils._pytreeutilsZ_pytreer   Ztorch._Cr   Z_compatibilityr   r   r   r   r   Zgraph_moduler   r   r   r   r   r  r   r   r   r   r   r   r   rL   r   r   r?   r   r   r   r    r!   r#   r&   r   r(   intr^   r_   ra   re   rh   r  rg   r   r  environr   r3   r   r  r  r  r  r  r  r  r   r   r   r6  r7  r   r$   r$   r$   r%   <module>   s    0EI	    y	= 
 = ;