
    ǄgK]                        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Zd dl	m
Z
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mZmZmZmZ ddlmZmZmZmZmZ ddl m!Z! dd	l"m#Z# d dl$m%c m&Z' g d
Z( ejR                  e*      Z+ e!d       G d d             Z, e!d       G d d             Z-g dZ. e!d       G d d             Z/ e!d       G d de/             Z0 e!d      d        Z1 e!d       G d de2             Z3 e!d       G d d             Z4 e!d       G d de4             Z5 e!d       G d de4             Z6eD ]  Z7d  Z8 e8e7        d! Z9eD ]
  Z: e9e:        y)"    N)is_dataclassfields   )magic_methodsreflectable_magic_methodsGraph)CapturedTraceback)TupleDictOrderedDictOptionalAnyIteratorCallable)TargetNodeArgument
base_typesmap_aggregate)compatibility)check_for_mutable_operation)
TracerBaseGraphAppendingTracer
TraceErrorProxy	AttributeParameterProxyScopeScopeContextManagerFis_backward_compatiblec                   ,     e Zd ZdZdedef fdZ xZS )r   a7   Scope object that records the module path and the module type
    of a module. Scope is used to track the information of the module
    that contains a Node in a Graph of GraphModule. For example::

        class Sub(torch.nn.Module):
            def forward(self, x):
                # This will be a call_method Node in GraphModule,
                # scope for this would be (module_path="sub", module_type=Sub)
                return x.transpose(1, 2)

        class M(torch.nn.Module):
            def __init__(self) -> None:
                self.sub = Sub()

            def forward(self, x):
                # This will be a call_method Node as well,
                # scope for this would be (module_path="", None)
                x = x.transpose(1, 2)
                x = self.sub(x)
                return x

    module_pathmodule_typec                 >    t         |           || _        || _        y N)super__init__r#   r$   )selfr#   r$   	__class__s      V/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/fx/proxy.pyr(   zScope.__init__9   s    &&    )__name__
__module____qualname____doc__strr   r(   __classcell__r*   s   @r+   r   r       s     .'C 'c ' 'r,   r   c                   8     e Zd ZdZdedef fdZd Zd Z xZS )r   z A context manager to track the Scope of Node during symbolic tracing.
    When entering a forward function of a Module, we'll update the scope information of
    the current module, and when we exit, we'll restore the previous scope information.
    scopecurrent_scopec                     t         |           t        j                  |      | _        |j                  |_        |j
                  |_        || _        y r&   )r'   r(   copy_prev_scoper#   r$   _scope)r)   r5   r6   r*   s      r+   r(   zScopeContextManager.__init__F   sD    
 	99U+)55)55r,   c                     | j                   S r&   )r:   r)   s    r+   	__enter__zScopeContextManager.__enter__T   s    {{r,   c                     | j                   j                  | j                  _        | j                   j                  | j                  _        y r&   )r9   r#   r:   r$   )r)   argss     r+   __exit__zScopeContextManager.__exit__W   s5    "&"2"2">">"&"2"2">">r,   )	r-   r.   r/   r0   r   r(   r=   r@   r2   r3   s   @r+   r   r   ?   s)    
 r,   r   )nn_module_stacktorch_fnsource_fn_stackoriginal_aten	recomputeac_graph_id	from_nodequantization_tag_numeric_debug_handlecustompartitioner_tagTc                   B   e Zd ZU eed<   dZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed<   eed	<   eeeeef   f   ed
<   eeeeef   f   ed<    ed      	 	 d$dededeedf   deeef   dee   dee   defd       Z ed      deddfd       Z ed      	 	 d%dededeedf   deeef   dee   dee   deegdf   fd       Zd Z ed      dedefd       Z ed      d ddefd!       Z ed      d ddefd"       Z ed      d ddefd#       Z y)&r   graphFrecord_stack_tracescheck_mutable_operationstrace_assertsproxy_buffer_attributesforwardtraced_func_namer5   module_stacknode_name_to_scopeTr    Nkindtargetr?   .kwargsname	type_exprreturnc                 .   |dk(  r| j                   rt        |||       | j                  j                  ||||||      }| j                  j
                  | j                  j                  f| j                  |j                  <   t        j                         rt        j                         }|j                  d      }	|	r|	|_        t        D ],  }
|
|v st        j                  ||
         |j                   |
<   . t"        j$                  j'                         dz
  }|j                  dd      dkD  r|d   d   }||j                   d<   n8| j(                  r,t        j                  | j(                        |j                   d	<   t*        j-                  d
|       |S )a'  
        Inserts a graph node given target, args, kwargs, and name.

        This method can be overridden to do extra checking, validation, or
        modification of values used in node creation. For example, one might
        want to disallow in-place operations from being recorded.
        call_functionstack_tracer   
in_grad_fnr   grad_fn_seq_nrseq_nrrA   zcreate_node %s)rO   r   rM   create_noder5   r#   r$   rU   rY   fx_tracebackhas_preserved_node_metaget_current_metagetr^   _COPY_META_FIELDSr8   metatorchautograd_get_sequence_nrrT   logdebug)r)   rV   rW   r?   rX   rY   rZ   nodecurrent_metar^   field
new_seq_nrs               r+   rc   zTracerBase.create_node   sg    ?"t'D'D'f=zz%%dFD&$	R JJ""JJ"".
		*
 //1+7+H+H+JL&**=9K#.  + FL('+yye1D'EDIIe$F 88:Q>J a014)*:;B?
",DIIh+/99T5F5F+GDII'(		"D)r,   ro   r   c                     t        ||       S r&   )r   )r)   ro   s     r+   proxyzTracerBase.proxy   s    T4  r,   proxy_factory_fnc                    | j                  |      }| j                  |      }	t        |t              sJ t        |	t              sJ | j	                  ||||	||      }
|s| j                  |
      }n ||
      }| j                  rV|j                  j                  s@dj                  t        j                         j                               |j                  _        |S )ao  
        Create a Node from the given arguments, then return the Node
        wrapped in a Proxy object.

        If kind = 'placeholder', then we're creating a Node that
        represents the parameter of a function. If we need to encode
        a default parameter, we use the ``args`` tuple. ``args`` is
        otherwise empty for ``placeholder`` Nodes.
         )
create_arg
isinstancetupledictrc   rt   rN   ro   r^   joinr	   extractformat)r)   rV   rW   r?   rX   rY   rZ   ru   args_kwargs_ro   rt   s               r+   create_proxyzTracerBase.create_proxy   s     %//&)%''''4(((feWdINJJt$E$T*E##EJJ,B,B%'WW->-F-F-H-O-O-Q%REJJ" r,   c                     t        j                         g d}r&j                  rt        fd|D              rnr&syS )zf
        Find the Python stack frame executing the user code during
        symbolic tracing.
        )
ztorch/fx/proxy.pyztorch/fx/_symbolic_trace.pyz%torch/fx/experimental/proxy_tensor.pyztorch/_ops.pyztorch/_tensor.pyztorch/utils/_python_dispatch.pyztorch/_prims_common/wrappers.pyztorch/_refs/__init__.pyz%torch/_refs/nn/functional/__init__.pyztorch/utils/_stats.pyc              3   j   K   | ]*  }j                   j                  j                  |        , y wr&   )f_codeco_filenameendswith).0fileframes     r+   	<genexpr>z.TracerBase._find_user_frame.<locals>.<genexpr>   s)     ^T!9!9!B!B4!HH^s   03N)inspectcurrentframef_backall)r)   pt_filesr   s     @r+   _find_user_framezTracerBase._find_user_frame   sN     $$&
 LLE^U]^^ 
 r,   ac           
          t        |t              st        |d      r|j                         S t        |t              r.t        |d      r"t	         fd|D              } t        |      | S t        |t        t        f      r t        |       fd|D              S t        |t              rRi }|j                         D ];  \  } j                        fd}t        |        j                  |      |<   = |S t        |t              rXt         j                  |j                         j                  |j                         j                  |j                              S t        |t              rXt         j                  |j                         j                  |j                         j                  |j                              S t        |t         j"                  j$                  t         j"                  j&                  f      r|S t        |t              r|j(                  S t+        |      rdt-        |      D ci c]2  }|j.                   j                  t1        ||j.                              4 }} j3                  d|j4                  d|      S t        |g t6        t8        j:                        s||du r|S t=        d	t        |             c c}w )
z
        A method that lowers the objects seen as arguments during symbolic evaluation
        into Argument types that can be stored in IR.

        Can be override to support more trace-specific types.
        __fx_create_arg___fieldsc              3   @   K   | ]  }j                  |        y wr&   rx   r   elemr)   s     r+   r   z(TracerBase.create_arg.<locals>.<genexpr>  s     =4.=   c              3   @   K   | ]  }j                  |        y wr&   r   r   s     r+   r   z(TracerBase.create_arg.<locals>.<genexpr>  s     ?T4??40?r   c                 B    t        | t              rt        d       y )NzJKeys for dictionaries used as an argument cannot contain a Node. Got key: )ry   r   RuntimeError)argks    r+   no_nodez&TracerBase.create_arg.<locals>.no_node  s1    !#t,* ,==>C,A B B -r,   r]    .zargument of type: )ry   r   hasattrr   rz   typelistr{   itemsrx   r   slicestartstopsteprangerj   _ops
OpOverloadHigherOrderOperatorro   r   r   rY   getattrrc   r*   r   enumEnumNotImplementedError)	r)   r   r?   rvr   rq   rX   r   s	   `       @r+   rx   zTracerBase.create_arg   sE    !U#3F(G&&t,,5!ga&; =1==D47D>!E4=)47?Q???4 A	 *1 OOA&B a)q)!* H5!14??1663JDOO\]\b\bLcdd5!14??1663JDOO\]\b\bLcddEJJ115::3Q3QRSHa66M?W]^_W`aeejj$//'!UZZ2H"IIaFa##OQ[["fMM3Z334	Q#XH!$6tAwi"@AA bs   7Kobjc                     t        d      )aF  Called when a proxy object is being converted to a boolean, such as
        when used in control flow.  Normally we don't know what to do because
        we don't know the value of the proxy, but a custom tracer can attach more
        information to the graph node using create_node and can choose to return a value.
        zFsymbolically traced variables cannot be used as inputs to control flowr   r)   r   s     r+   to_boolzTracerBase.to_bool7  s     abbr,   c                     t        d      )aA  Called when a proxy object is being iterated over, such as
        when used in control flow.  Normally we don't know what to do because
        we don't know the value of the proxy, but a custom tracer can attach more
        information to the graph node using create_node and can choose to return an iterator.
        aH  Proxy object cannot be iterated. This can be attempted when the Proxy is used in a loop or as a *args or **kwargs function argument. See the torch.fx docs on pytorch.org for a more detailed explanation of what types of control flow can be traced, and check out the Proxy docstring for help troubleshooting Proxy iteration errorsr   r   s     r+   iterzTracerBase.iter@  s      2 3 	3r,   c                 $     t        |d             S )zCalled when a proxy object is has the keys() method called.
        This is what happens when ** is called on a proxy. This should return an
        iterator it ** is suppose to work in your custom tracer.
        keysr   r   s     r+   r   zTracerBase.keysP  s     &yf%''r,   NN)NNN)!r-   r.   r/   r   __annotations__rN   boolrO   rP   rQ   rS   r1   r   r   r
   r   r   r   r   r   r   r   r   rc   rt   r   r   r   rx   r   r   r   r   r   r,   r+   r   r   l   s9   L!&$& ',t+ MD %*d* &c% M c5c?233 S%T	"2233$/fj044 4v 4 3/4:>sH}:M4V^_bVc4 (49=4 04l $/!$ !7 ! 0! $/MQCG f E#s(O UYZ]_bZbUc #C==Ec]'/'@ 0>> $/5BC 5BH 5B 05Bn $/c7 ct c 0c $/3 3H 3 03 $/( (C ( 0(r,   r   c                   $     e Zd Zdef fdZ xZS )r   rM   c                     t         |           || _        t        dd       | _        t        j                         | _        i | _        y )Nrw   )	r'   r(   rM   r   r5   collectionsr   rT   rU   )r)   rM   r*   s     r+   r(   zGraphAppendingTracer.__init__\  s;    
2t_
'335"$r,   )r-   r.   r/   r   r(   r2   r3   s   @r+   r   r   Z  s    %e % %r,   r   c                     | sJ y r&   r   xs    r+   	assert_fnr   c  s	    H1r,   c                       e Zd Zy)r   N)r-   r.   r/   r   r,   r+   r   r   g  s    r,   r   c                       e Zd ZdZ ed      ddeddfd       Zd	efd
ZddZ	d	e
fdZd	e
fdZd ZddZd	ed    fdZd Zd	efdZ ed      d        Zd Zedd       Zy)r   a  
    ``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``.

    ``Proxy`` objects cannot be iterated. In other words, the symbolic
    tracer will throw an error if a ``Proxy`` is used in a loop or as
    an ``*args``/``**kwargs`` function argument.

    There are two main ways around this:
    1. Factor out the untraceable logic into a top-level function and
    use ``fx.wrap`` on it.
    2. If the control flow is static (i.e. the loop trip count is
    based on some hyperparameter), the code can be kept in its original
    position and refactored into something like::

        for i in range(self.some_hyperparameter):
            indexed_item = proxied_value[i]

    For a more detailed description into the Proxy internals, check out
    the "Proxy" section in `torch/fx/README.md`
    Tr    Nro   tracerzOptional[TracerBase]c                 N    |t        |j                        }|| _        || _        y r&   )r   rM   r   ro   )r)   ro   r   s      r+   r(   zProxy.__init__  s#    >)$**5F	r,   r[   c                 6    d| j                   j                   dS )NzProxy())ro   rY   r<   s    r+   __repr__zProxy.__repr__  s    		'q))r,   c                     t        | |      S r&   r   )r)   r   s     r+   __getattr__zProxy.__getattr__  s     q!!r,   c                     | j                   S r&   __dict__r<   s    r+   __getstate__zProxy.__getstate__  s    }}r,   c                    dd l }i }| j                  j                         D ]  \  }}	  |j                  ||      }|||<     d|v sJ d|v sJ t        |d   |d         }|j                         D ]  \  }}||j                  |<    |S # t        $ r@ t
        j                  d|| j                  j                          |j                   |      }Y w xY w)Nr   zVShallow copy %s of Proxy because it cannot be deepcopied. Proxy is created for node %sro   r   )
r8   r   r   deepcopy	Exceptionrm   warningro   rY   r   )r)   memor8   new_dictr   r   new_obj	new_proxys           r+   __deepcopy__zProxy.__deepcopy__  s     	MM'') 	"DAq''$--40 "HQK	" !!!8###(6*HX,>?	NN$ 	&DAq$%Iq!	&  '345tyy~~G $$))A,	's   B		ACCc                     || _         y r&   r   )r)   ds     r+   __setstate__zProxy.__setstate__  s	    r,   c                 F    | j                   j                  dd| f|z   |      S )Ncall_method__call__)r   r   r)   r?   rX   s      r+   r   zProxy.__call__  s$    {{''zD7T>SYZZr,   c                     t        j                         }|J |j                  }|J t        t	        j
                  |j                              }t        j                  dk\  rddl	m
}  |||j                  d       }n|j                  dz  }||   }|j                  dk(  r fdt        |j                        D        S  j                  j!                         S )	N      r   bisect_leftc                     | j                   S r&   offsetr   s    r+   <lambda>z Proxy.__iter__.<locals>.<lambda>  s    STS[S[ r,   key   UNPACK_SEQUENCEc              3   (   K   | ]	  }|     y wr&   r   )r   ir)   s     r+   r   z!Proxy.__iter__.<locals>.<genexpr>  s     8DG8s   )r   r   r   r   disget_instructionsr   sysversion_infobisectr   f_lastiopnamer   argvalr   r   )r)   r   calling_frame	inst_listr   inst_idxinsts   `      r+   __iter__zProxy.__iter__  s    $$&   (((--m.B.BCD	w&*"9m.C.CI[\H$,,1H";;++8U4;;%788{{%%r,   c                 \    | j                   j                  dt        j                  | fi       S Nr]   )r   r   operatorabsr<   s    r+   __abs__zProxy.__abs__  s$    {{''wPRSSr,   c                    | j                   j                  r4t        j                         }|J |j                  }|J t        t        j                  |j                              }t        j                  dk\  rddlm}  |||j                  d       }n|j                  dz  }||   }|j                  dk(  r||dz      }|j                  J ||j                  dz  dz
     }|j                  d	k(  xr |j                   d
k(  xs |j                  dk(  }	|	r3|j                  dk(  r$| j                   j#                  dt$        | fi        y| j                   j'                  |       S )Nr   r   r   c                     | j                   S r&   r   r   s    r+   r   z Proxy.__bool__.<locals>.<lambda>  s
    ahh r,   r   r   POP_JUMP_IF_TRUEr   LOAD_GLOBALAssertionErrorLOAD_ASSERTION_ERRORRAISE_VARARGSr]   T)r   rP   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )
r)   r   r   instsr   curr   firstlaststarts_with_asserts
             r+   __bool__zProxy.__bool__  sO   ;;$$ ((*E$$$!LLM ,,,--m.B.BCDE7*.!%)>)>DVW#++q0:D{{00cAgxx+++TXX]Q./&+llm&C&hXhHh 'P).9O)O #%$++*HKK,,_i$RTU{{""4((r,   c                 8    | j                   j                  |       S r&   )r   r   r<   s    r+   r   z
Proxy.keys  s    {{%%r,   c                     t        d      )Nz'len' is not supported in symbolic tracing by default. If you want this call to be recorded, please call torch.fx.wrap('len') at module scope)r   r<   s    r+   __len__zProxy.__len__  s     * + 	+r,   c           	      t    |r|nd}|r|ni }i  fd}t         j                  j                  j                  ||       t         j                  j                  j                  ||       t	              dkD  r(t        dt        j                                d|       t        t        j                                     }t        |t         j                  j                        r.|j                  f|z   }|j                  d|j                  ||      S t         j                   j#                  |      r|j                  d|j$                  ||      S t        |t         j&                  j(                        rt        d      |j                  d||||j*                  j-                  |j$                        	      S )
Nr   c                 >    t        |       rd | j                  <   y y r&   )ry   r   )r   clstracerss    r+   find_tracerz-Proxy.__torch_function__.<locals>.find_tracer  s     !S!$(! "r,   r   z!Found multiple different tracers z" while trying to trace operations r   z1Unable to symbolically trace HigherOrderOperatorsr]   rY   )rj   fxro   r   lenr   r   r   nextr   ry   _CScriptMethodownerr   rY   	overridesis_tensor_method_or_propertyr-   r   r   rM   _target_to_str)r  orig_methodtypesr?   rX   r  r   r  s   `      @r+   __torch_function__zProxy.__torch_function__  ss   t!r$&	) 	##D+6##FK8w<!!B4CWBX Y==HM K L Ld7<<>*+k588#8#89%%'$.D&&}k6F6FfUU??77D&&}k6J6JDRXYY+uzz'E'EF"#VWW&&T6,2LL,G,GH\H\,] ' _ _r,   r&   )r[   r   )r[   r   r   )r-   r.   r/   r0   r   r   r(   r1   r   r   r   r   r   r   r   r   r   r  r   r  r   r  classmethodr'  r   r,   r+   r   r   k  s    8 $/T +A  0*# *"
d D ,[&(7+ &"T)$ )8 $/& 0&+
 _ _r,   r   c                   J    e Zd Z ed      dedefd       Zed        Zd Z	y)	r   Tr    rootattrc                 P    || _         || _        |j                  | _        d | _        y r&   )r*  r+  r   _node)r)   r*  r+  s      r+   r(   zAttribute.__init__  s"    		kk%)
r,   c                     | j                   G| j                  j                  dt        | j                  | j
                  fi       j                  | _         | j                   S r  )r-  r   r   r   r*  r+  ro   r<   s    r+   ro   zAttribute.node  sK     ::11/7TYYX\XaXaLbdfgllDJzzr,   c                 n    | j                   j                  d| j                  | j                  f|z   |      S )Nr   )r   r   r+  r*  r   s      r+   r   zAttribute.__call__"  s.    {{''tyy499,QUBUW]^^r,   N)
r-   r.   r/   r   r   r1   r(   propertyro   r   r   r,   r+   r   r     sA    $/*U *# * 0*  _r,   r   c                   p     e Zd ZdZdedef fdZdefdZe	d        Z
d Zd	 Ze	d
        Zd Zd Z xZS )r   z
    A special proxy which lets "shape", "size", "dim", and a few other
    attribute accesses pass through to the underlying  module parameter object,
    so that conditional tests on these attributes will not throw exception during tracing
    r   ro   c                     t         |   ||       t        |t        j                  j
                        sJ || _        || _        y r&   )r'   r(   ry   rj   nn	ParameterparamrY   )r)   r   ro   rY   r5  r*   s        r+   r(   zParameterProxy.__init__-  s:    v&%!3!3444
	r,   r[   c                 "    d| j                    dS )NzParameterProxy(r   r  r<   s    r+   r   zParameterProxy.__repr__3  s     1--r,   c                 .    | j                   j                  S r&   )r5  shaper<   s    r+   r8  zParameterProxy.shape6  s    zzr,   c                 6    | j                   j                         S r&   )r5  sizer<   s    r+   r:  zParameterProxy.size:  s    zz  r,   c                 6    | j                   j                         S r&   )r5  dimr<   s    r+   r<  zParameterProxy.dim=  s    zz~~r,   c                 .    | j                   j                  S r&   )r5  ndimr<   s    r+   r>  zParameterProxy.ndim@  s    zzr,   c                 6    | j                   j                         S r&   )r5  numelr<   s    r+   r@  zParameterProxy.numelD  s    zz!!r,   c                 6    | j                   j                         S r&   )r5  nelementr<   s    r+   rB  zParameterProxy.nelementG  s    zz""$$r,   )r-   r.   r/   r0   r   r   r(   r1   r   r0  r8  r:  r<  r>  r@  rB  r2   r3   s   @r+   r   r   &  sc    
z  .# .    !   "%r,   r   c                 j      fd} |_         d j                  d       d}t        t        ||       y )Nc                  j    | d   j                   }t        t              }|j                  d|| |      S )Nr   r]   )r   r   r  r   )r?   rX   r   rW   methods       r+   implz_scope.<locals>.implM  s3    !W^^FXv.F&&fMMr,   ___)r-   stripsetattrr   )rE  rF  as_magics   `  r+   r:   r:   L  s6    	N S)*"-x&r,   c                 x     d j                  d       d} fd}||_        ||_        t        t        ||       y )N__rrH  rG  c                 d    t        t              }| j                  j                  d||| fi       S r  )r   r  r   r   )r)   rhsrW   orig_method_names      r+   rF  z!_define_reflectable.<locals>.implY  s/    #34{{''#tbQQr,   )rI  r-   r/   rJ  r   )rP  method_namerF  s   `  r+   _define_reflectablerR  V  sA    (..s34B7KR  DM#DE;%r,   );r   r   r8   r   rj   r   r  r   loggingdataclassesr   r   rM   r   r   r   torch.utils._tracebackr	   typingr
   r   r   r   r   r   r   ro   r   r   r   r   r   _compatibilityr   operator_schemasr   torch.fx.tracebackr  	tracebackrd   __all__	getLoggerr-   rm   r   r   rh   r   r   r   
ValueErrorr   r   r   r   rE  r:   rR  rP  r   r,   r+   <module>r^     s    
  
      , C B 4 N N N C C ) 9 ) )"
 g! e,' ' -'< e,  -:  d+i( i( ,i(Z d+%: % ,% e, - d+	 	 ,	 d+b_ b_ ,b_J d+_ _ ,_( e,!%U !% -!%H  	F' 6N	& 2 *()*r,   