
    [Th              	       V   % S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	r	S SK
Jr  S SKJrJrJr  S SKJrJrJrJrJr  S SKrS SKJs  Jr  S SKJr  S SKJr  SSKJ r   SS	K!J"r"  SS
K#J$r$J%r%J&r&  SSK'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.J/r/J0r0J1r1J2r2  \Rf                  \Rh                  -  r5\Rl                  Rn                  Rp                  r9\\:S'   \Rl                  Rn                  Rv                  r<\\:S'   0 r=\>\?S4   \:S'   Sq@S rA\ " SS9 " S S\?5      5       rBS\S\CS\4S jrD\ " SS9 " S S5      5       rE\E" 5       rF\ " SS9 " S S\E5      5       rGS rH\ " SS9 " S  S!\25      5       rI0 rJ\>\K\C\L4   \>4   \:S"'   / rM\N\K\?\L4      \:S#'   \R                  R                  S$5      S%:X  a  \MR                  \R                  S&45        S' rSS( rTS) rU " S* S+\5      rV " S, S-\V5      rW " S. S/\V5      rX " S0 S1\V5      rY " S2 S35      rZSq[\\Z   \:S4'   \R                  S5 5       r]\R                  S6 5       r^S7\Z4S8 jr_S7\ZS9\>\L\4   S:\`\C   4S; jra\ " SS9S<\\L\4   4S= j5       rb\ " SS9 SCS>\\Rl                  Rn                  \S?\4   4   S@\\>\L\4      S\(4SA jj5       rc\bSB 5       rdg)D    N)chain)CodeTypeFunctionType
ModuleType)AnyCallable
NamedTupleOptionalUnion)ScriptObject)FakeScriptObject   )compatibility)_make_graph_module)_PyTreeCodeGen_PyTreeInfoGraph)GraphModule)Argument
base_typesmap_aggregate)ParameterProxyProxyScopeScopeContextManager
TracerBase_orig_module_call_orig_module_getattr_proxyable_classesFc                      [         $ N)_is_fx_tracing_flag     P/var/www/auris/envauris/lib/python3.13/site-packages/torch/fx/_symbolic_trace.pyis_fx_tracingr&   (   s    r$   Tis_backward_compatiblec                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )ProxyableClassMeta,   aF  
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                 P   > [         R                  U 5        [        TU ]  XU5        g r!   )r   
setdefaultsuper__init__)clsnamebasesattrs	__class__s       r%   r/   ProxyableClassMeta.__init__]   s     %%c*e,r$   c                 B  ^ U R                  U 5      n[        5       (       d  U R                  " U/UQ70 UD6  U$ / mU4S jn[        X5        [        X$5        [	        T5      S:w  a"  TS   R
                  nUR                  SXU5      $ U R                  " U/UQ70 UD6  U$ )Nc                 T   > [        U [        5      (       a  TR                  U 5        g g r!   )
isinstancer   append)afound_proxiess    r%   check_proxy0ProxyableClassMeta.__call__.<locals>.check_proxyj   s#    !U##$$Q' $r$   r   call_function)__new__r&   r/   r   lentracercreate_proxy)r0   argskwargsinstancer<   rA   r;   s         @r%   __call__ProxyableClassMeta.__call__a   s    ;;s#LL3D3F3O	( 	d(f*}""1%,,F&&6JJLL3D3F3Or$   r#   )	__name__
__module____qualname____firstlineno____doc__r/   rF   __static_attributes____classcell__r4   s   @r%   r*   r*   ,   s    -^- r$   r*   fnnargsreturnc                 n   U R                   nUR                  [        ) -  n[        US5      (       a  USSUR                  UR
                  UUR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                   UR"                  4nGO%[        US5      (       a  USSUR                  UR
                  UUR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                   UR"                  4nOUSUR                  UR
                  UUR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                   UR"                  4n[%        U6 n['        XPR(                  U R*                  U R,                  U R.                  5      $ )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_namerT   co_firstlineno	co_lnotabco_exceptiontableco_freevarsco_cellvarsr   r   __globals__rH   __defaults____closure__)rP   rQ   corW   co_argsnew_codes         r%   _patch_functionrm   y   s   	B{{l]*Hr=!! MMOOJJLLKKNNNNJJNNLL  NNNN%
( 
)	*	*MMOOJJLLKKNNNNJJLLNNNN!
( MMOOJJLLKKNNNNJJLLNNNN
" !H.."++r r$   c                       \ rS rSrSrS rSrg)PHBase   =
Object representing an input placeholder to `concrete_args`
c                     g)NPHr#   selfs    r%   __repr__PHBase.__repr__   s    r$   r#   N)rH   rI   rJ   rK   rL   rv   rM   r#   r$   r%   ro   ro      s    r$   ro   c                   >   ^  \ rS rSrSrSS\\   4U 4S jjjrSrU =r	$ )
PHWithMeta   rq   ph_keyc                 .   > [         TU ]  5         Xl        g r!   )r.   r/   r{   )ru   r{   r4   s     r%   r/   PHWithMeta.__init__   s     r$   )r{   r!   )
rH   rI   rJ   rK   rL   r
   strr/   rM   rN   rO   s   @r%   ry   ry      s    x}  r$   ry   c                     [        U 5       HV  n[        X5      n[        U5      (       a  M   UR                  S5      (       a  M8  [	        X5      (       a  MJ  [        XU5        MX     g )N__)dirgetattrcallable
startswithrY   setattr)frto	attr_nameattr_vals       r%   _transfer_attrsr      sK    W	2)""((..B**B8, r$   c                     ^  \ rS rSr% Sr\" SS9\4SS4S\\   S\\	S	4   S
\
SS4U 4S jjj5       r\R                  " \5      r\\\4   \S'   \" SS9S\S\4S j5       r\" SS9S\SS4U 4S jj5       r\" SS9S\R.                  R0                  S\S\
4S j5       r\" SS9S\R.                  R0                  S\4S j5       r\" SS9S\R.                  R0                  S\	S	\4   S\\S	4   S\\\4   S\4
S j5       r\" SS9S\S\S\\\4   4S  j5       r\" SS9S(S! j5       r\" SS9 S(S"\\R.                  R0                  \	S	\4   4   S#\\\\4      S\ 4S$ jj5       r!S% r"S& r#S'r$U =r%$ ))Tracer   a  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autowrap_modulesautowrap_functions.param_shapes_constantrR   Nc                 0  > [         TU ]  5         [        R                  " S U 5       5       VVs1 s H:  u  pEUR	                  S5      (       a  M  [        U5      (       d  M/  [        U5      iM<     snnU l        U R                  R                  U Vs1 s H  n[        U5      iM     sn5        [        U5      U l
        X0l        SU l        SU l        [        SS5      U l        [         R"                  " 5       U l        0 U l        0 U l        gs  snnf s  snf )aG  
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              3   T   #    U  H  oR                   R                  5       v   M      g 7fr!   )__dict__items).0ms     r%   	<genexpr>"Tracer.__init__.<locals>.<genexpr>#  s"      3,<q

  "",<s   &(_N )r.   r/   r   from_iterabler   r   id_autowrap_function_idsupdatelist_autowrap_searchr   submodule_pathsroot_module_namer   scopecollectionsOrderedDictmodule_stack	num_callsnode_name_to_scope)ru   r   r   r   r1   valuefr4   s          r%   r/   Tracer.__init__   s    B 	  %22 3,<3  1
  ??3'	  -5UO	 BuI 1
# 	##**;M+N;MaBqE;M+NO 377G2H%:"EI%'2t_
'335)+?A-1
 ,Os   DD"DD_qualname_counterprefixc                     U S3n[        U R                  U5      (       d  SU R                  U'   U$ U R                  U   n U U 3nUS-  n[        U R                  U5      (       d  OM)  X0R                  U'   U$ )z
Gets a fresh name for a prefix and returns it. This function ensures
that it will not clash with an existing attribute on the graph.
0r   r   )rY   rootr   )ru   r   qualnameis       r%   get_fresh_qualnameTracer.get_fresh_qualname;  s     XQ<tyy(++-.D""6*O""6* !~HFA499h//	 
 *+v&r$   r:   r   c                   >^  [        U[        R                  R                  5      (       aH  T R                  R                  5        H  u  p#XL d  M  T R                  SUS0 5      s  $    [        S5      e[        U[        R                  5      (       a>  T R                  R                  5        H  u  pEXL d  M  T R                  SUS0 5      s  $    Of[        U[        R                  R                  5      (       a=  T R                  R                  5        H  u  pEXL d  M  T R                  SUS0 5      s  $    [        U[        5      (       aD  [        US5      (       a3  [        U 4S jU 5       5      nT R                  SUR                  U0 5      $ [        U[        R                  [        [         45      (       a  T R"                  R%                  U5      nU(       dp  [        U[        R                  5      (       a  SOSnT R'                  U5      n[        U[(        5      (       d   eUT R"                  U'   [+        T R                  Xq5        T R                  SUS0 5      $ [-        U5      [.        ;   aj  T R'                  S	UR                  R0                   S
35      n[        U[(        5      (       d   e[+        T R                  Xq5        T R                  SUS0 5      $ [2        T	T ]i  U5      $ )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   F   >#    U  H  nTR                  U5      v   M     g 7fr!   )
create_arg)r   elemru   s     r%   r   $Tracer.create_arg.<locals>.<genexpr>  s     =14..1s   !r>   _tensor_constant_torchbind_objr   
_constant_)r8   torchnn	Parameterr   named_parameterscreate_node	NameErrorTensornamed_buffersModulenamed_modulestuplerY   r4   r   r   tensor_attrsgetr   r~   r   typer   rH   r.   r   )
ru   r:   npn_p_rC   r   	base_namer4   s
   `        r%   r   Tracer.create_argU  sc   @ a++,,		2246++J2rBB 5 FGG5<<(())1137++JBCC 4 588??++))1137++JBCC 4
 aGAy$9$9=1==D##OQ[[$KK a%,,6FGHH&*&7&7&;&;A&>H  "!U\\22 ') 
  229=!(C0000'/!!!$		8/##J"bAA7((
 ..1;;3G3G2H
/STHh,,,,DIIx+##J"bAAw!!$$r$   r   module_qualified_namec                     UR                   R                  S5      =(       d    UR                   R                  S5      =(       a)    [        U[        R                  R
                  5      (       + $ )a  
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)rI   r   r8   r   r   
Sequential)ru   r   r   s      r%   is_leaf_moduleTracer.is_leaf_module  sP    * LL##J/ 6||&&}55 Q 3 344	5r$   modc                    U R                   (       aB  U R                   R                  U5      nUc  [        S5      e[        U[        5      (       d   eU$ U R
                  R                  5        H  u  p4XL d  M  Us  $    [        S5      e)aF  
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.
z&module is not installed as a submodule)r   r   r   r8   r~   r   r   )ru   r   pathr   r   s        r%   path_of_moduleTracer.path_of_module  s     ''++C0D| HIIdC((((K 		//18H 2 DEEr$   forwardrC   rD   c           	      @   U R                  U5      n[        U R                  [        U[	        U5      5      5       nU R
                  R                  US5      nUS:  a  UR                   SU 3OUR                  nXVR                  4U R                  U'   US-   U R
                  U'   U R                  X5      (       d	  U" U0 UD6n	OU R                  SXSU5      n	U R                  R                  SS9u  pX:X  d
   SU
 35       e SSS5        U	$ ! , (       d  f       W	$ = f)	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.
r   @r   call_moduleT)lastz Unexpected key N)r   r   r   r   r   r   r   module_pathmodule_typer   r   rB   popitem)ru   r   r   rC   rD   r   _scoper   
module_keyret_valkeyr   s               r%   r   Tracer.call_module  s8   D !% 3 3A 6 JJ3T!W=
 **+@!DI q= %%&a	{3'' 
 .CDVDV,WDj)4=MDNN01&&q@@!4262++!#8 &&..D.9FC$>(8&>>$)
, -
 
, s   CD
Dattrr   parameter_proxy_cachec                 b  ^  U 4S jn[        U[        R                  R                  5      (       a'  U" UT R                  R                  5       U5      nUb  U$ T R                  (       aF  [        U[        R                  5      (       a'  U" UT R                  R                  5       U5      nUb  U$ U$ )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                   >^ ^ U H  u  mnT UL d  M  TU;  ah  0 nS[         R                  " TR                  5      R                  ;   a  TR                  (       d  S OU UU4S jUS'   TR                  " STS0 40 UD6nXRT'   UT   s  $    g )Nproxy_factory_fnc                     > [        TU TT5      $ r!   )r   )noder   r   ru   s    r%   <lambda>BTracer.getattr.<locals>.maybe_get_proxy_for_attr.<locals>.<lambda>C  s    .$($83"r$   r   r#   )inspect	signaturerB   
parametersr   )r   collection_to_searchr   r   rD   	val_proxyr   ru   s   `     @r%   maybe_get_proxy_for_attr0Tracer.getattr.<locals>.maybe_get_proxy_for_attr5  s     -1q= 55!#.&001B1BCNNO
 (,'A'A !%&" ##56 %)$5$5j!R$Vv$V	3<a0033# -$ r$   )	r8   r   r   r   r   r   proxy_buffer_attributesr   r   )ru   r   r   r   r   maybe_parameter_proxymaybe_buffer_proxys   `      r%   r   Tracer.getattr  s    0	. h 2 233$<$))4468M%! %0,,''Jx,N,N!9$))1135J" "-))r$   c                   ^ ^^^^^^ [         R                  " T5      mTR                  nUR                  UR                  -   n[        UR                  5      n[        UR                  5      n/ nSn	U(       a9  US:X  a  [        S5      eSn	[        U5        UR                  T R                  5        [         R                  " T5      mSn
[        T[        5      (       a  [        T5      S:  a  UR                   ["        -  (       ar  US:X  al  T Hb  nT R%                  SSU
 3S0 5      n[        U[&        5      (       a  U[(        :w  a  [+        XR,                  S9  UR                  U5        U
S-  n
Md     TU4$ [/        X5       Vs/ s H  n[        U5      PM     nn[        T[        5      (       aQ  [        U5      [        T5      :w  a$  [        S[        U5       S	[        T5       S
35      e[1        [3        UT5      5      mUUU U4S jmUR5                  U4S jU 5       5        UR                  S:  d  UR                   ["        -  (       a  UR                   [         R6                  -  (       a#  UR                  T" S[        U5      -   5      5        UR                   [         R8                  -  (       a#  UR                  T" S[        U5      -   5      5        [;        T[        U5      5      m[<        R>                  " [        U5      5      u  nm[A        S TRB                   5       5      (       d4  [E        [G        USU TS5      5      T RH                  l%        UUU 4S jnUU4$ TU4$ s  snf )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   placeholderinput_r#   r   r   zTracing expected z arguments but got z concrete argumentsc                 ,   > TR                  U TTT5      $ r!   )_proxy_placeholder)r1   concrete_argsfn_for_analysisru   sigs    r%   proxy_placeholder6Tracer.create_args_for_root.<locals>.proxy_placeholder  s    **4_UUr$   c              3   4   >#    U  H  nT" U5      v   M     g 7fr!   r#   )r   namesr  s     r%   r   .Tracer.create_args_for_root.<locals>.<genexpr>  s     D)%e,,)s   *z**c              3   @   #    U  H  oR                  5       v   M     g 7fr!   )is_leaf)r   childs     r%   r   r    s     G0Fu==??0Fs   Nc                  d  > [         R                  " [        U 5      T5      nT" U6 n[         R                  " U5      u  p4[	        TR
                  R                  [        5      (       d   eTR
                  R                  R                  R                  US9TR
                  R                  l        U$ )N)out_spec)
pytreetree_unflattenr   tree_flattenr8   graph_codegenr   pytree_info_replace)rC   	tree_argstree_outout_argsr  in_specroot_fnru   s        r%   
flatten_fn/Tracer.create_args_for_root.<locals>.flatten_fn  s    "11$t*gF	"I.%+%8%8%B"!$**"5"5~FFFFJJ''33<<h<O 

##/  r$   )&r   unwraprV   co_argcountco_kwonlyargcountr   r_   iterRuntimeErrornextr9   r   r   r8   r   r@   rW   rX   rB   ro   rs   r   r   rangedictzipextend
CO_VARARGSCO_VARKEYWORDSrm   r  r  allchildren_specsr   r   r  r  )ru   r  	is_moduler  rj   
total_args	orig_args
names_iterrC   skip_arg_idxname_idxconcrete_argoutidx	arg_names	flat_argsr  r  r  r  r  s   `` `             @@@@r%   create_args_for_rootTracer.create_args_for_root]  s    "..1%%^^b&:&::
(	"..)
Q"J  LKK		"0
 }e,,M"Q&|+a -''z7JBPRSlF33#r) (<HHEC A !. D= 16|1PQ1P#T*%1P	QmU++9~]!33"'I'77J3}K]J^^qr  !Y!>?M	V 	V 	D)DD!#r{{\'A{{W///-cD4D.DEF{{W333-dT*5E.EFG%gs4y9G#00t=	7G0F0FGGG #1Ikz2GTB#DJJ  y((}S Rs   M'r   r  c                 l  ^ ^^^ [         nSq  [        U[        R                  R                  5      (       a  SSKJn  UR                  U5        UT l        [        [        U5      T R                  5      (       d*   ST R                   S[        U5      R                   35       e[        [        U5      T R                  5      nUR                  5       T l        UR!                  5        VVs0 s H  u  pgXv_M	     snnT l        O%[        R                  R	                  5       T l        Un[        T SS5      n[%        US9T l        [        US	5      (       a?  UR(                  n	U	R*                  U	R,                  U	R.                  S
.T R&                  l        0 T l        S[        R                  R                  S[4        [6           4UU 4S jjmT" T R                  / 5        [        U[8        5      (       d   eUR:                  n
T R=                  U[        U[        R                  R                  5      U5      u  p[0 m[>        R@                  " [B        5      UU 4S j5       n[>        R@                  " [D        5      UU 4S j5       n[G        5        mTRI                  [        R                  R                  SUSS9  TRI                  [        R                  R                  SUSS9  [K        T5        [M        TU
T RN                  5        T RP                   H$  n[M        TURR                  T RN                  5        M&     T RU                  SST RW                  U" U6 5      40 URX                  R[                  SS5      S9  SSS5        ST l         Uq T R&                  $ s  snnf ! , (       d  f       N*= f! [\         ax  n[        UR^                  S   [6        5      (       aP  SUR^                  S   ;   a=  [a        ST R&                  Rc                  SSS9Rd                  -   [f        Rh                  S9  e SnAff = f! Uq f = f)aQ  
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``.
Tr   )_LazyGraphModuleztraced_func_name=z doesn't exist in r4   N)
tracer_clsrV   )ra   r`   rb   r   prefix_atomsc                 0  > U R                   R                  5        HR  u  p#[        U[        R                  [
        [        45      (       d  M1  SR                  X/-   5      TR                  U'   MT     U R                  5        H  u  p#T" X1U/-   5        M     g )N.)
r   r   r8   r   r   r   r   joinr   named_children)r   r>  kvcollect_tensor_attrsru   s       r%   rE  *Tracer.trace.<locals>.collect_tensor_attrs  sy    JJ,,.DA!!ellLBR%STT/2xxs8J/K))!, / ,,.DA(A3,>? /r$   c                 >   > [        X5      nTR                  XT5      $ r!   )r   r   )r   r   r   r   ru   s      r%   module_getattr_wrapper,Tracer.trace.<locals>.module_getattr_wrapper  s    /:||D4IJJr$   c           
         >^  U 4S jn[        T[        [        T ST 5      S0 5      TR                  5        TR                  T X1U5      $ )Nc                  "   > [        T/U Q70 UD6$ r!   )r   )rC   rD   r   s     r%   r   :Tracer.trace.<locals>.module_call_wrapper.<locals>.forward%  s    ,SB4B6BBr$   r   rg   )_autowrap_checkr   r   r   )r   rC   rD   r   patcherru   s   `   r%   module_call_wrapper)Tracer.trace.<locals>.module_call_wrapper#  sK    C  GCC8-L//
 ''WFCCr$   __getattr__F)deduplicaterF   outputrR   	type_exprzdata-dependent
ru   )root_moduleverbose)file)5r"   r8   r   r   r   torch.fx._lazy_graph_moduler<  force_recompiler   rY   r   traced_func_namerH   r   	_get_namer   r   r   r   r  rV   ra   r`   rb   
_co_fieldsr   r   r~   r   rg   r9  	functoolswrapsr   r   _new_patcherpatch_method_patch_wrapped_functionsrM  r   r   r   r   r   __annotations__r   r$  rC   printpython_codesrcsysstderr)ru   r   r  old_is_fx_tracing_flagr<  rP   r1   r   r=  code
fn_globalsrC   rH  rO  moduleerE  r   rN  s   `               @@@r%   traceTracer.trace  s   < "5"z	9$00
 I 006 	J 5 5  f&t'<'<&==OPTUYPZPcPcOdef  T$Z)>)>?(,(8%CGCUCUCW'XCWid	CW'X$!HHOO-	18{D1QJ*5DJr:&&{{#||#'#3#3&*&9&9)

%  @ @tCy @ @ !B/b,////J00JtUXX__5}HB  " __12K 3K __./	D 0	D 7$$HHOO!* %	 %  $$HHOO' %	 %  )1T5P5PQ"33F#$2M2M 4   __RY/1 0044XtD ! )  8 $(D  #9zzS (Y|  :  	!&&)S)).>!&&).Kjj,,$* $ -  c	
  	 #9sQ   CN* *N8FN* 
C+N5N* N* 
N'#N* *
P,4A3P''P,,P/ /P3c                     [         R                  [         5      nU R                  R                  5        HF  u  p4US;   a  [        R                  " U5      nO[        R
                  " XA5      nXRR                  U'   MH     U$ )N>   r   )r   r?   r   r   copydeepcopy)ru   memo
new_tracerrC  rD  new_objs         r%   __deepcopy__Tracer.__deepcopy__\  sc    ^^F+
MM'')DA(())A,--0%," * r$   c           
      `  ^ ^^^ Ub*  TU;   a$  SmUUU U4S jn[         R                  " XRT   5      $ TS   S:X  a  SnOETR                  T   nUR                  [        R
                  R                  L a  SOUR                  4nT R                  STU0 UR                  R                  TS 5      S9$ )Nr   c                   > TS-  mTR                   T   nUR                  [        R                  R                  L a  SOUR                  4nTR                  ST S[        T5       3U0 5      n[        U [        5      (       a  U [        :w  a  [        XR                  S9  U$ [        U 5      [        :X  d0  [        U 5      [        ;   a>  [        U 5      [        R                   :w  a!  [        R"                  " X0:H  T SU  S35        U $ U c!  UT S34nTR                  S	[$        U0 5        U $ [&        R(                  " S
T S35        U $ )Nr   r#   r   r   r  z$ has been specialized to have value z but got another valuez> has been specialized to have value None but got another valuer>   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   emptyrB   r~   r8   ro   rs   r   r   r   boolr   r   r   _assert_assert_is_nonewarningswarn)	xparamr{  r5  rC   cntr1   ru   r  s	        r%   
replace_ph-Tracer._proxy_placeholder.<locals>.replace_phn  sH   qt,--7+<+<+B+BBBHX  ''!dV1SXJ#7" a((Bw (1:J7d?d1g&;Q5<<@WMM& DQCG]^"  Y& ^_D %%obQ  MMSTXSY ZD E r$   r  r#   r   rT  )
r  tree_mapr   r{  r   r   r|  rB   rd  r   )	ru   r1   r  r  r  r  r{  r  r  s	   `` `    @r%   r  Tracer._proxy_placeholderj  s    $)>C) )V ??:T/BCC7c>')GNN4(Emmw'8'8'>'>>U]]DT    %5599$E ! 
 	
r$   )r   r   r  r   r   r   r   r   r   r   r   r   r!   )&rH   rI   rJ   rK   rL   r   mathr   r   r   r}  r/   r   defaultdictintr   r'  r~   rd  r   r   r   r   r   r   r   r   r   r   r9  r   r
   r   ro  rw  r  rM   rN   rO   s   @r%   r   r      sz   	 $/ 04g35&+	:B
+:B "(C-0:B  $	:B
 
:B 0:Bx )4(?(?(DtCH~D$/   02 $/V%C V%J V% 0V%p $/5 5 5PT 5 050 $/F%((// Fc F 0F4 $/888??8 #s(#8 CHo	8
 S#X8 
8 08t %0<C <3 <tCQTH~ < 1<~ %0_ 1_B $/ 37ZEHHOOXc3h%778Z  S#X/Z 
	Z 0Zx=
 =
r$   r   _wrapped_fns_to_patch_wrapped_methods_to_patchFX_PATCH_GETITEM1__getitem__c                  .   ^ SmU4S jn[        X5        T$ )z\
Recursively search a data structure for a Proxy() and return it,
return None if not found.
Nc                 6   > [        U [        5      (       a  U mg g r!   )r8   r   )r  proxys    r%   
find_proxy_find_proxy.<locals>.find_proxy  s    aE  r$   )r   )objects_to_searchr  r  s     @r%   _find_proxyr    s    
 E
 #0Lr$   c                 F   ^  [         R                  " T 5      U 4S j5       nU$ )Nc                     > [        X5      nUb8  UR                  R                  STX5      nSUR                  R                  S'   U$ T" U 0 UD6$ )a&  
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.
r>   T
is_wrapped)r  rA   rB   r   meta)rC   rD   r  return_proxyorig_fns       r%   wrapped%_create_wrapped_func.<locals>.wrapped  s^     D) <<44$L 48L""<0'''r$   )r_  r`  )r  r  s   ` r%   _create_wrapped_funcr    s%    __W( (  Nr$   c                 b   ^^ [        U T5      m[        R                  " T5      UU4S j5       nU$ )Nc                  j   > [        X5      nUb  UR                  R                  STX5      $ T" U 0 UD6$ )z
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.
call_method)r  rA   rB   )rC   rD   r  r1   r  s      r%   r  '_create_wrapped_method.<locals>.wrapped  s>     D)<<,,]D$OO'''r$   )r   r_  r`  )r0   r1   r  r  s    ` @r%   _create_wrapped_methodr    s1    c4 G__W
( 
( Nr$   c                   J    \ rS rSr% \\S'   \\S'   \\S'   \\S'   S rS rSr	g	)

_PatchedFni  
frame_dictfn_namer  new_fnc                     [         er!   NotImplementedErrorrt   s    r%   revert_PatchedFn.revert      !!r$   c                     [         er!   r  rt   s    r%   patch_PatchedFn.patch  r  r$   r#   N)
rH   rI   rJ   rK   r   rd  r~   r  r  rM   r#   r$   r%   r  r    s     OLLK""r$   r  c                        \ rS rSrS rS rSrg)_PatchedFnSetItemi  c                 J    U R                   U R                  U R                  '   g r!   )r  r  r  rt   s    r%   r  _PatchedFnSetItem.revert  s    (,%r$   c                 J    U R                   U R                  U R                  '   g r!   r  r  r  rt   s    r%   r  _PatchedFnSetItem.patch      (,%r$   r#   NrH   rI   rJ   rK   r  r  rM   r#   r$   r%   r  r    s    54r$   r  c                        \ rS rSrS rS rSrg)_PatchedFnDeli
  c                 2    U R                   U R                  	 g r!   )r  r  rt   s    r%   r  _PatchedFnDel.revert  s    OODLL)r$   c                 J    U R                   U R                  U R                  '   g r!   r  rt   s    r%   r  _PatchedFnDel.patch  r  r$   r#   Nr  r#   r$   r%   r  r  
  s    *4r$   r  c                        \ rS rSrS rS rSrg)_PatchedFnSetAttri  c                 Z    [        U R                  U R                  U R                  5        g r!   )r   r  r  r  rt   s    r%   r  _PatchedFnSetAttr.revert  s    t||<r$   c                 Z    [        U R                  U R                  U R                  5        g r!   )r   r  r  r  rt   s    r%   r  _PatchedFnSetAttr.patch  s    t{{;r$   r#   Nr  r#   r$   r%   r  r    s    =<r$   r  c            	          ^  \ rS rSrSU 4S jjr SS\\\4   S\S\S\	4S jjr
 SS\S\S\S\	4S	 jjrS
\4S jrS rS rS rS rSrU =r$ )_Patcheri  c                 N   > [         TU ]  5         / U l        [        5       U l        g r!   )r.   r/   patches_madesetvisited)ru   r4   s    r%   r/   _Patcher.__init__  s    .0!$r$   r  r1   r  rR  c                    XCl         X!;  aY  [        [        U5      (       aD  U R                  R	                  [        XSU5      5        U R                  S   R                  5         g[        X   SS5      (       a  gU R                  R	                  [        XX   U5      5        U R                  S   R                  5         g)zI
Replace frame_dict[name] with new_fn until we exit the context manager.
N__fx_already_patchedF)	_Patcher__fx_already_patchedrY   builtinsr  r9   r  r  r   r  )ru   r  r1   r  rR  s        r%   r  _Patcher.patch   s     '2#!gh&=&=$$]:T6%RSb!'')Z%'=uEE$$!*J4DfM b!'')r$   r0   c                     XCl         [        X5      n[        USS5      (       a  gU R                  R                  [	        XXS5      5        U R                  S   R                  5         g)zL
Replace object_or_dict.name with new_fn until we exit the context manager.
r  FNr  )r  r   r  r9   r  r  )ru   r0   r1   r  rR  r  s         r%   rb  _Patcher.patch_method6  sZ     '2##$72E::  !23g!NO"##%r$   thingc                 p    [        U5      nX R                  ;   a  gU R                  R                  U5        g)z<Return True on the first call to with thing, otherwise falseFT)r   r  add)ru   r  r6  s      r%   
visit_once_Patcher.visit_onceC  s-    i,,r$   c                 `    U R                    H  nUR                  5         M     U R                   $ )zA
Remove all the stored patcheds. It doesn't modify patches_made.
)r  r  ru   r  s     r%   revert_all_patches_Patcher.revert_all_patchesK  s)     &&ELLN '   r$   c                 `    U R                    H  nUR                  5         M     U R                   $ )z@
Patch all the stored patcheds. It doesn't modify patches_made.
)r  r  r  s     r%   reapply_all_patches_Patcher.reapply_all_patchesS  s)     &&EKKM '   r$   c                     U $ r!   r#   rt   s    r%   	__enter___Patcher.__enter__[  s    r$   c                     U R                   (       a;  U R                   R                  5       R                  5         U R                   (       a  M;  U R                  R	                  5         g)zD
Undo all the changes made via self.patch() and self.patch_method()
N)r  popr  r  clear)ru   exc_typeexc_valexc_tbs       r%   __exit___Patcher.__exit__^  sH     !!#**,  	r$   )r  r  )rR   N)T)rH   rI   rJ   rK   r/   r'  r~   r   r   r}  r  r   rb  r  r  r  r  r  rM   rN   rO   s   @r%   r  r    s    ' !*cN* * 	*
 *. KO&&"&,4&CG& !! r$   r  CURRENT_PATCHERc               #      #    [         n  [        5       q [         v   [         c   e[         R                  5         U q g ! [         c   e[         R                  5         U q f = f7fr!   )r  r  r  )prior_patchers    r%   ra  ra  k  s]      $M("* *****,' *****,'s   A <  A !AA c               #      #    [         n S nS n U b  U R                  5       nS v   U b  U R                  5       nX:X  d   S5       eg ! U b  U R                  5       nX:X  d   S5       ef = f7f)Nz7CURRENT_PATCHER was changed during a revert_all_patches)r  r  r  )current_patcherr  patches_removeds      r%   _maybe_revert_all_patchesr  y  s     %OLO	E&-@@BO&*>>@L+	ED	E+ &*>>@L+	ED	E+s   A)A  A)!A&&A)rN  c           	      H   [         R                  5       R                  5        HR  u  u  pnX#;  a&  [        [        U5      (       a  [        [        U5      nOX2   nU R                  X2[        U5      5        MT     [         H   u  pRU R                  XR[        XR5      5        M"     g)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  rr  r   rY   r  r   r  r  r  rb  r  )rN  r   r1   r  r  r0   s         r%   rc  rc    s    
 "7!;!;!=!C!C!E	:!gh&=&=h-G &Gj(<W(EF "F /	S(>s(IJ /r$   r  function_idsc                    U R                  U5      (       ap  UR                  5        H[  u  p4UR                  S5      (       a  M  [        U5      (       d  M/  [	        U5      U;   d  M@  U R                  X[        U5      5        M]     gg)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.
r   N)r  r   r   r   r   r  r  )rN  r  r  r1   r   s        r%   rM  rM    sg     *%%%++-KDOOC((UOOuI-j0DU0KL . &r$   
fn_or_namec                    [        U 5      (       d   [        U [        5      (       d  [        S5      e[        U 5      (       a$  [        U [        5      (       a   eU R                  nO[        U [        5      (       d   S5       eU n[
        R                  " 5       nUc   eUR                  nUc   eUR                  R                  S:w  a  [        S5      eUR                  [        [        UR                  5      U4'   U $ )a  
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 namez<module>z0wrap must be called at the top level of a module)r   r8   r~   r$  rH   r   currentframef_backf_codera   r  	f_globalsr  r   )r  r  r  r   s       r%   wrapr    s    H J
:s(C(C
 	

 
j#....%%
 
 	A@	A 
 '')L###A==xx:%!"TUU 9:2akk?G45r$   r   .r  c                     [        5       nUR                  X5      n[        U [        R                  R
                  5      (       a  U R                  R                  OU R                  n[        UR                  X45      $ )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``.
)
r   ro  r8   r   r   r   r4   rH   r   r   )r   r  rA   r  r1   s        r%   symbolic_tracer    sY    l XFLL-E#-dEHHOO#D#D$-- 	 fkk577r$   c                     U b   U5       eg r!   r#   )r   msgs     r%   r  r  )  s    =#=r$   r!   )er  r   
contextlibrr  r_  r   r  osrh  r  	itertoolsr   typesr   r   r   typingr   r   r	   r
   r   r   torch.utils._pytreeutils_pytreer  torch._Cr   "torch._library.fake_class_registryr   _compatibilityr   _lazy_graph_moduler   r  r   r   r   graph_moduler   r   r   r   r   r  r   r   r   r   r   r*  r+  rX   r   r   rF   r   rd  rQ  r   r   r'  r   r"   r&   r*   r  rm   ro   rs   ry   r   r   r  r   r~   r  r   environr   r9   r   r  r  r  r  r  r  r  r  r  contextmanagerra  r  rc  r  rM  r  r  r  r#   r$   r%   <module>r     sP          	 
   4 4 = =  $ $ ! ? ) 2 5 5 % 5 5 P P !!G$:$:: $hhoo66 8 6!&!<!< h <') Dt$ )  d+I I ,IXB BS B\ BR e,  - X e,	 	 -	- d+

Z 

 ,

L 68 tE#s(OT12 7 57 4dCi 01 6::>>$%, $$ellM%BC *&
" 
"4
 44J 4<
 <K K\ '+(# * 
( 
( E E Kh K MM#'S>MADSM" d+<U3=) < ,<~ d+ /3:8
#s(!33
4:8DcN+:8 :8 ,:8z  r$   