
    Ǆg                        U d dl mZ ddlmZmZmZmZmZmZ d dl	m
c mZ ddlmZ ddlmZ d dlmZ d dlZd dlZd dlmZmZmZmZmZmZmZmZmZmZm Z m!Z! d d	l"m#Z# d d
lm$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-Z-g dZ.erddl/m0Z0 ddl1m2Z2 e3ee4ee5ee6ee7eiZ8eee9   gee9   f   Z: G d de      Z;i Z<ee9e;f   e=d<   de9de9defdZ> e>dde+j~                          e>dde+j                          e>dd eAd              e>dde'        e>dde'j                          e>dd e        e>d!d"e       d#e9d$eCfd%ZDd&e9d$e9fd'ZEded$eCfd(ZF G d) d*      ZGi e'j                  d+e'j                  d,e'j                  d-e'j                  d.e'j                  d/e'j                  d0e'j                  d1e'j                  d2e'j                  d3e'j                  d4e'j                  d5e'j                  d6e'j                  d7e'j                  d8e'j                  d9e'j                  d:e'j                  d;e'j                  d<e'j                  d=e'j                  d>e'j                  d?iZ\ ed@A      e# G dB dC                    Z]dDe9dEe9d$e9fdFZ^ G dG dH      Z_ G dI dJ      Z` G dK dLe      Za e#d@M       G dN dO             ZbdPe9fdQZc edRA       G dS dT             Zd G dU dVed      Ze G dW dX      Zf ed@A       G dY dZ             Zgd[d\d]d^d_d_d`dadbdcdddedfdgdhdiZh e4djdkdldmdndodpdqdrds	fi ehZidtdudvdwdxdydzd{d|d}d~ddddZjy)    )defaultdict   )NodeArgumentTargetmap_arg
_type_repr_get_qualified_nameN)_pytree)compatibility)	_NodeIter)TYPE_CHECKINGCallableAnyListDict
NamedTupleOptionalTupleSet	FrozenSetTypeIterable)	dataclass)contextmanager)
PythonCodeCodeGenGraph)GraphModule)Tracerc                   &    e Zd ZU dZeed<   eed<   y)_CustomBuiltinzAdditional objs that we add to every graph's globals.

    The repr() for some standard library objects is not valid Python code without
    an import. For common objects of this sort, we bundle them in the globals of
    every FX graph.
    
import_strobjN)__name__
__module____qualname____doc__str__annotations__r        V/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/fx/graph.pyr"   r"   .   s     O	Hr,   r"   _custom_builtinsnamer#   r$   c                 *    t        ||      t        | <   y N)r"   r.   )r/   r#   r$   s      r-   _register_custom_builtinr2   =   s    +J<Tr,   infzfrom math import infnanzfrom math import nanNoneTypezNoneType = type(None)torchzimport torchdevicezfrom torch import device	fx_pytreez$import torch.fx._pytree as fx_pytreepytreez$import torch.utils._pytree as pytreexreturnc                 J    | j                  d      xr | j                  d      S )N__)
startswithendswithr:   s    r-   	_is_magicrA   J   s    <<2!**T"22r,   sc                     g }d}| D ]T  }|r!|j                         r|j                  d       |j                  |j                                |j                         }V dj	                  |      S )z
    Transforms the given string ``s`` to a Python-style variable name

    Examples:
        ``mod.snake_case`` -> ``mod.snake_case``
        ``mod.pascalCase``-> ``mod.pascal_case``
        ``mod.ALL_CAPS`` -> ``mod.all_caps``
    F_ )isupperappendlowerislowerjoin)rB   chars
prev_lowercs       r-   _snake_caserN   N   sa     EJ !!))+LLQWWYYY[
	!
 775>r,   c                 8   t        | dd       }|A|j                  d      d   }|dk(  xr& |j                  d       xr |j                  d       S t        | dd       }|;|dk7  r6t        t        j                  j
                  fD ]  }t        ||d       | u s y y	)
Nr&   .r   r6   ztorch._dynamo.ztorch._inductor.r%   TF)getattr	partitionr>   r6   nn
functional)r$   module_namebase_moduler/   guesss        r-   _is_from_torchrX   a   s    #|T2K!++C037" ;&&'788;&&'9::	
 3
D)DDGOUXX001 	EudD)S0	 r,   c                   d    e Zd ZdZd Zdedee   defdZdedefdZ	dedede
fd	Zdedefd
Zy)
_Namespacea  A context for associating names uniquely with objects.

    The following invariants are enforced:
    - Each object gets a single name.
    - Each name is unique within a given namespace.
    - Names generated do not shadow builtins, unless the object is indeed that builtin.
    c                     i | _         t               | _        t               | _        t	        t
              | _        t        j                  d      | _	        t        j                  d      | _
        y )Nz[^0-9a-zA-Z_]+z(.*)_(\d+)$)_obj_to_nameset_unassociated_names_used_namesr   int_base_countrecompile_illegal_char_regex_name_suffix_regexselfs    r-   __init__z_Namespace.__init__}   sN    ,.#&5 %(U+6s+;#%::.>#? "$**^"<r,   	candidater$   r;   c                    ||| j                   v r| j                   |   S | j                  j                  d|      }|sd}|d   j                         rd| }| j                  j                  |      }||}d}n |j                  dd      \  }}t        |      }||n| d| }|s| j                  |   }|| j                  v s| j                  ||      r.|dz  }| d| }|| j                  v r| j                  ||      r.| j                  j                  |       || j                  |<   || j                  j                  |       |S || j                   |<   |S )zCreate a unique name.

        Arguments:
            candidate: used as the basis for the unique name, relevant to the user.
            obj: If not None, an object that will be associated with the unique name.
        NrD   _unnamedr   r      )r\   rd   subisdigitre   matchgroupr`   ra   r_   _is_illegal_nameaddr^   )rg   ri   r$   ro   basenumnum_strs          r-   create_namez_Namespace.create_name   s    ?sd&7&77$$S)) ,,00i@	"IQ<!I;I''--i8=DC!KK1-MD'g,CKDvQse_	""4(C4+++t/D/DYPS/T1HC&#I 4+++t/D/DYPS/T 	Y'!$;$$((3  &/Dc"r,   r/   c                     || j                   vsJ || j                  v sJ || j                   |<   | j                  j                  |       y)zpAssociate a unique name with an object.

        Neither `name` nor `obj` should be associated already.
        N)r\   r^   removerg   r/   r$   s      r-   associate_name_with_objz"_Namespace.associate_name_with_obj   sP    
 $+++++t/////!%#  ''-r,   c                     |t         j                  v ry|t        j                  v r|t        j                  |   uS |t        v r|t        |   j
                  uS y)NTF)keywordkwlistbuiltins__dict__r.   r$   ry   s      r-   rq   z_Namespace._is_illegal_name   s\    7>>! 8$$$h//555 ##.t48888r,   c                 x    || j                   v sJ || j                   |<   | j                  j                  |       y r1   )r\   r_   rr   )rg   r$   r/   s      r-   _rename_objectz_Namespace._rename_object   s:    d'''''!%#T"r,   N)r%   r&   r'   r(   rh   r)   r   r   rv   rz   boolrq   r   r+   r,   r-   rZ   rZ   u   sk    =)S )x} ) )V.C .c .S s t ## #S #r,   rZ   bf16f64f32f16f8e4m3fnf8e5m2
f8e4m3fnuz
f8e5m2fnuzc32c64c128i8i16i32i64b8u8u16u32u64b16Tis_backward_compatiblec                   P    e Zd ZU dZeed<   eeef   ed<   eee	ee	   f      ed<   y)r   zZ
    Represents all the information necessary to exec or save a graph as Python code.
    srcglobals_lineno_mapN)
r%   r&   r'   r(   r)   r*   r   r   r   r`   r+   r,   r-   r   r      s7     
H#s(^ $sHSM1233r,   r   rs   targetc                 |    |j                  d      }| }|D ]#  }|j                         s
d| d| d}| d| }% |S )NrP   zgetattr(z, ""))splitisidentifier)rs   r   elemsres        r-   _format_targetr      sX    LLEA ~~1#S2&A#Qqc
A	
 Hr,   c                       e Zd Zd Zd Zd Zy)_InsertPointc                 D    || _         |j                  |c| _        |_        y r1   )graph_insertorig_insert)rg   r   
new_inserts      r-   rh   z_InsertPoint.__init__  s    
*/--'%-r,   c                      y r1   r+   rf   s    r-   	__enter__z_InsertPoint.__enter__  s    r,   c                 :    | j                   | j                  _        y r1   )r   r   r   )rg   typevaluetbs       r-   __exit__z_InsertPoint.__exit__  s    !--

r,   N)r%   r&   r'   rh   r   r   r+   r,   r-   r   r      s    D.r,   r   c                   0    e Zd Zd	dddefdZd Zd Zd Zy)

_node_listr   r   	directionc                 ,    |dv sJ || _         || _        y )N)_next_prev)r   r   )rg   r   r   s      r-   rh   z_node_list.__init__  s    ....
"r,   c                 .    | j                   j                  S r1   )r   _lenrf   s    r-   __len__z_node_list.__len__  s    zzr,   c              #      K   | j                   dk(  s| j                   dk(  sJ t        | j                  j                  | j                   dk(        E d {    y 7 wNr   r   )r   r   r   _rootrf   s    r-   __iter__z_node_list.__iter__  sF     ~~(DNNg,EEETZZ--t~~/HIIIs   AAAAc                 X    t        | j                  | j                  dk(  rd      S d      S r   )r   r   r   rf   s    r-   __reversed__z_node_list.__reversed__  s'    $**71JgXXPWXXr,   N)r   )r%   r&   r'   r)   rh   r   r   r   r+   r,   r-   r   r     s&    #g ## #
JYr,   r   c                   d    e Zd ZU dZee   ed<   ej                  ed<   e	ej                     ed<   y)_PyTreeInfoz=
    Contains extra info stored when we're using Pytrees
    	orig_argsin_specout_specN)
r%   r&   r'   r(   r   r)   r*   r9   TreeSpecr   r+   r,   r-   r   r     s,     Cy__v''r,   r   )frozenc                   @    e Zd ZU dZeed<   eed<   eed<   eed<   d Zy)_ParsedStackTracez?
    Represents the top-most frame of a parsed stack trace
    filelinenor/   codec                 n    d| j                    d| j                   d| j                   d| j                   S )NzFile: :z in z, code: )r   r   r/   r   rf   s    r-   get_summary_strz!_ParsedStackTrace.get_summary_str-  s1    		{!DKK=TYYKx		{SSr,   N)r%   r&   r'   r(   r)   r*   r   r+   r,   r-   r   r   #  s#     IK
I
ITr,   r   stack_tracec                    | y t        j                  d      }| j                         j                  d      }d}t	        t        |      dz
  dd      D ]  }||   j                         }|j                  |      }|s*|j                  d      }|j                  d      }|j                  d      }	||dz      j                         }
t        |||	|
      c S  y )Nz$^File \"(.+)\", line (\d+), in (.+)$
rE   rl   r      )	rb   rc   stripr   rangelenro   rp   r   )r   patternlinessummary_stridxlinematchesr   r   r/   r   s              r-   _parse_stack_tracer   1  s    jj@AG%%d+E KSZ!^R, 	?Sz!--%==#D]]1%F==#Dq>'')D$T64>>	? r,   Fc                       e Zd Zd Zdee   dedefdZdedefdZde	de	fd	Z
d
e	de	fdZdeeee	f      fdZddddddededededededefdZy)r   c                      d | _         d| _        y )Nforward)_body_transformer
_func_namerf   s    r-   rh   zCodeGen.__init__H  s    >B(r,   	free_varsmaybe_return_annotationr;   c                     t        |      dk(  s|d   dk7  r|j                  dd       d| j                   ddj                  |       d| dS )z
        Given the free variables and a return annotation, generates the beginning of the FX function.
        By default, `gen_fn_def(['a', 'b'], '') == 'def {self._func_name}(a, b):'`
        r   rg   zdef (, )r   )r   insertr   rJ   )rg   r   r   s      r-   
gen_fn_defzCodeGen.gen_fn_defL  sX     y>Q)A,&"8Q'doo&a		)(<'=Q?V>WWXYYr,   output_argsc                     dt        |       S )z
        Given the output arguments, generates the return statement of the FX function.
        Note: The returned statement should not be indented.
        zreturn )repr)rg   r   s     r-   generate_outputzCodeGen.generate_outputW  s    
 k*+,,r,   argsc                     |S )a{  
        Transforms the inputs so that the graph can take them as arguments, as
        non-default codegen may result in the inputs to the function being
        different from the inputs to the graph.

        If the graph was directly runnable, this invariant should hold true
        `f.graph.process_outputs(f.graph(*f.graph.process_inputs(*inputs))) == f(*inputs)`
        r+   rg   r   s     r-   process_inputszCodeGen.process_inputs^  s	     r,   outputsc                     |S )z
        Transforms the outputs of the graph to be identical to the codegen.

        See ``process_inputs`` for more details.
        r+   )rg   r   s     r-   process_outputszCodeGen.process_outputsi  s	     r,   c                     g S )z
        If your codegen uses extra global values, add tuples of (identifier,reference to the value) here.
        For example, return ['List', typing.List] if you need ``List`` in the global context.
        r+   rf   s    r-   additional_globalszCodeGen.additional_globalsq  s	    
 	r,   Fverboseinclude_strideinclude_devicecoloredroot_module	namespacer   r   r   r   c                    !"#$%&'()*+,-./0123 g (g #i )i 3dg*xs# t         j                  j                  dd      dk(  xs# t         j                  j                  dd      dk(  dt        dt        f)fd!t
        j                         D ]  \  }\  }	}
 !||
        d	t        f!1fd
1dddddddddd	$$fd} |d      } |d      } |d      . |d      } |d      ' |d      % |d      & |d      "dt        dt        f!"fd  d!t        t        d"f   d#t        t        t        f   dt        f fd$i ,i 2d%t        d&t        f,2fd'/t        |      D ]6  +t        +j                  +/fd(       t        +j                  +/fd)       8 d&t        f#%2fd*}d -d+t        f#%-fd,}d-t        dt        fd.0d+t        f !"#&'(*. 013fd/}t!        |      D ]4  \  }+r |+       #j#                  d0| d1        |+        |+       6 t%        #      d2k(  r#j#                  d3       t%        3      d2kD  rG !d4t&        j(                  j*                        }d1j-                  3D cg c]
  }| d5| d6 c}      }nd} j.                  r j/                  #      # j1                         D ]  \  }} !||         j3                  (*d2         }i }|j5                  d1      d7z   }g }d }dj-                  #      j7                  d1      D ]h  }t9        j:                  d8|      }|r,|j=                  d7      t?        |j=                  d7            }G||t%        |      |z   <   |j#                  |       j d1j-                  |      jA                  d1      }d1j-                  d9 |j7                  d1      D              }d1| d:| d1| }tC        |)|;      S c c}w )<NrE   FX_GRAPH_SHOW_STRIDE01FX_GRAPH_SHOW_DEVICE	name_hintr$   c                     t        |      r|t        j                  k7  rt        |      S j	                  | |      }|v r|   |u sJ |S ||<   |S )a  Add an obj to be tracked as a global.

            We call this for names that reference objects external to the
            Graph, like functions or types.

            Returns: the global name that should be used to reference 'obj' in generated source.
            )rX   r6   r7   r
   rv   )r  r$   global_nameglobals_r  s      r-   
add_globalz,CodeGen._gen_python_code.<locals>.add_global  sj     c"sell': +3// $//	3?Kh&,333""$'H[!r,   oc                 z   | dk(  ryt        |       }t        | d      rt        j                  | j                  | j                        } t        |      |      }t        | d      rF| j
                  D cg c]
  } |       }}t        |      dk(  r|S | ddj                  |       dS |S  ||       S c c}w )	Nr+   z()
__origin____args__r   [,])r	   hasattr_origin_type_mapgetr  r  r   rJ   )r  typenameorigin_typeorigin_typenameargr   r  	type_reprs         r-   r  z+CodeGen._gen_python_code.<locals>.type_repr  s    Bw!!}Hq,'.221<<N",Z-Dk"R1j)67jjAsIcNADA4yA~  /.-.a/?qAA +* h** Bs   5B8z[33mz[36mz[32mz[34mz[31mz[2mz	[2m[34mz	[2m[32mz[0m)	yellowcyangreenbluereddimdim_blue	dim_greenresetc                       fd}|S )Nc                 (    r    |  d    S | S )Nr$  r+   )rB   codesr   r/   s    r-   fz>CodeGen._gen_python_code.<locals>.make_wrapper_func.<locals>.f  s'    #Dk]1#eGn-=>>r,   r+   )r/   r(  r'  r   s   ` r-   make_wrapper_funcz3CodeGen._gen_python_code.<locals>.make_wrapper_func  s     Hr,   r  r  r   r  r#  r!  r"  r  r  r;   c                    t        | t              rJt        | d      r>t        t	        |             } |t	        |             }| t        t        |              S t        | t        j                  j                  t        j                  j                  f      rt        |       } ||       }| S t        | t        j                        r0| j                  } |j                  |      }| d| j                   S t        | t              rt        |       S t        | t        j                         rIt#        | j%                               }t'        | j(                        j+                  d      d   }d| d| dS  t        |             S )N_fieldsrP   r   ztorch.Tensor(size=z, dtype=r   )
isinstancetupler  r
   r   r   r6   _ops
OpOverloadHigherOrderOperatorenumEnum	__class__r%   r/   r   Tensorlistsizer)   dtyper   )	r  qualified_namer
  clsclsnamer6  r7  r  r  s	          r-   	_get_reprz+CodeGen._gen_python_code.<locals>._get_repr  s<   #u%'#y*A!4T#Y!?(cC%tE#J'7&899C%**"7"79W9W!XY!4S!9(=%'C+mm$S\\37!!CHH:..C&Cy C.CHHJ'CII,,S1"5+D6%BBDI&r,   r   .kwargsc                     dj                  fd| D              }dj                  fd|j                         D              }|r	|r| d| S |xs |S )Nr   c              3   .   K   | ]  } |        y wr1   r+   .0ar;  s     r-   	<genexpr>zACodeGen._gen_python_code.<locals>._format_args.<locals>.<genexpr>  s     :y|:   c              3   >   K   | ]  \  }}| d  |         yw) = Nr+   )r@  kvr;  s      r-   rB  zACodeGen._gen_python_code.<locals>._format_args.<locals>.<genexpr>  s$      TTQA3c)A,!8 Ts   )rJ   items)r   r<  args_skwargs_sr;  s       r-   _format_argsz.CodeGen._gen_python_code.<locals>._format_args  sR    YY:T::Fyy TV\\^ TTH( H:..%X%r,   nuserc                 \    | vr'|| <   j                  |g       j                  |        y y r1   )
setdefaultrG   )rL  rM  node_to_last_useuser_to_last_usess     r-   register_last_usesz4CodeGen._gen_python_code.<locals>.register_last_uses  s7    ((&* #!,,T26==a@ )r,   c                      |       S r1   r+   rL  noderR  s    r-   <lambda>z*CodeGen._gen_python_code.<locals>.<lambda>  s    );At)D r,   c                      |       S r1   r+   rT  s    r-   rV  z*CodeGen._gen_python_code.<locals>.<lambda>  s    +=a+F r,   c                    | j                   dk(  ry| j                   dk(  rj                  d       yj                  | g       }t        | j                  j                               dk(  r|j                  |        t        |      rHdj                  |D cg c]  }t        |       c}dgz         }j                  d |       d       yj                  d       yc c}w )	z
            Delete values after their last use. This ensures that values that are
            not used in the remainder of the code are freed and the memory usage
            of the code is optimal.
            placeholderNoutputr   r   rE  None;  )oprG   r  r   userskeysrJ   r   )rM  nodes_to_deleterL  to_delete_strbodyr!  rQ  s       r-   delete_unused_valuesz6CodeGen._gen_python_code.<locals>.delete_unused_values
  s     ww-'ww("D!/33D"=O4::??$%*  &&t,?# %

_+MDG+MQWPX+X Yc#m"4!5R89D! ,Ns   C!rU  c                 N   | j                   dvr| j                  rd| j                  k7  rT| j                  d}t        | j                        x}r|j                         }j	                  d d|z          d       yydk7  r dd}j	                  d |       d       yyy)z}
            Append a summary of the stacktrace to the generated code. This is
            useful for debugging.
            >   rZ  rY  rE   z
 z# r   z)# No stacktrace found for following nodesN)r]  r   r   r   rG   )rU  r   parsed_stack_traceno_stacktrace_msgrb  r!  prev_stacktraces       r-   append_stacktrace_summaryz;CodeGen._gen_python_code.<locals>.append_stacktrace_summary%  s     ww77##''?:*.*:*:&(1CDDTDT1UU-U*<*L*L*NKc#d[.@*A)B"$EF ; %*&(O(S%KK"S):%;$<B ?@ + 8r,   shapec                 :    ddj                  d | D               dS )Nr  r   c              3   2   K   | ]  }t        |        y wr1   )r)   )r@  r:   s     r-   rB  zDCodeGen._gen_python_code.<locals>.stringify_shape.<locals>.<genexpr><  s      7AQ 7   r  )rJ   )ri  s    r-   stringify_shapez1CodeGen._gen_python_code.<locals>.stringify_shape;  s!    tyy 7 778::r,   c                    | j                   dnd | j                          }r0ddlm} ddlm} | j
                  j                  d| j
                  j                  d| j
                  j                  dd                   }t        |t        j                        rrr |j                                nd}r|j                   nd}d	 t        |j                              |j                                |        |       d
}nHt        ||      rd| d}n5t        ||      r)d	t        |j                       |j                         d
}| j                  dk(  rt        | j                   t"              sJ | j$                  sdnd | j$                  d          }j'                  | j                    | |        | j                   j)                  dd      }|t+        |       k7  r j'                  t+        |        d| d       y | j                  dk(  rt        | j                   t"              sJ j'                  t+        |        | dt-         | j$                  d         | j                          d | j$                  dd  | j.                         d       y | j                  dk(  rt1        | j                         sJ t3        | j                   dd      dk(  r| j                   j4                  t6        v rxt        | j$                  t8              sJ j'                  t+        |        | dt7        | j                   j4                     j:                  fd| j$                  D                 y t3        | j                   dd      dk(  r| j                   j4                  t<        v rrj'                  t=        | j                   j4                     j:                  fd| j$                  D          dt+        |        | d | j$                  d                 y t?        | j                         }	 |	| j                         }
|
dk(  rt        | j$                  t8              rt        | j$                  d   t"              r| j$                  d   jA                         rdtC        | j$                        dk(  rLj'                  t+        |        | dt-         | j$                  d         | j$                  d                 y j'                  t+        |        | d|
 d | j$                  | j.                         d       | j
                  j                  dd      rjE                  |
       y | j                  dk(  rqt        | j                   t"              sJ j'                  t+        |        | dt-        | j                          d | j$                  | j.                         d       y | j                  d k(  rRt        | j                   t"              sJ j'                  t+        |        | dt-        | j                                 y | j                  d!k(  rR| j                   d" | j                          d<   j'                  jG                  | j$                  d                y tI        d#| j                   d$| j                          )%NrE   z : r   )py_sym_types)TensorMetadatavaltensor_metaexample_valuez: ""z: "Sym(z)"rY  rE  *r   call_methodr   r   r   call_functionr&   	_operatorc              3   .   K   | ]  } |        y wr1   r+   r?  s     r-   rB  z>CodeGen._gen_python_code.<locals>.emit_node.<locals>.<genexpr>h  s     OpabPYZ[P\OprC  c              3   .   K   | ]  } |        y wr1   r+   r?  s     r-   rB  z>CodeGen._gen_python_code.<locals>.emit_node.<locals>.<genexpr>n  s     QrcdR[\]R^QrrC  r\  rQ   rl   
is_wrappedFcall_moduleget_attrrZ  z -> znode:  )%r   "torch.fx.experimental.proxy_tensorro  torch.fx.passes.shape_proprp  metar  r,  r6   r4  strider7   dtype_abbrsr7  ri  r]  r   r)   r   rG   replacer   r   r<  callablerQ   r%   magic_methodsr-  formatinplace_methodsr
   r   r   rO  r   NotImplementedError)rU  maybe_type_annotationro  rp  meta_valstride_annotationdevice_annotationmaybe_default_argraw_namer8  r
  rK  r;  r  r  rb  r"  r#  r   r   r   r   r   r  rg   rm  r  r   wrapped_fnss              r-   	emit_nodez+CodeGen._gen_python_code.<locals>.emit_node>  s   *.))*;B3yQUQZQZG[F\A]!KE99==		mTYY]][jlpMq0rs h5Sa?8??;L+M*Ngi%@N8??*;TV%c+hnn"=>?_U]UcUcEd@e?f#$567	BS8T7UUVX *  ,7.5hZr,B).9.1+hnn2M1N_g_m_mOnNoop,q)ww-'!$++s333.2iiBs9TYYWX\CZB[=\!  DKK=1F0GHYGZ![\;;..sB7tDz)KK4:,c(2 >?M)!$++s333Dzl#8"9^IVZV_V_`aVbLceiepep=q<rTYYqr]DKK@ADE O+,,,4;;b9[HT[[MaMaerMr%dii777KK4:,/D.ES#01E1E#F#M#MOpfjfofoOp#q"r!t u 4;;b9[HT[[MaMaetMtKK?4;;3G3G#H#O#OQrhlhqhqQr#s"ttw#':,/D.ESSWS\S\]^S_I`Ha!c d!4T[[!A(E )+dii/diilC099Q<,,.tyy>Q&KK4:,/D.ESXabfbkbklmbnXoquqzqz{|q}I~H  !A  BtDzl+@*A[MQRS_`d`i`ikokvkvSwRxxyz{99==u5**;7M)!$++s333tDzl+@*A-k4;;GH,W[W`W`bfbmbmJnIoopr sJ&!$++s333tDzl+@*A^T_aealalEmDnopH$99(37	$))8L7M1N+A.D001>?%twwiq&FGGr,   z# COUNTER: r   r   zpass
wrapz("r   r   z# COUNTER: (\d+)c              3   &   K   | ]	  }d |z     yw)z    Nr+   )r@  r   s     r-   rB  z+CodeGen._gen_python_code.<locals>.<genexpr>  s     D4$Ds   z

)r   )"osenvironr  r)   r   r.   rH  r   r   r   r   reversedr   r   r<  r   	enumeraterG   r   r6   fxr  rJ   r   r   r   countr   rb   searchrp   r`   lstripr   )4rg   nodesr  r  r   r   r   r   r/   rD   r$   r)  r  r  r  rc  rh  r  i	wrap_name
wrap_stmtsr   prologue
lineno_mapprologue_len	new_linescur_idxr   counterr   fn_coderK  r;  r  r  rb  r'  r!  r"  r#  r   r  r   rU  rP  rg  r   rR  rm  r  rQ  r  s4   ` ``````                       @@@@@@@@@@@@@@@@@@@@@r-   _gen_python_codezCodeGen._gen_python_codex  s8     "	#%') 02d'_BJJNN;QSV,W[^,^'_BJJNN;QSV,W[^,^	# 	C 	0 /446 	"ND(1ctS!	"	+# 	+> !)*

	 #8, (&!'*%k2	&$Z0 (	'3 	'3 	'0	&uXs]3 	&T#x-=P 	&UX 	& /157	A4 	A 	A
 UO 	HDDIIDEDKK!FG	H	" 	"2 	AT 	A,	;H 	; 	;Q	HT Q	H Q	H Q	Hf !' 
	'GAt )$/ KK+aS+,dO &
	' t9> KK! {a"6588==9I#UykD6$<#UVJJ!!))$/D224 	$KD%tU#	$ ??9.Ea.HI 02
~~d+a/!	GGDM''- 	'Dii 3T:G7==+7gmmA./<C
3y>L89  &	' yy#**40yyD4::d3CDD 	
 	

 '8DDC $Vs   PN)r%   r&   r'   rh   r   r)   r   r   r   r   r   r   r   r   rZ   r   r   r  r+   r,   r-   r   r   F  s    )	ZDI 	Z 	ZPS 	Z-8 - -	C 	C 	s s DsCx$9  eTYkpPE"%PE2<PEPE/3PEMQPEdhPE 
PEr,   r   c                   X     e Zd Zdef fdZdedefdZdedefdZ fdZ fd	Z	 xZ
S )
_PyTreeCodeGenpytree_infoc                 0    t         |           || _        y r1   )superrh   r  )rg   r  r3  s     r-   rh   z_PyTreeCodeGen.__init__  s    (3r,   inputsr;   c                 *    t        j                  | }|S r1   )r9   arg_tree_leaves)rg   r  	flat_argss      r-   r   z_PyTreeCodeGen.process_inputs  s    **F3	r,   outc                     | j                   | j                   j                  |S t        |t        t        f      s|g}| j                   j                  J t        j                  || j                   j                        S r1   )r  r   r,  r5  r-  r9   tree_unflattenrg   r  s     r-   r   z_PyTreeCodeGen.process_outputs  sp    #t'7'7'@'@'HJ#e}-%C((444$$S$*:*:*C*CDDr,   c           
      D   | j                   t        | 	  ||      S | j                   j                  }t	        |      dkD  r|d   dk(  nd}|r|j                  dd       t        | 	  |d d  |      }t	        |      dkD  r| j                   j                  j                  t        k(  xr | j                   j                  j                  dk(  xrj | j                   j                  j                  d   j                  t        k(  xr4 | j                   j                  j                  d   j                  t        k(  }d}ddj                  |       d	}|r| j                   j                  j                  d   j                  }	| j                   j                  d |	 }d
dj                  d t        | j                   j                  j                  d   j                  | j                   j                  |	d        D              z   dz   }ddj                  |       d| d}|D 
cg c]  }
|
j                  d      d    }}
|D 
cg c]  }
d|
v s|
dz    }}
t	        |      dkD  r|ddj                  |      z   dz   z  }|ddj                  |       d| dz  }|S c c}
w c c}
w )Nr   rg   Frl   r   z{}r  r   z], self._in_spec{c              3   2   K   | ]  \  }}d | d|   yw)'z':Nr+   )r@  rF  rG  s      r-   rB  z,_PyTreeCodeGen.gen_fn_def.<locals>.<genexpr>  s&      ,LTQas"QCL ,Lrl  }z([z], z), self._in_specr   z; 
    rE   r   z , = fx_pytree.tree_flatten_spec(r   )r  r  r   r   r   r   r   r   r-  num_childrenchildren_specsdictrJ   zipcontextr   )rg   r   r   fn_argshas_orig_selffn_definitionhas_args_kwargs_tuple	fn_kwargsfn_signature
count_argsr:   without_annotationhas_annotationr3  s                r-   r   z_PyTreeCodeGen.gen_fn_def  s     #7%i1HII"",,25g,2Bv-Q'*71:7NOy>A$($4$4$<$<$A$AU$J %H  ((55:%H  ((77:??5H%H   ((77:??4G " Ityy122BCL$!--55DDQGTT
**44[jA$)) ,LS"&"2"2":":"I"I!"L"T"T"&"2"2"<"<Z["IFK ,L #L LNQR	 "$DIIg$6#7s9+EUV <E!Ea!''#,q/!E!E09F1SAXa$hFNF>"Q&BGGN,C!Cd!JJ "	YY!"##CL>QRV VM "FFs   J 	J
Jc                     | j                   r%| j                   j                  rdt        |       dS t        |   |      S )Nzreturn pytree.tree_unflatten(z, self._out_spec))r  r   r   r  r   )rg   r   r3  s     r-   r   z_PyTreeCodeGen.generate_output  s@     0 0 9 9243D2EEVWW7*;77r,   )r%   r&   r'   r   rh   r   r   r   r   r   __classcell__)r3  s   @r-   r  r    sH    4K 4c c E3 E3 E3j8 8r,   r  c                   z    e Zd ZdZd Zdeeee   f   fdZ	de
fdZdeddfdZdeddfd	Zdd
deded   fdZy)_FindNodesLookupTablezH
    Side table for the graph for the purpose of doing fast queries
    c                 ,    t        t              | _        y r1   )r   r  tablerf   s    r-   rh   z_FindNodesLookupTable.__init__!  s    KVW[K\
r,   r;   c                 V    |j                   |j                   dk(  r|j                  fS d fS Nrw  r]  r   rg   rU  s     r-   _keyz_FindNodesLookupTable._key$  s(    ?(BMMMMr,   c                 B    || j                   | j                  |         v S r1   r  r  r  s     r-   __contains__z"_FindNodesLookupTable.__contains__'  s    tzz$))D/222r,   rU  Nc                 F    d | j                   | j                  |         |<   y r1   r  r  s     r-   r   z_FindNodesLookupTable.insert*  s    ,0

499T?#D)r,   c                 ^    | j                   | j                  |         j                  |       y r1   )r  r  popr  s     r-   rx   z_FindNodesLookupTable.remove-  s!    

499T?#''-r,   )r   r]  r   r   c                <   |dk(  r,|J t        | j                  ||f         j                         S |(t        | j                  |d f         j                         S | j                  |d f   j                         D cg c]  }|j                  |k(  s| c}S c c}w r  )r  r  r_  r   )rg   r]  r   rU  s       r-   
find_nodesz _FindNodesLookupTable.find_nodes0  s     %%%

B<016688>

B:./4466 "&RJ!7!<!<!>X$++QWBWXXXs   =BB)r%   r&   r'   r(   rh   r   r)   r   r   r  r   r  r   r   rx   r  r+   r,   r-   r  r    s~    ]NE#x'7"78 N3D 314 1D 1.4 .D . CG 	Y 	YXh-? 	Yr,   r  c                      e Zd ZdZ ed      	 	 dNded   deed      d	eeee	f      fd
       Z
ed        Zej                  ded   fd       Zedefd       Z ed      ddddeded   defd       Z ed      dOdd deeef   ddfd       ZdPdQdZ ed      	 	 	 	 dRdedddeed      deeedf      d ee   d!ee	   defd"       Z ed      d#        Z ed      d$        Z ed      d%eddfd&       Z ed      dPd'ee   fd(       Z ed      dPd'ee   fd)       Z ed      dej:                  j<                  fd ed!ee	   d*e	defd+       Z ed      dPd,ed!ee	   defd-       Z  ed      	 	 	 dNd.edeed      deeedf      d!ee	   def
d/       Z! ed      	 	 	 dNd0edeed      deeedf      d!ee	   def
d1       Z" ed      	 	 	 dNd2e#d3e	f   deed      deeedf      d!ee	   def
d4       Z$ ed      d5 fd6ed7e#egdf   defd8       Z% ed      dPd9dd!ee	   fd:       Z&de'defd;Z( ed      ddddd<d=ed>ed?ed@edAede)fdB       Z*ddddd<d=edCe+d>ed?ed@edAede)fdDZ,defdEZ- ed      dF        Z. ed      dG        Z/ ed      dPdHee#egef      fdI       Z0 ed      dJe1fdK       Z2 ed      dLe#ee3   ge3f   fdM       Z4y)Sr   a]  
    ``Graph`` is the main data structure used in the FX Intermediate Representation.
    It consists of a series of ``Node`` s, each representing callsites (or other
    syntactic constructs). The list of ``Node`` s, taken together, constitute a
    valid Python function.

    For example, the following code

    .. code-block:: python

        import torch
        import torch.fx

        class MyModule(torch.nn.Module):
            def __init__(self):
                super().__init__()
                self.param = torch.nn.Parameter(torch.rand(3, 4))
                self.linear = torch.nn.Linear(4, 5)

            def forward(self, x):
                return torch.topk(torch.sum(self.linear(x + self.linear.weight).relu(), dim=-1), 3)

        m = MyModule()
        gm = torch.fx.symbolic_trace(m)

    Will produce the following Graph::

        print(gm.graph)

    .. code-block:: text

        graph(x):
            %linear_weight : [num_users=1] = self.linear.weight
            %add_1 : [num_users=1] = call_function[target=operator.add](args = (%x, %linear_weight), kwargs = {})
            %linear_1 : [num_users=1] = call_module[target=linear](args = (%add_1,), kwargs = {})
            %relu_1 : [num_users=1] = call_method[target=relu](args = (%linear_1,), kwargs = {})
            %sum_1 : [num_users=1] = call_function[target=torch.sum](args = (%relu_1,), kwargs = {dim: -1})
            %topk_1 : [num_users=1] = call_function[target=torch.topk](args = (%sum_1, 3), kwargs = {})
            return topk_1

    For the semantics of operations represented in the ``Graph``, please see :class:`Node`.
    Tr   Nowning_moduler   
tracer_clsr    tracer_extrasc                    t        | ddddi       | _        i | _        | j                  j                  | _        d| _        t               | _        || _        || _	        || _
        t               | _        i | _        t               | _        y)z+
        Construct an empty Graph.
        rE   rootr+   r   N)r   r   r_   prependr   r   rZ   _graph_namespace_owning_module_tracer_cls_tracer_extrasr   _codegen
_co_fieldsr  _find_nodes_lookup_table)rg   r  r  r  s       r-   rh   zGraph.__init__h  sw     !r62r2>
,.zz))	 *+%+	+-(=(?%r,   c                     | j                   S r1   r  rf   s    r-   r  zGraph.owning_modulez  s    """r,   modc                     || _         y r1   r  )rg   r  s     r-   r  zGraph.owning_module~  s
    !r,   r;   c                     t        |       S )av  
        Get the list of Nodes that constitute this Graph.

        Note that this ``Node`` list representation is a doubly-linked list. Mutations
        during iteration (e.g. delete a Node, add a Node) are safe.

        Returns:

            A doubly-linked list of Nodes. Note that ``reversed`` can be called on
            this list to switch iteration order.
        )r   rf   s    r-   r  zGraph.nodes  s     $r,   F)r   sortr]  r   r   r  c                Z    | j                   j                  ||      }|rt        |      S |S )a  
        Allows for fast query of nodes

        Args:

            op (str): the name of the operation

            target (Optional[Target]): the target of the node. For call_function,
                the target is required. For other ops, the target is optional.

            sort (bool): whether to return nodes in the order they appear on
                         on the graph.

        Returns:

            Iteratable of nodes with the requested op and target.
        r  )r  r  sorted)rg   r]  r   r  	node_lists        r-   r  zGraph.find_nodes  s3    & 11<<6<R	)$$r,   gval_mapzOptional[Argument]c                     |j                   D ]V  }|v r|j                  dk(  r(t        |j                  d   fd      }|s|c S ||fc S | j	                  |fd      |<   X y)aM  
        Copy all nodes from a given graph into ``self``.

        Args:

            g (Graph): The source graph from which to copy Nodes.

            val_map (Dict[Node, Node]): a dictionary that will be populated with a mapping
                from nodes in ``g`` to nodes in ``self``. Note that ``val_map`` can be passed
                in with values in it already to override copying of certain values.

        Returns:

            The value in ``self`` that is now equivalent to the output value in ``g``,
            if ``g`` had an ``output`` node. ``None`` otherwise.
        rZ  r   c                     |    S r1   r+   rL  r  s    r-   rV  z"Graph.graph_copy.<locals>.<lambda>  s    WQZ r,   c                     |    S r1   r+   r  s    r-   rV  z"Graph.graph_copy.<locals>.<lambda>  s    GAJ r,   N)r  r]  r   r   	node_copy)rg   r  r  return_output_noderU  rvs     `   r-   
graph_copyzGraph.graph_copy  sp    $ GG 	HDwww("TYYq\+?@!3rC"dC NN41FGGDM	H r,   c                 `   |r|ni }t        | j                        }|j                  | |d      }t        j                  | j
                        |_        t        |t              sJ |\  }}|j                  |t        |dd            }t        j                  |j                        |_
        |S )a  
        Explicitly implement __deepcopy__ to prevent excessive recursion depth
        from the default implementation. This uses graph_copy to copy the nodes
        in an iterative way, rather than recursive. It also populates the
        memoization table to prevent unnecessary copies (e.g. references to
        nodes or other parts of the Graph from a custom GraphModule implementation.
        )r  T)r  r  r   N	type_expr)r   r  r  copydeepcopyr  r,  r-  rZ  rQ   r  )rg   memor  output_vals
output_valold_output_nodenew_output_nodes          r-   __deepcopy__zGraph.__deepcopy__  s     tT--.ll4$lO]]4==1
+u---&1#
O((:RXZ^9_(`#yy)=)=>r,   r   )r   .r<  r   r/   r  c           	      P   |dv sJ |dn|}|i n|}t        |t              sJ d       t        |t              sJ d       ||n| j                  |      }| j                  j                  |d      }t        | ||||||      }| j                  :t        | j                  dd      #| j                  j                  D ]
  }	 |	|        | j                  j                  ||       | j                  |       | j                  j                  |       | xj                  dz  c_        |S )a&  
        Create a ``Node`` and add it to the ``Graph`` at the current insert-point.
        Note that the current insert-point can be set via :meth:`Graph.inserting_before`
        and :meth:`Graph.inserting_after`.

        Args:
            op (str): the opcode for this Node. One of 'call_function', 'call_method', 'get_attr',
                'call_module', 'placeholder', or 'output'. The semantics of these opcodes are
                described in the ``Graph`` docstring.

            args (Optional[Tuple[Argument, ...]]): is a tuple of arguments to this node.

            kwargs (Optional[Dict[str, Argument]]): the kwargs of this Node

            name (Optional[str]): an optional string name for the ``Node``.
                This will influence the name of the value assigned to in the
                Python generated code.

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.

        Returns:

            The newly-created and inserted node.
        )rw  rv  r}  r|  rY  rZ  Nr+   zargs must be a tuplezkwargs must be a dict_create_node_hooksr   )r,  r-  r  _target_to_strr  rv   r   r  rQ   r	  rz   r   r  r   r   )
rg   r]  r   r   r<  r/   r  ri   rL  r(  s
             r-   create_nodezGraph.create_node  s'   > iiii\rt~6$&>(>>&&$'@)@@' ,D$2E2Ef2M	$$00DAtRvyA)gd6H6HJ^`d.e.q'':: ! 	55dA>Q%%,,Q/		Q	r,   c                 4     | j                   j                  | S )zL
        Processes args so that they can be passed to the FX graph.
        )r  r   r   s     r-   r   zGraph.process_inputs
  s    
 ,t}}++T22r,   c                 8    | j                   j                  |      S r1   )r  r   r  s     r-   r   zGraph.process_outputs  s    }},,S11r,   to_erasec           	         t        |j                        dkD  r2t        d| dt        |j                         d|j                   d      |j                  | k7  rt        d| d      |j                  rt        j                  d| d	       y
| j                  :t        | j                  dd
      #| j                  j                  D ]
  } ||        | j                  j                  |       |j                          d|_        | xj                  dz  c_        t        |j                  d       }t!        |t"              sJ ||_        t        |j$                  d       }t!        |t&              sJ ||_        y
)z
        Erases a ``Node`` from the ``Graph``. Throws an exception if
        there are still users of that node in the ``Graph``.

        Args:

            to_erase (Node): The ``Node`` to erase from the ``Graph``.
        r   zTried to erase Node z but it still had z users in the graph: !zAttempting to remove z from wrong graph!zerase_node(z) on an already erased nodeN_erase_node_hooksTr   c                      y r1   r+   rL  s    r-   rV  z"Graph.erase_node.<locals>.<lambda>4      r,   c                      y r1   r+   r  s    r-   rV  z"Graph.erase_node.<locals>.<lambda>7  r  r,   )r   r^  RuntimeErrorr   _erasedwarningswarnr  rQ   r  r  rx   _remove_from_listr   r   r   r,  r-  r<  r  )rg   r  r(  new_args
new_kwargss        r-   
erase_nodezGraph.erase_node  sg    x~~"!5hZ?QRUV^VdVdReQf g66>nn5EQ H I I>>T!!6xj@RSTTMMKz1LMN)gd6H6HJ]_c.d.p''99 ( 	%%,,X6""$		Q	 8==.9(E*** X__n=
*d+++$r,   rL  c                     || j                  | j                        S |j                  | k(  sJ d       t        | |j                        S )a  Set the point at which create_node and companion methods will insert into the graph.
        When used within a 'with' statement, this will temporary set the insert point and
        then restore it when the with statement exits::

            with g.inserting_before(n):
                ... # inserting before node n
            ... # insert point restored to what it was previously
            g.inserting_before(n) #  set the insert point permanently

        Args:

            n (Optional[Node]): The node before which to insert. If None this will insert before
                the beginning of the entire graph.

        Returns:
            A resource manager that will restore the insert point on ``__exit__``.
        z&Node to insert before is not in graph.)inserting_afterr   r   r   r  rg   rL  s     r-   inserting_beforezGraph.inserting_before;  sE    & 9''

33ww$H HHD!)),,r,   c                     || j                  | j                        S |j                  | k(  sJ d       t        | |j                        S )a  Set the point at which create_node and companion methods will insert into the graph.
        When used within a 'with' statement, this will temporary set the insert point and
        then restore it when the with statement exits::

            with g.inserting_after(n):
                ... # inserting after node n
            ... # insert point restored to what it was previously
            g.inserting_after(n) #  set the insert point permanently

        Args:

            n (Optional[Node]): The node before which to insert. If None this will insert after
                the beginning of the entire graph.

        Returns:
            A resource manager that will restore the insert point on ``__exit__``.
        z%Node to insert after is not in graph.)r!  r   r   r   rG   r   s     r-   r  zGraph.inserting_afterS  sE    & 9((44ww$G GGD!((++r,   default_valuec                 n    |t         j                  j                  u rdn|f}| j                  d|||      S )a%  
        Insert a ``placeholder`` node into the Graph. A ``placeholder`` represents
        a function input.

        Args:

            name (str): A name for the input value. This corresponds to the name
                of the positional argument to the function this ``Graph`` represents.

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have. This is needed in some
                cases for proper code generation (e.g. when the function is used
                subsequently in TorchScript compilation).

            default_value (Any): The default value this function argument should take
                on. NOTE: to allow for `None` as a default value, `inspect.Signature.empty`
                should be passed as this argument to specify that the parameter does _not_
                have a default value.

        .. note::
            The same insertion point and type expression rules apply for this method
            as ``Graph.create_node``.
        r+   rY  )r   r  )inspect	Signatureemptyr  )rg   r/   r  r#  r   s        r-   rY  zGraph.placeholderk  s;    4 #g&7&7&=&==rMCSt$)TTr,   r8  c                     dt         j                  j                  dt        dt        fd}| j
                  r* || j
                  |      st        j                  dd       | j                  d||	      S )
a  
        Insert a ``get_attr`` node into the Graph. A ``get_attr`` ``Node`` represents the
        fetch of an attribute from the ``Module`` hierarchy.

        Args:

            qualified_name (str): the fully-qualified name of the attribute to be retrieved.
                For example, if the traced Module has a submodule named ``foo``, which has a
                submodule named ``bar``, which has an attribute named ``baz``, the qualified
                name ``foo.bar.baz`` should be passed as ``qualified_name``.

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.


        Returns:

            The newly-created and inserted ``get_attr`` node.

        .. note::
            The same insertion point and type expression rules apply for this method
            as ``Graph.create_node``.
        r  r8  r;   c                    |j                  d      \  }}}	 | j                  |      }t        ||      syt        ||      }t        |t        j                  j                        s3t        |t        j                  j                        s||j                  vryy# t        $ r t        j                  d| d       Y yw xY w)NrP   zFailed to fetch module r  FT)
rpartitionget_submoduleAttributeErrorr  r  r  rQ   r,  r6   rS   Module	Parameter_buffers)r  r8  module_pathrD   r/   submodress          r-   _get_attr_reference_existsz2Graph.get_attr.<locals>._get_attr_reference_exists  s    #1#<#<S#A KD*-*;*;K*H
 64(&$'CsEHHOO4&sEHH,>,>?FOO3 "  7}AFGs   B "B>=B>a  Attempted to insert a get_attr Node with no underlying reference in the owning GraphModule! Call GraphModule.add_submodule to add the necessary submodule, GraphModule.add_parameter to add the necessary Parameter, or nn.Module.register_buffer to add the necessary bufferrl   )
stacklevelr}  r  )	r6   rS   r-  r)   r   r  r  r  r  )rg   r8  r  r3  s       r-   r}  zGraph.get_attr  sp    2	EHHOO 	S 	UY 	* .t/A/A>RMM - :;< 
NiPPr,   rU   c                     | j                   r0| j                   j                  |      t        j                  d       | j	                  d||||      S )a  
        Insert a ``call_module`` ``Node`` into the ``Graph``. A ``call_module`` node
        represents a call to the forward() function of a ``Module`` in the ``Module``
        hierarchy.

        Args:

            module_name (str): The qualified name of the ``Module`` in the ``Module``
                hierarchy to be called. For example, if the traced ``Module`` has a
                submodule named ``foo``, which has a submodule named ``bar``, the
                qualified name ``foo.bar`` should be passed as ``module_name`` to
                call that module.

            args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
                to the called method. Note that this should *not* include a ``self`` argument.

            kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
                to the called method

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.

        Returns:

            The newly-created and inserted ``call_module`` node.

        .. note::
            The same insertion point and type expression rules apply for this method
            as :meth:`Graph.create_node`.
        zAttempted to insert a call_module Node with no underlying reference in the owning GraphModule! Call GraphModule.add_submodule to add the necessary submoduler|  r  )r  r+  r  r  r  )rg   rU   r   r<  r  s        r-   r|  zGraph.call_module  sU    H ""00=EMM 0 1
 {D&T]^^r,   method_namec                 .    | j                  d||||      S )aj  
        Insert a ``call_method`` ``Node`` into the ``Graph``. A ``call_method`` node
        represents a call to a given method on the 0th element of ``args``.

        Args:

            method_name (str): The name of the method to apply to the self argument.
                For example, if args[0] is a ``Node`` representing a ``Tensor``,
                then to call ``relu()`` on that ``Tensor``, pass ``relu`` to ``method_name``.

            args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
                to the called method. Note that this *should* include a ``self`` argument.

            kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
                to the called method

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.

        Returns:

            The newly created and inserted ``call_method`` node.

        .. note::
            The same insertion point and type expression rules apply for this method
            as :meth:`Graph.create_node`.
        rv  r  r  )rg   r6  r   r<  r  s        r-   rv  zGraph.call_method  s"    B {D&T]^^r,   the_function.c                 .    | j                  d||||      S )a  
        Insert a ``call_function`` ``Node`` into the ``Graph``. A ``call_function`` node
        represents a call to a Python callable, specified by ``the_function``.

        Args:

            the_function (Callable[..., Any]): The function to be called. Can be any PyTorch
                operator, Python function, or member of the ``builtins`` or ``operator``
                namespaces.

            args (Optional[Tuple[Argument, ...]]): The positional arguments to be passed
                to the called function.

            kwargs (Optional[Dict[str, Argument]]): The keyword arguments to be passed
                to the called function

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.

        Returns:

            The newly created and inserted ``call_function`` node.

        .. note::
            The same insertion point and type expression rules apply for this method
            as :meth:`Graph.create_node`.
        rw  r  r8  )rg   r9  r   r<  r  s        r-   rw  zGraph.call_function  s"    B tVW`aar,   c                     | S r1   r+   r@   s    r-   rV  zGraph.<lambda>7  s    \] r,   rU  arg_transformc                 j   t        |j                  |      }t        |j                  |      }t        |t              sJ t        |t
              sJ | j                  |j                  |j                  |||j                  |j                        }t        j                  |j                        |_        |S )ay  
        Copy a node from one graph into another. ``arg_transform`` needs to transform arguments from
        the graph of node to the graph of self. Example::

            # Copying all the nodes in `g` into `new_graph`
            g : torch.fx.Graph = ...
            new_graph = torch.fx.graph()
            value_remap = {}
            for node in g.nodes:
                value_remap[node] = new_graph.node_copy(node, lambda n : value_remap[n])

        Args:

            node (Node): The node to copy into ``self``.

            arg_transform (Callable[[Node], Argument]): A function that transforms
                ``Node`` arguments in node's ``args`` and ``kwargs`` into the
                equivalent argument in ``self``. In the simplest case, this should
                retrieve a value out of a table mapping Nodes in the original
                graph to ``self``.
        )r   r   r<  r,  r-  r  r  r]  r   r/   r   r   r  )rg   rU  r<  r   r<  result_nodes         r-   r  zGraph.node_copy6  s    . tyy-0m4$&&&&$'''&&twwT6499VZV_V_`99TYY/r,   resultc                 .    | j                  dd|f|      S )a5  
        Insert an ``output`` ``Node`` into the ``Graph``. An ``output`` node represents
        a ``return`` statement in Python code. ``result`` is the value that should
        be returned.

        Args:

            result (Argument): The value to be returned.

            type_expr (Optional[Any]): an optional type annotation representing the
                Python type the output of this node will have.

        .. note::

            The same insertion point and type expression rules apply for this method
            as ``Graph.create_node``.
        rZ  )r]  r   r   r  r8  )rg   r?  r  s      r-   rZ  zGraph.outputU  s!    & 8HF9Xabbr,   c                     t        |      r|j                  }n$t        |t              sJ |}t	        |      r|dd }t        |      }|S )Nrl   )r  r%   r,  r)   rA   rN   )rg   r   r]  s      r-   r
  zGraph._target_to_strj  sH    FBfc***B}"X_	r,   r   r  r   r   r   r   c          	          t               dt        ffdt        dt        ffd       } ||       5  | j	                  |||||      cddd       S # 1 sw Y   yxY w)a  
        Turn this ``Graph`` into valid Python code.

        Args:

            root_module (str): The name of the root module on which to look-up
                qualified name targets. This is usually 'self'.

        Returns:

            A PythonCode object, consisting of two fields:
                src: the Python source code representing the object
                globals: a dictionary of global names in `src` -> the objects that they reference.
        rL  c                 <    j                  | j                  |       S r1   )rv   r/   )rL  r  s    r-   	node_reprz$Graph.python_code.<locals>.node_repr  s    ((33r,   r   c              3      K   i }| j                   D ]  }|j                  ||<   |_         	 d  | j                   D ]  }||   |_         y # | j                   D ]  }||   |_         w xY wwr1   )r  _repr_fn)r   orig_repr_fnsrU  rE  s      r-   override_node_reprz-Graph.python_code.<locals>.override_node_repr  s~     M *&*mmd# )*8
 "KK 8D$1$$7DM8EKK 8D$1$$7DM8s   *A.A A.A++A.r   N)rZ   r   r   r   _python_code)	rg   r  r   r   r   r   rI  r  rE  s	          @@r-   python_codezGraph.python_codeu  su    N L		4 	4 

	8e 
	8 

	8  % 	$$Y~gn % 	 	 	s   AA r  c          	      Z    | j                   j                  | j                  ||||||      S )Nr   )r  r  r  )rg   r  r  r   r   r   r   s          r-   rJ  zGraph._python_code  s5     }}--JJYN>cj . 
 	
r,   c                     g }dg}| j                   D cg c]  }|j                  |       }}dj                  |      }d| d|d    d}|D ]  }|s|d|z   z  } |S c c}w )zl
        Return a human-readable (not machine-readable) string representation
        of this Graph
        rE   r   zgraph(r   r   r   r  )r  format_noderJ   )rg   placeholder_namesmaybe_return_typenamerU  	node_strs	param_strrB   node_strs           r-   __str__zGraph.__str__  s    
 )+ .0DEIZZPTT%%&78P	PII/0	YKq!6q!9 :!<! 	)HX((	)  Qs   Ac                    	 ddl m } | j                  D cg c];  }|j                  |j
                  |j                  |j                  |j                  g= }}t         ||g d             y# t        $ r t        d        w xY wc c}w )z
        Prints the intermediate representation of the graph in tabular
        format. Note that this API requires the ``tabulate`` module to be
        installed.
        r   )tabulatez`print_tabular` relies on the library `tabulate`, which could not be found on this machine. Run `pip install tabulate` to install the library.)opcoder/   r   r   r<  )headersN)	rV  ImportErrorprintr  r]  r/   r   r   r<  )rg   rV  rL  
node_specss       r-   print_tabularzGraph.print_tabular  s    	)  $zz+ ttQVVQXXqvvqxx@ +
 +hzDF 	G  	 > ? 		+s   A. A B.Bc                 f   
 d#dt         dt        t            ddf fd
t               }t                j                  D ]  j                  dvrt        d dj                   d	      j                   urt        d
 d       j                  vrt        d
 d      t        j                  
fd       t        j                  
fd       j                         j                  |v rt        dj                   d	      |j                  j                           j                  rsd}d} j                  D ]<  j                  dk(  rQt        j                        st!        d dj                   dt#        j$                  j                         d      t'        j                  t(              s<t!        d dj                   dt#        j$                  j                         d      j                  dv sɉj                  j+                  d      } j                  }t-        |      D ]>  \  }}t/        ||d      }dj1                  |d|       }	|!t        d dj                   d| d|	       j                  dk(  rFt'        |t"        j2                  j4                        s"t        d dj                   d| d|	 d	      j                  dk(  rt'        |t"        j2                  j4                        sjt'        |t"        j2                  j6                        sF||j8                  vr8||k  r,t;        j<                  d dj                   d| d|	 d	       |d z  }=|}A ? ||kD  rt;        j<                  d!||z
   d"       yyy)$aJ  
        Runs various checks on this Graph to make sure it is well-formed. In
        particular:
        - Checks Nodes have correct ownership (owned by this graph)
        - Checks Nodes appear in topological order
        - If this Graph has an owning GraphModule, checks that targets
        exist in that GraphModule
        Nr  rL  r;   c                     |rd| dnd}| j                   urt        d|  d| d       | vrt        d|  d| d       y )Nz
 of Node 'z' r~  z
Argument 'r  zdoes not belong to this Graph, but was used as an argument! If you are copying nodes from another graph, make sure to use ``arg_transform`` on node_copy() to remap values
zdwas used before it has been defined! Please check that Nodes in the graph are topologically ordered
)r   r  )r  rL  context_strseen_valuesrg   s      r-   	check_argzGraph.lint.<locals>.check_arg  s    23Ks#.Kyy$"[R} Eddhci$k l l +%"[R} Eoosnt$v w w &r,   )rY  rv  r|  rw  r}  rZ  zNode z had unknown opcode r  zNode 'z ' does not belong to this Graph!z ' is not added to the side tablec                      |       S r1   r+   r  ra  rU  s    r-   rV  zGraph.lint.<locals>.<lambda>  s    9S$+? r,   c                      |       S r1   r+   rc  s    r-   rV  zGraph.lint.<locals>.<lambda>	  s    YsD-A r,   zNode redefined name r      rw  z target z
 has type z but a Callable is expectedz but a str is expected)r}  r|  rP   z" references nonexistent attribute z of r|  r~  z  does not reference an nn.Moduler}  zj does not reference an nn.Module, nn.Parameter, or buffer, which is what 'get_attr' Nodes typically targetr   zAdditional z. warnings suppressed about get_attr referencesr1   )r   r   r]   r  r]  r  r   r  r   r   r<  rr   r/   r  r  r   
ValueErrorr6   r  r,  r)   r   r  rQ   rJ   rS   r-  r.  r/  r  r  )rg   
seen_namesnum_warningsMAX_WARNINGStarget_atomsm_itrr  atom	new_m_itrseen_qualnamera  rU  r`  s   `         @@@r-   lintz
Graph.lint  s   	wD 	whtn 	w 	w !$
"%%JJ 	&Dwwrr"U4&0DTWWIQ#OPPzz%"WTF2S#TUU4888"VD61Q#RSSDII?@DKK!ABOOD!yyJ&"%9$))A#FGGNN499%	&  LL

 #.77o-#DKK0(5ht{{m:V[VdVdeiepepVqUr sB *B C C &dkk37(5ht{{m:V[VdVdeiepepVqUr s= *= > >7799#';;#4#4S#9L ..E#,\#: .4$+E4$>	(+bq1A(B$,".tfHT[[MQs26tM?0L #M M GG}4(29ehhoo(N".tfHT[[MQRSWRXX\]j\k lL 0L #M M"gg3&0EHHOO&L&0EHH<N<N&O"&enn"<+l: !)dV8DKK=PQRVQWW[\i[j kY /Y !Z )A-L$-E/.#.H l*!,"=!> ?; ; +O r,   is_impure_nodec                     | j                          fd}d}t        | j                        D ]7  } ||      rt        |j                        dk(  s%| j                  |       d}9 |S )a  
        Remove all dead code from the graph, based on each node's number of
        users, and whether the nodes have any side effects. The graph must be
        topologically sorted before calling.

        Args:
            is_impure_node (Optional[Callable[[Node], bool]]): A function that returns
            whether a node is impure. If this is None, then the default behavior is to
            use Node.is_impure.

        Returns:
          bool: Whether the graph was changed as a result of the pass.

        Example:

        Before dead code is eliminated, `a` from `a = x + 1` below has no users
        and thus can be eliminated from the graph without having an effect.

        .. code-block:: python

            def forward(self, x):
                a = x + 1
                return x + self.attr_1

        After dead code is eliminated, `a = x + 1` has been removed, and the rest
        of `forward` remains.

        .. code-block:: python

            def forward(self, x):
                return x + self.attr_1

        .. warning::

            Dead code elimination has some heuristics to avoid removing
            side-effectful nodes (see Node.is_impure) but in general coverage
            is very bad, so you should assume that this method is not sound
            to call unless you know that your FX graph consists entirely
            of functional operations or you supply your own custom
            function for detecting side-effectful nodes.
        c                 8     |       S | j                         S r1   )	is_impure)rU  rp  s    r-   has_side_effectz2Graph.eliminate_dead_code.<locals>.has_side_effectm  s!    )%d++>>##r,   Fr   T)ro  r  r  r   r^  r  )rg   rp  rt  changedrU  s    `   r-   eliminate_dead_codezGraph.eliminate_dead_code>  sb    Z 				$ TZZ( 	D"4(S_-A%	
 r,   codegenc                     || _         y r1   )r  )rg   rw  s     r-   set_codegenzGraph.set_codegen}  s	    r,   make_transformerc                       j                   j                   |       j                   _        t        j                   fd       } |       S )aa
  Register a transformer function when python code is generated

        Args:
            make_transformer (Callable[[Optional[TransformCodeFunc]], TransformCodeFunc]):
                a function that returns a code transformer to be registered.
                This function is called by `on_generate_code` to obtain the
                code transformer.

                This function is also given as its input the currently
                registered code transformer (or None if nothing is registered),
                in case it is not desirable to overwrite it. This is useful to
                chain code transformers together.

        Returns:
            a context manager that when used in a `with` statement, to automatically
            restore the previously registered code transformer.

        Example:

        .. code-block:: python


            gm: fx.GraphModule = ...

            # This is a code transformer we want to register. This code
            # transformer prepends a pdb import and trace statement at the very
            # beginning of the generated torch.fx code to allow for manual
            # debugging with the PDB library.
            def insert_pdb(body):
                return ["import pdb; pdb.set_trace()\n", *body]

            # Registers `insert_pdb`, and overwrites the current registered
            # code transformer (given by `_` to the lambda):
            gm.graph.on_generate_code(
                lambda _: insert_pdb
            )

            # Or alternatively, registers a code transformer which first
            # runs `body` through existing registered transformer, then
            # through `insert_pdb`:
            gm.graph.on_generate_code(
                lambda current_trans: (
                    lambda body: insert_pdb(
                        current_trans(body) if current_trans
                        else body
                    )
                )
            )

            gm.recompile()
            gm(*inputs)  # drops into pdb


        This function can also be used as a context manager, with the benefit to
        automatically restores the previously registered code transformer:

        .. code-block:: python

            # ... continue from previous example

            with gm.graph.on_generate_code(lambda _: insert_pdb):
                # do more stuff with `gm`...
                gm.recompile()
                gm(*inputs)  # drops into pdb

            # now previous code transformer is restored (but `gm`'s code with pdb
            # remains - that means you can run `gm` with pdb here too, until you
            # run next `recompile()`).
        c               3   f   K   	 d   j                   _        y #  j                   _        w xY wwr1   )r  r   )on_gen_code_oldrg   s   r-    on_generate_code_context_managerz@Graph.on_generate_code.<locals>.on_generate_code_context_manager  s(     B2A///s   1 1.1)r  r   
contextlibr   )rg   rz  r~  r}  s   `  @r-   on_generate_codezGraph.on_generate_code  sK    T --99*:?*K'		"	"	B 
#	B 011r,   )NNN)Fr1   )r;   r   )NNNN)5r%   r&   r'   r(   r   r   r   r   r)   r   rh   propertyr  setterr   r  r   r  r   r  r  r   r  r   r   r  r!  r  r%  r&  r'  rY  r}  r|  rv  r   rw  r  rZ  r   r
  r   rK  rZ   rJ  rT  r\  ro  rv  r   ry  TransformCodeFuncr  r+   r,   r-   r   r   ;  sD   )V $/mq;?@h}&= @RZ[_`h[iRj @ (c3h 8@ 0@" # # "-!8 " "  z     %0BFUY  Xh-? d  1. $/W T4Z0@ _s  04$ $/=A>B*./3	1c 18 1"5#9:1$T#z/%:;1 #3-1  (}	1 9=	1 01f %03 13 %02 12 $/"%D "%T "% 0"%H $/-(4. - 0-. $/,$ , 0,. $/@D*1*;*;*A*AU U U$'UFJU 0U8 $/8Qs 8Qx} 8QPT 8Q 08Qt $/ >B>B/3	*_!$*_"5#9:*_ %T#z/%:;*_  (}	*_ 9=	*_ 0*_X $/ >B>B/3	 _!$ _"5#9: _ %T#z/%:; _  (}	 _ 9=	 _ 0 _D $/ @D@D15	 b$,S#X$6 b$U?%;< b 'tCO'<= b "*#	 b ;?	 b 0 bD $/R] d 8TFJ<N3O bf  0< $/cZ cHSM c 0c(	f 	 	 $/ eTYkpAAA/3AMQAdhA 
A 0AJ eTYkp

+5

/3
MQ
dh
 

 $ $/G 0G& $/R 0Rh $/<(8TFDL;Q2R < 0<| %0 7   1  %0S2"H->$?#@BS#STS2 1S2r,   r   z{} + {}z{} - {}z{} * {}z{} // {}z{} / {}z{} % {}z{} ** {}z{} << {}z{} >> {}z{} & {}z{} | {}z{} ^ {}z{}[{}]z{} @ {})rr   rm   mulfloordivtruedivdivr  powlshiftrshiftand_or_xorgetitemmatmulz{} == {}z{} != {}z{} < {}z{} > {}z{} <= {}z{} >= {}z+{}z-{}z~{})	eqneltgtlegeposneginvertz{} += {}z{} &= {}z	{} //= {}z	{} <<= {}z{} %= {}z{} *= {}z{} @= {}z{} |= {}z	{} **= {}z	{} >>= {}z{} -= {}z{} /= {}z{} ^= {}z{}[{}] = {})iaddiand	ifloordivilshiftimodimulimatmulioripowirshiftisubitruedivixorsetitem)kcollectionsr   rU  r   r   r   r   r	   r
   torch.utils._pytreeutilsr   r9   rE   r8   _compatibilityr   torch._Cr   r  r  typingr   r   r   r   r   r   r   r   r   r   r   r   dataclassesr   r   r   r1  r6   r|   rb   r~   mathr  r%  __all__graph_moduler   _symbolic_tracer    r5  r  r]   	frozensetr-  r  r)   r  r"   r.   r*   r2   r3   r4   r   r7   r   rA   rN   rX   rZ   bfloat16float64float32float16float8_e4m3fnfloat8_e5m2float8_e4m3fnuzfloat8_e5m2fnuz	complex32	complex64
complex128int8int16int32int64uint8uint16uint32uint64bits16r  r   r   r   r   r   r   r   r   r  r  r   reflectable_magic_methodsr  r  r+   r,   r-   <module>r     se   # R R $ $ " )  	  x x x x ! %     	    
,)'
 	$$y	5  d3i[$s)34 
Z 
 /1 $sN*+ 0=3 =C =c =  6 A  6 A %<d4j I .% 8 #=u|| L &Li X #I6 R3 3 33 3 &  (X# X#t	NNF	MM5 
MM5 
MM5	
 
 
x 
< 
< 
OOU 
OOU 
f 
JJ 
KK 
KK 
KK  
JJ!" 
KK#$ 
LL%	LL%	LL%	LL%+0 d+

4 
4  ,
4 c c 	. 	.Y Y (* ( $
T 
T 
TC * e,AE AE -AETJ8W J8XY Y< d+Y2 Y2 ,Y2z  $ 





	 	3 2	3 r,   