
    ^j                      U 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
d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZmZmZmZmZ d dlmZ d dlmZ d dlmZmZmZmZ d dl Z d dl!m"c m#Z$ d dl%m&Z'm(Z( d d	l)m*Z*m+Z+ d d
l,m-Z- d dl.m/Z/ ddl0m#Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z=  e	j|                  e?      Z@g dZAerd dlBZBddlCmDZD ddlEmFZF eGej                  eIej                  eKej                  eMej                  eOej                  iZQeIj                  g d      ZSeeGeT   geGeT   f   ZU G d de      ZVej                  D  ci c]
  } |  eX        c} ZYeYj                  ej                         i Z\de]d<   dd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&e1        e^d'd(e$       dd)Zcdd*Zd ej                   ej                  d+      j                  d,      Zh ej                  d-      Zi ej                  d.      Zj ej                  d/      j                  Zldd0Zm G d1 d2      Zn e3d34      e G d5 d6                    Zodd7Zp G d8 d9      Zq G d: d;      Zr G d< d=e      Zs ed3>       G d? d@             Zt	 d	 	 	 	 	 ddAZu e3dB4       G dC dD             Zv G dE dFev      Zw G dG dHev      Zx G dI dJex      Zy G dK dL      Zz e3d34       G dM dN             Z{e	 	 	 	 ddO       Z|ddPZ}ddQZ~dRdSdTdUdVdWdXdYdZZej                         D  ci c]  \  } }|  e~|       c}} Z ej                  d[      Zd\d]d^d_d`d`dadbdcdddedfdgdhdidjZdkdldmdndodpdqdrdsdt	eZdudvdwdxdydzd{d|d}d~dddddZyc c} w c c}} w )    )annotationsN)defaultdict)Callable	GeneratorIterableIteratorSequence)contextmanager)	dataclass)AnyLiteral
NamedTupleTYPE_CHECKING)_fx_map_arg	_NodeIter)get_opaque_obj_repris_opaque_value_typepy_sym_types)dtype_abbrs   )_pytree)compatibility)immutable_dict)_get_qualified_name
_type_reprArgumentNodeTarget)
TensorType)
PythonCodeCodeGenGraph)Tracer)GraphModule)call_functioncall_methodget_attrcall_moduleplaceholderoutputc                  &    e Zd ZU dZded<   d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.
    str
import_strobjectobjN__name__
__module____qualname____doc____annotations__     Y/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/fx/graph.pyr-   r-   F   s     O	Kr9   r-   zdict[str, _CustomBuiltin]_custom_builtinsc                <    t        ||      t        | <   |t        | <   y N)r-   r;   _illegal_names)namer/   r1   s      r:   _register_custom_builtinr@   [   s    +J<TN4r9   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 pytreec                J    | j                  d      xr | j                  d      S )N__)
startswithendswithxs    r:   	_is_magicrN   i   s    <<2!**T"22r9   c                4    t        |       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``
    )_snake_case_sublower)ss    r:   _snake_caserS   m   s     1##%%r9   z(?<=[a-z])([A-Z])z_\1z[^0-9a-zA-Z_]+z&^([a-zA-Z_][0-9a-zA-Z_]*?)(?:_(\d+))?$z,^torch(?:\.(?!_dynamo\.|_inductor\.)[^.]+)*$c                    t        | dd       }|t        |      d uS t        | dd       }|;|dk7  r6t        t        j                  j                  fD ]  }t        ||d       | u s y y)Nr4   r3   rD   TF)getattr_torch_but_not_dynamorD   nn
functional)r1   module_namer?   guesss       r:   _is_from_torchr[      sw    #|T2K$[1==3
D)DDGOUXX001 	EudD)S0	 r9   c                  0    e Zd ZdZddZddZd	dZd
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               | _        i | _        y r=   )_obj_to_nameset_used_names_base_countselfs    r:   __init__z_Namespace.__init__   s    /1%(U+-r9   c                   ||| j                   v r| j                   |   S t        j                  |      }|Wt        j	                  d|      }|sd}|d   j                         rd| }t        j                  |      }|t        d|       |j                  dd      \  }}||| j                  v rA| j                  j                  |d      }t        j                  ||      |ur|dz  }| d| }nt        |      }|| j                  v r|dz  }| d| }|| j                  v r| j                  j                  |       || j                  |<   ||| 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.
        __unnamedr   z&Name regex failed to match candidate: r      )r_   _name_regexmatch_illegal_char_regexsubisdigitAssertionErrorgroupra   rb   getr>   intadd)rd   	candidater1   rk   basenums         r:   create_namez_Namespace.create_name   s    ?sd&7&77$$S)) !!),=+//Y?I&	|##%	{O	%%i0E}$<YKH  KK1%	c;)t'7'77 ""&&tQ/C!!)S1<q#fAcUO	 c(C4+++1HC&#I 4+++ 	Y'!$?%.Dc"r9   c                Z    | j                   j                  ||      }||urt        d      y)zpAssociate a unique name with an object.

        Neither `name` nor `obj` should be associated already.
        zobj is already associatedN)r_   
setdefaultro   )rd   r?   r1   maybe_existings       r:   associate_name_with_objz"_Namespace.associate_name_with_obj   s5    
 **55c4@% !<== &r9   c                    || j                   vrt        d| d      || j                   |<   | j                  j                  |       y )NzObject z is not in _obj_to_name)r_   ro   ra   rs   )rd   r1   r?   s      r:   _rename_objectz_Namespace._rename_object   sI    d''' 73%/F!GHH!%#T"r9   NreturnNone)rt   r.   r1   zobject | Noner   r.   )r?   r.   r1   r0   r   r   )r1   r0   r?   r.   r   r   )r3   r4   r5   r6   re   rw   r{   r}   r8   r9   r:   r]   r]      s    .
1f>#r9   r]   Tis_backward_compatiblec                  >    e Zd ZU dZded<   ded<   ded<   dZd	ed
<   y)r!   zZ
    Represents all the information necessary to exec or save a graph as Python code.
    r.   srczdict[str, Any]globalszdict[int, int | None] | None_lineno_mapr   rr   _prologue_startN)r3   r4   r5   r6   r7   r   r8   r9   r:   r!   r!      s&    
 
H .-OSr9   r!   c                |    |j                  d      }| }|D ]#  }|j                         s
d| d| d}| d| }% |S )N.zgetattr(z, ""))splitisidentifier)ru   targetelemsres        r:   _format_targetr      sX    LLEA ~~1#S2&A#Qqc
A	
 Hr9   c                  4    e Zd ZddZddZ	 	 	 	 	 	 	 	 ddZy)_InsertPointc                D    || _         |j                  |c| _        |_        y r=   )graph_insertorig_insert)rd   r   
new_inserts      r:   re   z_InsertPoint.__init__
  s    
*/--'%-r9   c                     y r=   r8   rc   s    r:   	__enter__z_InsertPoint.__enter__  s    r9   c                :    | j                   | j                  _        y r=   )r   r   r   )rd   typevaluetbs       r:   __exit__z_InsertPoint.__exit__  s     "--

r9   N)r   r#   r   zCallable[..., None]r   r   r~   )r   ztype[BaseException] | Noner   zBaseException | Noner   ztypes.TracebackType | Noner   r   )r3   r4   r5   re   r   r   r8   r9   r:   r   r   	  s8    D.(. $. '	.
 
.r9   r   c                  :    e Zd Z	 d	 	 	 	 	 ddZddZd	dZd	dZy)

_node_listc                D    |dvrt        d|       || _        || _        y )N)_next_prevz*direction must be '_next' or '_prev', got )ro   r   	direction)rd   r   r   s      r:   re   z_node_list.__init__  s4     .. <YKH  
"r9   c                .    | j                   j                  S r=   )r   _lenrc   s    r:   __len__z_node_list.__len__%  s    zzr9   c                \    t        | j                  j                  | j                  dk(        S )Nr   r   r   _rootr   rc   s    r:   __iter__z_node_list.__iter__-  "    ))4>>W+DEEr9   c                \    t        | j                  j                  | j                  dk(        S )Nr   r   rc   s    r:   __reversed__z_node_list.__reversed__0  r   r9   N)r   )r   r#   r   zLiteral['_prev', '_next']r   r   )r   rr   )r   zIterator[Any])r3   r4   r5   re   r   r   r   r8   r9   r:   r   r     s3    CJ##'@#	#FFr9   r   c                  0    e Zd ZU dZded<   ded<   ded<   y)	_PyTreeInfoz=
    Contains extra info stored when we're using Pytrees
    	list[str]	orig_argszpytree.TreeSpecin_speczpytree.TreeSpec | Noneout_specNr2   r8   r9   r:   r   r   4  s     $$r9   r   )frozenc                  B    e Zd ZU dZded<   ded<   ded<   ded<   d	dZy)
_ParsedStackTracez?
    Represents the top-most frame of a parsed stack trace
    r.   filelinenor?   codec                n    d| j                    d| j                   d| j                   d| j                   S )NzFile: :z in z, code: )r   r   r?   r   rc   s    r:   get_summary_strz!_ParsedStackTrace.get_summary_strI  s1    		{!DKK=TYYKx		{SSr9   Nr   r.   )r3   r4   r5   r6   r7   r   r8   r9   r:   r   r   >  s#     IK
I
ITr9   r   c                   | y t        j                  d      }| j                         j                  d      }t	        t        |      dz
  dd      D ]  }||   j                         }|j                  |      }|s*|j                  d      }|j                  d      }|j                  d      }	||dz      j                         }
|r |||	|
      st        |||	|
      c S  y )Nz$^File \"(.+)\", line (\d+), in (.+)$
ri   r      )	recompilestripr   rangelenrk   rp   r   )stack_trace	filter_fnpatternlinesidxlinematchesr   r   r?   r   s              r:   _parse_stack_tracer   N  s     jj@AG%%d+E SZ!^R, ?Sz!--%==#D]]1%F==#Dq>'')D4t!<$T64>>? r9   Fc                  "   e Zd ZU d Zded<   ddZddZddZddZ	 	 	 d	 	 	 	 	 	 	 	 	 dd	Z		 	 	 	 	 	 dd
Z
	 	 	 	 	 	 	 	 ddZdd	 	 	 	 	 	 	 ddZddd	 	 	 	 	 	 	 ddZd dZd!dZd"dZdddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#dZy)$r"   c                    t        |       S r=   )reprrL   s    r:   <lambda>zCodeGen.<lambda>j  s
    $q' r9   &Callable[[torch.types.PySymType], str]	_sym_reprc                     d | _         d| _        y )Nforward)_body_transformer
_func_namerc   s    r:   re   zCodeGen.__init__l  s    ;?(r9   c                8     dj                   fd|D              S )zAHelper to format function arguments in expanded multiline format. c              3  @   K   | ]  }j                  |        y wr=   )_format_single_arg).0argrd   s     r:   	<genexpr>z1CodeGen._format_multiline_args.<locals>.<genexpr>r  s     Dt..s3Ds   joinrd   argss   ` r:   _format_multiline_argszCodeGen._format_multiline_argsp  s    wwDtDDDr9   c                    d|v r:|j                  dd      \  }}d|j                          d|j                          dS d| dS )z9Helper to format a single argument with optional comment.#r       z,  # r   z,
)r   rstriplstrip)rd   r   arg_partcomment_parts       r:   r   zCodeGen._format_single_argt  sS    #:%(YYsA%6"Hl(//+,E,2E2E2G1HKK#c?"r9   c                *    t        |t              rdS dS )z<Helper to get opening and closing delimiters for containers.)())[])
isinstancetuple)rd   	containers     r:   _get_delimiterszCodeGen._get_delimiters|  s    '	59zIzIr9   Nc                    | j                  |      \  }}| j                  ||      }t        | | ddj                  fdt	        ||      D              z   | z   S )z?Helper to format containers (lists/tuples) in multiline format.r   r   c              3  B   K   | ]  \  }}d  |       d| d  yw)r   ,r   Nr8   )r   itemtrailerrepr_fns      r:   r   z6CodeGen._format_multiline_container.<locals>.<genexpr>  s0      !D' wt}oQwir2s   )r   _get_desc_trailersr   r   zip)rd   itemsdescsprefixr   ldelimrdelimdesc_trailerss       `   r:   _format_multiline_containerz#CodeGen._format_multiline_container  s{     --e4//u=?G hvhb!gg %(%> 
 	
r9   c                T    |dgt        |      z  S |D cg c]  }d| 	 c}S c c}w )z2Helper to generate description trailers for items.r     # )r   )rd   r   r   descs       r:   r   zCodeGen._get_desc_trailers  s4     =4#e*$$*/0$$tf000s   %c                    t        j                  |      }|j                         D ci c]  \  }}||j                  v s|| }}} ||i |S c c}}w )zDHelper to call a method with optional parameters based on signature.)inspect	signaturer   
parameters)rd   methodr   kwargssigkvfiltered_kwargss           r:   !_call_method_with_signature_checkz)CodeGen._call_method_with_signature_check  sV     ',2LLNRDAqa3>>>Q1a4RRt/// Ss   A AFexpanded_defc                   t        |      dk(  s|d   dk7  r|j                  dd       |r'| j                  |      }d| j                   d| d| dS 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   rd   def z(
r   r   r   , )r   insertr   r   r   )rd   	free_varsmaybe_return_annotationr  args_formatteds        r:   
gen_fn_defzCodeGen.gen_fn_def  s     y>Q)A,&"8Q'!88CNt's>*:!<S;TTUV $//*!DIIi,@+ACZB[[\]]r9   r   r   c                   |t         }|+t        |t        t        f      r| j	                  ||d|      S d ||       S )z
        Given the output arguments, generates the return statement of the FX function.
        Note: The returned statement should not be indented.
        zreturn r   )r   r   listr   r  )rd   output_argsr   r   s       r:   generate_outputzCodeGen.generate_output  sW     ?GK$!G33UIw 4   W[1233r9   c                    |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)`
        r8   r   s     r:   process_inputszCodeGen.process_inputs  s	     r9   c                    |S )z
        Transforms the outputs of the graph to be identical to the codegen.

        See ``process_inputs`` for more details.
        r8   )rd   outputss     r:   process_outputszCodeGen.process_outputs  s	     r9   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.
        r8   rc   s    r:   additional_globalszCodeGen.additional_globals  s	    
 	r9   verboseinclude_strideinclude_devicecoloredr  record_funcadditional_metac                  
#$%&'()*+,-./012345 g +g 'i ,i 5dg.xs# t         j                  j                  dd      dk(  xs# t         j                  j                  dd      dk(  t         j                  j                  dd      dk(  -d*,fd%t        j	                         D ]  \  }\  }} %||        d+%3fd3|r.t
        d	   1t
        d
   *t
        d   (t
        d   )t
        d   &nt        1t        *t        (t        )t        &d,$%&fd$	 	 	 	 	 	 d-$fd#i /i 4d./4fd}t        |      D ]  }|j                  D ]  } |||         d/'(4fd}d 0d0
'(0fd}d1d2d0#$%&')*+-.1 235fd}|	r'j                  d       t        |      D ]  \  }}r ||       'j                  d| d       |	xr |j                  dv }|r/'j                  d|j                   d| d|j                   d        ||        ||       |s{'j                  d|j                   d        |	r'j                  d       t        '      dk(  r'j                  d        t        5      dkD  rG %d!t        j                  j                         }dj#                  5D cg c]
  }| d"| d# c}      }nd} j$                  r j%                  '      ' j'                         D ]  \  }} %||         j)                   j*                  +.d   $      }i }|j-                  d      d%z   }g }d }dj#                  '      j/                  d      D ]V  }t0        j3                  |      }|t5        |j7                  d%            }5||t        |      |z   <   |j                  |       X dj#                  |      j9                  d      } dj#                  d& | j/                  d      D              } d| d'| d|  }!|j-                  d      d(z   }"t;        |!,||")      S c c}w )2Nr   FX_GRAPH_SHOW_STRIDE01FX_GRAPH_SHOW_DEVICEFX_GRAPH_SHOW_METAc                    t        |      r|t        j                  k7  rt        |      S j	                  | |      }|v r|   |k7  rt        d| d      |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.
            zGlobal name z% already assigned to different object)r[   rD   rE   r   rw   ro   )	name_hintr1   global_nameglobals_	namespaces      r:   
add_globalz,CodeGen._gen_python_code.<locals>.add_global  s     s#u||(;
 +3// $//	3?Kh&K(C/(&{m3XY  #"$'H[!r9   c                `   | dk(  ryt        |       }t        | t        j                        r=d|v r9t	        j
                  |       D cg c]
  } |       }}dj                  |      S t        | dd       x}rt        | t        j                        rt        j                  ||      } t        |      |      }t        | t              r| j                  }nt	        j
                  |       }|r,|D cg c]
  } |       }}| ddj                  |       dS |S  ||       S c c}w c c}w )Nr8   z()|
__origin__r   r   r   )r   r   types	UnionTypetypingget_argsr   rU   _GenericAlias_origin_type_maprq   r    dims)	otypenamer   r   origin_typeorigin_typename	type_argsr=  	type_reprs	          r:   rM  z+CodeGen._gen_python_code.<locals>.type_repr+  s   Bw!!}H!U__-#/28//!2DE3	#EExx~%%at<<{< a!5!56"2"6"6{K"PK",Z-Dk"Ra, !I & 2I6?@sIcN@D@-.a/?qAA** h**/ F" As   D&3D+red	dim_greendimdim_bluebluec                0   t        | t              rt        |       S 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        j                         rIt#        | j%                               }t'        | j(                        j+                  d      d   }d| d| dS t        | t              r=t-        |       dk(  rd | d	          d
S ddj/                  fd| D              z   dz   S t        | t"              r ddj/                  fd| D              z   dz   S t        | t0              r<d | j2                         d | j4                         d | j6                         dS t9        t        |             r1t;        |       \  }}|j=                         D ]  \  }	}
 |	|
        |S  t        |             S )N_fieldsr   r   ztorch.Tensor(size=z, dtype=r   r   r   r   z,)r  c              3  .   K   | ]  } |        y wr=   r8   r   a	_get_reprs     r:   r   z>CodeGen._gen_python_code.<locals>._get_repr.<locals>.<genexpr>s  s     *EA9Q<*E   r   c              3  .   K   | ]  } |        y wr=   r8   rV  s     r:   r   z>CodeGen._gen_python_code.<locals>._get_repr.<locals>.<genexpr>u  s     &Ay|&ArY  r   zslice()r   r   r   r   hasattrr   r   rD   _ops
OpOverloadHigherOrderOperatorenumEnum	__class__r3   r?   Tensorr!  sizer.   dtyper   r   r   slicestartstopstepr   r   r   )r   qualified_namer:  clsclsnamerc  rd  obj_repropaque_typesntrX  r=  rR  s              r:   rX  z+CodeGen._gen_python_code.<locals>._get_reprY  sD   #t$Cy C'GC,C!4T#Y!?(cC%tE#J'7&899ejj++UZZ-K-KL "5S!9(=%'C+mm$S\\37!!CHH:..C.CHHJ'CII,,S1"5+D6%BBC's8q=yQ0144*E*E!EEKKC&TYY&AS&AAACGGC'	#)) 45R	#((8K7LByY\YaYaObNccdee%d3i0)<S)A&,(..0 %DAqq!$%DI&r9   c                    | D cg c]
  } |       }}|j                  |j                         D cg c]  \  }}| d |        c}}       dj                  |      S c c}w c c}}w )N = r  )extendr   r   )r   r  rW  resr  r  rX  s         r:   _format_argsz.CodeGen._gen_python_code.<locals>._format_args  sb     *..A9Q<.C.JJFLLNKDAq1#S1/KL99S>! /Ks
   A%A*
c                \    | vr'|| <   j                  |g       j                  |        y y r=   )ry   append)rn  usernode_to_last_useuser_to_last_usess     r:   register_last_usesz4CodeGen._gen_python_code.<locals>.register_last_uses  s7    ((&* #!,,T26==a@ )r9   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.
            r*   Nr+   r   r   rq  r   ;  )oprv  rq   r   userskeysr   r   )rw  nodes_to_deletern  to_delete_strbodyrP  ry  s       r:   delete_unused_valuesz6CodeGen._gen_python_code.<locals>.delete_unused_values  s     ww-'ww("D!/33D"=O4::??$%*  &&t,?# %

&56T!W6&A! c#m"4!5R89D!	 7s   C!c           	        | j                   dvrd}rRg }D ]4  }|| j                  v s|j                  | d| j                  |           6 |rddj                  |       d}d}| j                  j	                  di       }i }|rG|j                         D ]/  \  }}t        |      }t        |      dkD  r|d	d d
z   ||<   +|||<   1 d| }d}	| j                  x}
rt        |
      x}r|j                         }	d}t        | d      r| j                  r| j                  j	                  dd	      }| j                  j	                  dd	      }|'|%dt        |       dt        |j                         }n+|dt        |j                         }n|dt        |       }d | d| | d|	        d}|k7  r|j                  |       y	y	y	)z}
            Append a summary of the stacktrace to the generated code. This is
            useful for debugging.
            >   r+   r*   r   : z# r   custom(   Nz...z Annotation: z'No stacktrace found for following nodesmeta	recomputeac_graph_idz ac_graph_id: z - z recompute: r   r   )r}  r  rv  r   rq   r   r.   r   r   r   r   r[  r?   )nodeadditional_meta_strpartskeyannotation_str
annotationannotation_truncr   	value_strstack_trace_strr   parsed_stack_tracemaybe_recompute_infor  r  summary_strr1  r  rP  prev_summary_strs                   r:   append_stacktrace_summaryz;CodeGen._gen_python_code.<locals>.append_stacktrace_summary  s4    ww77&(#"')E. E$))+!LLC5499S>2B)CDE 02499U3C2DA.F+!#!YY]]8R8
#% &0&6&6&8 :
U$'J	y>B.4=crNU4J,S149,S1: (55E4F%GN"K"&"2"22;2-?-LL)L*<*L*L*N')$4(TYY !%		k4 @I"&))--t"DK ,1H,S-=,>c#innBUAVW - #.1=c)..>Q=R/S,$01?K@P?Q/R, "3*=)>a?OPdOeefgvfw'x#y"zz|}"22'2$KK, 3] 8r9   c           	     d    ddj                  | D cg c]  }t        |       c}       dS c c}w )Nr   r  r   )r   r.   )shaperM   s     r:   stringify_shapez1CodeGen._gen_python_code.<locals>.stringify_shape  s-    tyy%!8Q#a&!89:!<<!8s   -
c                   | j                   dnd '| j                          }d}(r	 ddlm}m} |j                  }ddlm} ddlm	} | j                  j                  d| j                  j                  d| j                  j                  d	d                   }d8!#&fd
}	t        |t        j                        r|j                  t        j                   t        j"                  fvrt        |      t        j                  u xs$ t        |t        j$                  j&                        }
 |	|      }|
rd| d}nt        |      |u rg|t)        d       ||j*                  j,                  |j*                  j.                        }|j0                  j2                  }d| d| d |       d}n}|j0                  j2                  }d| d| d}n]t        ||      rt4        j7                  |      }d| d}n5t        ||      r)dt8        |j:                       &|j<                         d}d }r5| j                  j                  dd       }|| j>                  dk(  r|d| z  } rtA        | d      r| j                  rzjC                  d       | j                  jE                         D ];  \  }}jC                  | dtG        jH                  tK        |      dd       d       = jC                  d       | j>                  dk(  rt        | jL                  tJ              s!t)        dt        | jL                               | jN                  sdnd | jN                  d          }jC                  | jL                   | | |        | jL                  jQ                  dd      }|tS        |       k7  r jC                  tS        |        d| d       y | j>                  dk(  rt        | jL                  tJ              s!t)        d t        | jL                               jC                  tS        |        | dtU         | jN                  d         | jL                         d | jN                  d!d  | jV                         d"       y | j>                  d#k(  rtY        | jL                        s!t)        d$t        | jL                               t[        | jL                  d%d      d&k(  r| jL                  j2                  t\        v rt        | jN                  t^              s!t)        d't        | jN                               jC                  tS        |        | dt]        | jL                  j2                     j`                  fd(| jN                  D                 y t[        | jL                  d%d      d&k(  r| jL                  j2                  tb        v rrjC                  tc        | jL                  j2                     j`                  fd)| jN                  D          d*tS        |        | d | jN                  d                 y te        | jL                        } || jL                        }|d+k(  rt        | jN                  t^              rt        | jN                  d!   tJ              r| jN                  d!   jg                         rdti        | jN                        d,k(  rLjC                  tS        |        | dtU         | jN                  d         | jN                  d!                 y jC                  tS        |        | d| d | jN                  | jV                         d"       | j                  j                  d-d.      r)jk                  |       y | j>                  d/k(  rt        | jL                  tJ              s!t)        d0t        | jL                               jC                  tS        |        | dtU        $| jL                         d | jN                  | jV                         d"       y | j>                  d1k(  rqt        | jL                  tJ              s!t)        d2t        | jL                               jC                  tS        |        | dtU        $| jL                                y | j>                  d3k(  rd| j                   d4 '| j                          "d<   jC                  %jm                  %jn                  | jN                  d   r|nd 5             y tq        d6| j>                   d7| jL                         # t
        $ r d }d }Y 	'w xY w)9Nr   z : r   )DTensorDTensorSpecr   )TensorMetadatavaltensor_metaexample_valuec                    r 	| j                               nd}r| j                   nd} t        | j                              	| j                                |        |       S )Nr   )striderE   r   rd  r  )
ro  r  rE   rR  rQ  rO  r.  r-  rN  r  s
      r:   _tensor_annotationzGCodeGen._gen_python_code.<locals>.emit_node.<locals>._tensor_annotation	  so    <J_QXXZ8PRF.<z"F{177345 89:#F+,$V,-/r9   z: ""z6dtensorspec_format_shard_order_str is None for DTensorr   r  z)"z: "Sym(r  r*   r  r  z"""
r  P   T)widthcompactr   z$Expected node.target to be str, got rq  *r'   z4Expected node.target to be str for call_method, got r   r   r&   z)Expected node.target to be callable, got r4   	_operatorz$Expected node.args to be tuple, got c              3  .   K   | ]  } |        y wr=   r8   rV  s     r:   r   z>CodeGen._gen_python_code.<locals>.emit_node.<locals>.<genexpr>r  s     GhYZ	RSGhrY  c              3  .   K   | ]  } |        y wr=   r8   rV  s     r:   r   z>CodeGen._gen_python_code.<locals>.emit_node.<locals>.<genexpr>}  s     Ij[\)TU,IjrY  r|  rU   ri   
is_wrappedFr)   z4Expected node.target to be str for call_module, got r(   z1Expected node.target to be str for get_attr, got r+   z -> r  znode: r  )ro  ztorch.Tensorr   r.   )9r   torch.distributed.tensor._apir  r  format_shard_order_strModuleNotFoundError"torch.fx.experimental.proxy_tensorr   torch.fx.passes.shape_propr  r  rq   r   rD   rb  layout
sparse_csc
sparse_csr_subclasses
FakeTensorro   _spec
placementsshard_orderra  r3   r"   r   r   rd  r  r}  r[  rv  r   pprintpformatr.   r   r   replacer   r   r  callablerU   magic_methodsr   formatinplace_methodsr   r   r   ry   r  r#  NotImplementedError)*r  maybe_type_annotationmaybe_commentr  r  "dtensorspec_format_shard_order_strr   r  meta_valr  is_plaincoredtensor_metarj  val_strr  r  r  maybe_default_argraw_nameri  r:  rt  rX  r=  rR  r  rQ  rO  r  r  r.  include_metar-  r  rN  root_modulerd   r  rM  r,  wrapped_fnss*                         r:   	emit_nodez+CodeGen._gen_python_code.<locals>.emit_node  s   ii's9TYY3G2H-I " M>R $:: 7 LE99==IIMM-PT1UV
  h5(//$$$$R ;
  $H~=   %"3"3">">BH .h7D25dV1-h72=E"0 X#  (J$NN55$NN66( '0099!#avR	,0G/HK . '009925cU!D60D-,7%//9G.5gYb,A).9.1+hnn2M1N_g_m_mOnNoop,q)Dyy}}VT2#=(@!tD6]2M f 5$))G$ IIOO- DAq KK#Rs1vR NOrR	 G$ww-'!$++s3(>tDKK?P>QR  #iiBs9TYYq\3J2K-L "   {{m$9#:;L:Mm_]  ;;..sB7tDz)KK4:,c(2 >?M)!$++s3(NtTXT_T_O`Nab  Dzl#8"9^IVZV_V_`aVbLceiepep=q<rTYYqr]DKK@AD O+,(CDDUCVW 
 DKKr:kI,,=%dii7,B4		?BST  KK:,'<&=S()=)=>EEGh^b^g^gGhijl 
 DKKr:kI,,?KK*4;;+?+?@GGIj`d`i`iIjkllo:,'<&=S499UV<AX@Y[ !4T[[!A(E  9,"499e4"499Q<5		!113DII!+KK:,'<&=SPYZ^ZcZcdeZfPgimirirstiuAv@wx Dzl#8"9[M<X\XaXacgcncnKoJppqr 99==u5**;7M)!$++s3(NtTXT_T_O`Nab  Dzl#8"9%k4;;?@,tyyZ^ZeZeBfAgghj J&!$++s3(KDQUQ\Q\L]K^_  Dzl#8"9^KY]YdYd=e<fg H$99(37	$))8L7M1N+A.::,,		!&2d )	 ;  %twwiq&FGGq + >"G9=6>s   e e'&e'zc_rf = torch._C._profiler._RecordFunctionFast('## ENTER_GRAPH_PLACEHOLDER_KEY ##'); _rf.__enter__()
z# COUNTER: r   r&   r'   r)   _rf_z. = torch._C._profiler._RecordFunctionFast('## z ##'); _rf_z.__enter__()
z.__exit__(None, None, None)
z_rf.__exit__(None, None, None)
r   zpass
wrapz("r   r  r   c              3  &   K   | ]	  }d |z     yw)r   Nr8   )r   r   s     r:   r   z+CodeGen._gen_python_code.<locals>.<genexpr>  s     D4$D   z

   )r   r   )r9  r.   r1   r   r   r.   )rH  r0   r   r.   )r   r0   r   r.   )r   ztuple[Argument, ...]r  zdict[str, Argument]r   r.   )rn  r   rw  r   r   r   )rw  r   r   r   r  r   r   r   )r  zIterable[object]r   r.   )osenvironrq   r;   r   
_color_fns	_identityreversed_input_nodesrv  	enumerater}  r?   r   rD   fxr  r   r   r*  r  r  countr   _counter_regexpsearchrr   rp   r   r!   )6rd   nodesr  r<  r,  r-  r.  r/  r  r0  r1  r?   rg   r1   rz  r  
input_noder  r  r  i	do_record	wrap_name
wrap_stmtsr   prologue
lineno_mapprologue_len	new_linescur_idxr   counterr   fn_codeprologue_startrt  rX  r=  rR  r  rP  rQ  rO  r  r;  r  r  rx  r  rN  r  rM  ry  r  s6   ` ````` ` `                        @@@@@@@@@@@@@@@@@@@r:   _gen_python_codezCodeGen._gen_python_code  s     "	#%') /1T' 
JJNN1373> 	 ( 
JJNN1373> 	 zz~~&:C@CG	: /446 	"ND(1ctS!	"	+B U#C";/IU#C!*-Hf%DC!IC HD%	'N	"&	"0C	"	" .046	A
 UO 	5D"// 5
":t45	5	"6  7	- 7	-r	=F	H F	H F	H F	HP KKv !' 	MGAt )$/ KK+aS+,#  4 )I
 499+%STUSVVabfbkbkallz{ dO &d499+-JKL-	M. KK:;t9> KK!{a"6588==9I#UykD6$<#UVJJ!!))$/D224 	$KD%tU#	$ 99OO#A&%	 : 
 -/
~~d+a/!	GGDM''- 	'D%,,T2G"gmmA./<C
3y>L89  &	' yy#**40yyD4::d3CDD 	
 	
 $))$/!3"*	
 	
Q $Vs   ?Q r~   )r   r   r   r.   )r   r.   r   r.   )r   Sequence[object]r   ztuple[str, str])Nr   N)
r   r  r   Sequence[str] | Noner  r.   r   Callable[[object], str] | Noner   r.   )r   r  r   r  r   r   )r  Callable[..., Any]r   r   r  r   r   r   r  r   r  r.   r  boolr   r.   r"  r   r   r  r   r  r   r.   r   r   r   r   )r'  r   r   r   )r   zlist[tuple[str, Any]])r  r   r  r.   r<  r]   r,  r  r-  r  r.  r  r/  r  r  r  r0  r  r1  list[str] | Noner   r!   )r3   r4   r5   r   r7   re   r   r   r   r  r   r  r  r#  r%  r(  r*  r  r8   r9   r:   r"   r"   g  s    9JI5I)E#J '+26

 $
 	

 0
 

,1%1.B1	10(0140@C0	0 #^^ "%^
 ^ 
^8 '+2644 $	4
 04 
4(	 $$"!,0^
^
 ^
 	^
 ^
 ^
 ^
 ^
 ^
 ^
 *^
 
^
r9   r"   c                  ,    e Zd ZdZdd	 	 	 	 	 	 	 ddZy)_BoxedCodeGenz
    CodeGen subclass that generates code using the "boxed" calling convention.

    The boxed calling convention takes a single list argument and clears it
    after extracting the arguments, which allows for early deallocation of
    input tensors.
    Fr  c                   d| j                    d| d}|rc|D cg c]<  }|dk7  s	|j                  d      d   j                  d      d   j                         > }}|r|dz  }|D ]  }|d| d	z  } |d
z  }|S c c}w )a  
        Generate function definition for boxed calling convention.

        Instead of taking individual arguments, the generated function takes
        a single 'args_list' parameter, extracts placeholder values from it,
        and clears the list.
        r  z(self, args_list)r   rd   r   =z 
    args_iter = iter(args_list)
    z = next(args_iter)z
    args_list.clear())r   r   r   )rd   r  r  r  fn_defr  placeholder_varsvars           r:   r  z_BoxedCodeGen.gen_fn_def  s     ((9:Q9RRST @I :;AQWKQ%%c*1-335     ==+ ?Cse+=>>F?33 s
   
A;6A;Nr  )r3   r4   r5   r6   r  r8   r9   r:   r  r    s7     # "%
  
r9   r  c                       e Zd Zd fdZddZddZddZ	 	 	 	 	 	 	 	 ddZdd	 	 	 	 	 	 	 d fdZd	d	d
	 	 	 	 	 	 	 d fdZ	 xZ
S )_PyTreeCodeGenc                0    t         |           || _        y r=   )superre   pytree_info)rd   r	  ra  s     r:   re   z_PyTreeCodeGen.__init__?  s    (3r9   c                *    t        j                  | }|S r=   )rG   arg_tree_leaves)rd   inputs	flat_argss      r:   r%  z_PyTreeCodeGen.process_inputsC  s    **F3	r9   c                   | j                   | j                   j                  |S t        |t        t        f      s|g}| j                   j                  t        d      t        j                  || j                   j                        S )Nzpytree_info.out_spec is None)r	  r   r   r!  r   ro   rG   tree_unflattenrd   outs     r:   r(  z_PyTreeCodeGen.process_outputsG  sv    #t'7'7'@'@'HJ#e}-%C$$, !?@@$$S$*:*:*C*CDDr9   c                    |sy|D cg c]	  }d|v s| }}|sy|rddj                  |      z   S ddj                  d |D              z   dz   S c c}w )z=Helper to format annotations for variables in pytree codegen.r   r   r  c              3  &   K   | ]	  }|d z     yw)z; Nr8   r   rM   s     r:   r   z5_PyTreeCodeGen._format_annotations.<locals>.<genexpr>\  s     %G1a$h%Gr  r   r   )rd   r  r  rM   has_annotations        r:   _format_annotationsz"_PyTreeCodeGen._format_annotationsP  sb    %.;#(!;;hmmN;;;bgg%G%GGG$NN <s
   	AAc           
     H   | j                   j                  }|j                  t        u xrU |j                  dk(  xrD |j                  d      j                  t        u xr! |j                  d      j                  t        u }d}ddj                  |       d}|r|j                  d      j                  }| j                   j                  d | }ddj                  d	 t        |j                  d      j                  | j                   j                  |d        D              z   d
z   }ddj                  |       d| d}|D 	cg c](  }	|	j                  d      d   j                  d      d   * }
}	| j                  ||      }|ddj                  |
       d| dz  }|S c c}	w )Nri   r   r   z{}r   r  z], self._in_spec{c              3  2   K   | ]  \  }}d | d|   yw)'z':Nr8   )r   r  r  s      r:   r   z2_PyTreeCodeGen.gen_var_bindings.<locals>.<genexpr>p  s(      1 s"QCLs   }z([z], z), self._in_specr   r   r  z , = fx_pytree.tree_flatten_spec(r   )r	  r   r   r   num_childrenchilddictr   r   r   contextr   r  )rd   fn_argsr  r  r   has_args_kwargs_tuple	fn_kwargsfn_signature
count_argsrM   without_annotationbindingss               r:   gen_var_bindingsz_PyTreeCodeGen.gen_var_bindings^  s    ""** LLE! .$$).a %%.. a %%-	 	 	499W-..>?  q)66J&&00*=G))  #a(00((22:;?!     		' 233ykAQRL FOOaggcl1o33C8;OO++I|D 	YY!"##CL>QRV 	V	 Ps   -FFr  c               :   | 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                  |||      z  }|S )Nr  r   rd   F)r	  r  r  r   r   r  r'  )rd   r  r  r  r   has_orig_selffn_definitionra  s          r:   r  z_PyTreeCodeGen.gen_fn_def  s    , #7%2 &   "",,25g,2Bv-Q'*AJ/l + 
 y>AT227I|TTMr9   Nr  c                   |t         }| j                  rR| j                  j                  r<|.t        |t        t
        f      r| j                  ||d|      dz   S d ||       dS t        | !  |||      S )Nreturn pytree.tree_unflatten(r   , self._out_spec)r  )	r   r	  r   r   r!  r   r  r  r#  )rd   r"  r   r   ra  s       r:   r#  z_PyTreeCodeGen.generate_output  s     ?G 0 0 9 9 ZdE]%K44#7 '	 5  ** 7w{7K6LL]^^7*;eW*UUr9   )r	  r   r   r   r  r   r   r   r  r   r   r   )r  r   r  r  r   r.   r   r   r  r   r  r  r   r.   r  r  )r3   r4   r5   re   r%  r(  r  r'  r  r#  __classcell__ra  s   @r:   r  r  >  s    4EO% %-6%FJ%	%X #%% "%%
 % 
%V '+26VV $	V
 0V 
V Vr9   r  c                  |     e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 d fdZd fdZd	 fdZd
 fdZ	 	 	 	 	 	 	 	 ddZddZ xZ	S )_ExportCodeGenc                \    t         |   |       || _        || _        || _        || _        y r=   )r  re   in_shuffle_graphout_shuffle_graphtree_leaf_namesroot)rd   r	  r6  r7  r8  r9  ra  s         r:   re   z_ExportCodeGen.__init__  s1     	% 0!2.	r9   c                    t        |   | }| j                  | j                  g|}|| _         | j                  | S r=   )r  r%  r9  r  r6  )rd   r  r  ra  s      r:   r%  z_ExportCodeGen.process_inputs  sG    G*F3	99 /Y/I"$t$$i00r9   c                f     | j                   g | j                  | }| `t        |   |      }|S r=   )r7  r  r  r(  )rd   r  	flat_outsretra  s       r:   r(  z_ExportCodeGen.process_outputs  s:    *D**ADNNASA	Ng%i0
r9   c                &    t        |   |i |}|S r=   )r  r  )rd   r   r  r  ra  s       r:   r  z_ExportCodeGen.gen_fn_def  s    #T4V4r9   c           
     X   |D cg c](  }|j                  d      d   j                  d      d   * }}dj                  |       }| j                  d| }ddj                  | j                         d| ddj                  |       d	dj                  | j                         d
	S c c}w )Nr   r   r   r  zself, r  z, = pytree.tree_leaves((z,))
    z, = self._in_shuffle_graph(r   )r   r   r9  r8  )rd   r   r  r  rM   r%  r#  s          r:   r'  z_ExportCodeGen.gen_var_bindings  s     FOOaggcl1o33C8;OO#yy1299 #L>2L	YYt##$%%=l^ L	YY!"##>tyyI]I]?^>__`d 	d	 Ps   -B'c                   t        |t        t        f      st        dt	        |             ddj                  | j                         ddj                  |D cg c]  }t        |       c}       d}d| dS c c}w )Nz,Expected list or tuple for output_args, got zself._out_shuffle_graph(r  r   r,  r-  )r   r!  r   	TypeErrorr   r   r8  r.   )rd   r"  r   r  rW  r+   s         r:   r#  z_ExportCodeGen.generate_output  s    +e}5>tK?P>QR  ,DIId6J6J,K+LBtyyjuYvefZ]^_Z`YvOwNxxyz.vh6GHH Zws   A<)r	  r   r6  r%   r7  r%   r8  r   r9  ztorch.nn.Module | Noner   r   r.  r/  )r   r   r  r   r   r.   r0  )r"  r   r   r   r  r   r   r.   )
r3   r4   r5   re   r%  r(  r  r'  r#  r1  r2  s   @r:   r4  r4    s      & '	
 # % 
1	d 	d-6	dFJ	d		dIr9   r4  c                  F    e Zd ZdZd
dZddZddZddZddZdddd	Z	y)_FindNodesLookupTablezH
    Side table for the graph for the purpose of doing fast queries
    c                ,    t        t              | _        y r=   )r   r  tablerc   s    r:   re   z_FindNodesLookupTable.__init__  s    HSI

r9   c                V    |j                   |j                   dk(  r|j                  fS d fS )Nr&   r}  r   rd   r  s     r:   _keyz_FindNodesLookupTable._key  s(    ?(BMMMMr9   c                B    || j                   | j                  |         v S r=   rE  rI  rH  s     r:   __contains__z"_FindNodesLookupTable.__contains__  s    tzz$))D/222r9   c                F    d | j                   | j                  |         |<   y r=   rK  rH  s     r:   r  z_FindNodesLookupTable.insert
  s    ,0

499T?#D)r9   c                ^    | j                   | j                  |         j                  |       y r=   )rE  rI  poprH  s     r:   removez_FindNodesLookupTable.remove  s!    

499T?#''-r9   Nr   c                  |dk(  r.|t        d      g | j                  ||f   j                         S |!g | j                  |d f   j                         S | j                  |d f   D cg c]  }|j                  |k(  s| c}S c c}w )Nr&   z,target must not be None for call_function op)ro   rE  r  r   )rd   r}  r   r  s       r:   
find_nodesz _FindNodesLookupTable.find_nodes  s     ~$%STT5TZZV-22455>3TZZT
+00233 "&RJ!7Q4;;&;PQQQs   *B?Br~   )r  r   r   ztuple[str, Target | None]r  r   r   r  r  )r}  r.   r   Target | Noner   	list[Any])
r3   r4   r5   r6   re   rI  rL  r  rP  rS  r8   r9   r:   rC  rC    s-    

N31. >B 
Rr9   rC  c            	         e Zd ZdZ ed      	 	 	 d/	 	 	 	 	 	 	 d0d       Zed1d       Zej                  d2d       Zed3d       Z	 ed	      d4d
       Z
 ed	      ddd	 	 	 	 	 	 	 d5d       Z ed      	 d6	 	 	 	 	 	 	 d7d       Zd8d9dZ ed      	 	 	 	 d:	 	 	 	 	 	 	 	 	 	 	 	 	 d;d       Z ed	      d<d       Z ed	      d=d       Z ed      d>d       Z ed      d8d?d       Z ed      d8d?d       Z ed      dej*                  j,                  f	 	 	 	 	 	 	 d@d       Z ed      d8dAd       Z ed      	 	 	 d/	 	 	 	 	 	 	 	 	 dBd       Z ed      	 	 	 d/	 	 	 	 	 	 	 	 	 dCd       Z ed      	 	 	 	 d:	 	 	 	 	 	 	 	 	 	 	 dDd       ZedEd       Z ed	      dFd       Z ed	      dFd       Z ed	      dGd       Z  ed	      	 	 	 	 	 	 	 	 dHd       Z! ed	      	 	 	 	 dId       Z" ed	      dJd        Z# ed      d! f	 	 	 	 	 dKd"       Z$ ed      	 d8	 	 	 dLd#       Z%dMd$Z& ed      d	d	d	d	d	d	dd%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dNd&       Z'd	d	d	d	d	d	dd%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dOd'Z(dPd(Z) ed      dQd)       Z* ed      dQd*       Z+ ed      	 d8	 	 	 dRd+       Z, ed	      dSd,       Z- ed	      	 	 	 	 dTd-       Z.dQd.Z/y)Ur#   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   Nc                   t        | ddddi       | _        i | _        | j                  j                  | _        d| _        t               | _        || _        || _	        || _
        t               | _        i | _        t               | _        y)z+
        Construct an empty Graph.
        r   r9  r8   r   N)r   r   ra   prependr   r   r]   _graph_namespace_owning_module_tracer_cls_tracer_extrasr"   _codegen
_co_fieldsrC  _find_nodes_lookup_table)rd   owning_module
tracer_clstracer_extrass       r:   re   zGraph.__init__O  sw      b&"b"=
+-zz))	 *+%+	*,(=(?%r9   c                    | j                   S r=   r[  rc   s    r:   ra  zGraph.owning_modulee  s    """r9   c                    || _         y r=   re  )rd   mods     r:   ra  zGraph.owning_modulei  s
    !r9   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   rc   s    r:   r  zGraph.nodesm  s     $r9   Fc                    t        t        t        | j                                    }|j                  dk7  rt        d|j                         |S )Nr+   zExpected output node, got op=)nextiterr  r  r}  ro   )rd   output_nodes     r:   rl  zGraph.output_node|  sD    4 456>>X% #@@P!QRRr9   )r   sortc               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:

            Iterable of nodes with the requested op and target.
        rG  )r`  rS  sorted)rd   r}  r   rm  	node_lists        r:   rS  zGraph.find_nodes  s3    , 11<<6<R	)$$r9   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.
        r+   r   c                    |    S r=   r8   rn  val_maps    r:   r   z"Graph.graph_copy.<locals>.<lambda>  s    WQZ r9   c                    |    S r=   r8   rs  s    r:   r   z"Graph.graph_copy.<locals>.<lambda>  s    71: r9   N)r  r}  map_argr   	node_copy)rd   grt  return_output_noder  rvs     `   r:   
graph_copyzGraph.graph_copy  sp    ( GG 	GDwww("TYYq\+?@!3rC"dC NN41EFGDM	G r9   c                   |r|ni }t        | j                        }|j                  | |d      }t        j                  | j
                        |_        |nt        |t              st        dt        |             |\  }}|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.
        )rb  T)rt  ry  Nz&Expected output_vals to be tuple, got r   	type_expr)r#   r\  r{  copydeepcopyr^  r   r   ro   r   r+   rU   r  )rd   memorx  output_vals
output_valold_output_nodenew_output_nodes          r:   __deepcopy__zGraph.__deepcopy__  s     tT--.ll# # 

 ]]4==1
"k51$<T+=N<OP  +6'Jhh!/64@ ' O $(99_-A-A#BO r9   c                   |sd}n't        |t              st        dt        |             |st	               }n't        |t
              st        dt        |             |dv r|s|rt        j                  ||f      D ]t  }t        |t        j                  t        j                  t        j                  f      s=t        j                  dt        |      j                   d| d| d| d		d
        n ||n| j                  |      }| j                   j#                  |d      }t%        | ||||||      }	| j&                  :t)        | j&                  dd      #| j&                  j*                  D ]
  }
 |
|	        | j                   j-                  ||	       | j/                  |	       | j0                  j3                  |	       | xj4                  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.
        r8   zargs must be a tuple, got zkwargs must be a dict, got r  zRaw z value (z.) passed as argument to Graph.create_node(op='z
', target=zu). Use create_*_node() helpers for tensor metadata queries or materialize_symints() for general symbolic expressions.ri   
stacklevelN_create_node_hooksr   )r   r   ro   r   r   r  rG   	tree_iterrD   SymIntSymFloatSymBoolwarningswarnr3   _target_to_strrZ  rw   r   ra  rU   r  r{   r   r`  r  r   )rd   r}  r   r   r  r?   r~  r  rt   rn  fs              r:   create_nodezGraph.create_node  s   H DdE*$'A$t*%NOO#%Ffd+$'B4<.%QRR @@df''v7 	cELL%..%--#PQMMtCy112(3% @113Jvh GUV $% 	 !,D$2E2Ef2M	$$00DAtRvyA ***,@$GS'':: ! 	55dA>Q%%,,Q/		Q	r9   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2r9   c                8    | j                   j                  |      S r=   )r^  r(  r  s     r:   r(  zGraph.process_outputs0  s    }},,S11r9   c           	        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_        |j                  t        |j                   d       t        |j"                  d              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 r=   r8   rn  s    r:   r   z"Graph.erase_node.<locals>.<lambda>Y      r9   c                     y r=   r8   r  s    r:   r   z"Graph.erase_node.<locals>.<lambda>Z  r  r9   )r   r~  RuntimeErrorr   _erasedr  r  ra  rU   r  r`  rP  _remove_from_listr   _update_args_kwargsrv  _args_kwargs)rd   to_eraser  s      r:   
erase_nodezGraph.erase_node4  sB    x~~"&xj0B3x~~CVBW X''/~~&6a9  >>T!!6xj@RSTTMMKz1LMN ***,?FR''99 ( 	%%,,X6""$		Q	 	$$HNNN3H$$n5	
r9   c                    || j                  | j                        S |j                  | k7  rt        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 temporarily 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   ro   r   rY  rd   rn  s     r:   inserting_beforezGraph.inserting_before]  sF    & 9''

3377d? !IJJD!)),,r9   c                    || j                  | j                        S |j                  | k7  rt        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 temporarily 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   ro   r   rv  r  s     r:   r  zGraph.inserting_afterv  sF    & 9((4477d? !HIID!((++r9   c                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``.
        r8   r*   )r   r~  )r
  	Signatureemptyr  )rd   r?   r~  default_valuer   s        r:   r*   zGraph.placeholder  s;    < #g&7&7&=&==rMCSt$)TTr9   c                    	 	 	 	 	 	 dd}| j                   * || 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``.
        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)Nr   zFailed to fetch module r  FT)
rpartitionget_submoduleAttributeErrorr  r  r[  rU   r   rD   rW   Module	Parameter_buffers)rg  ri  module_pathrg   r?   submodrs  s          r:   _get_attr_reference_existsz2Graph.get_attr.<locals>._get_attr_reference_exists  s     $2#<#<S#A KD*-*;*;K*H
 64(&$'C sEHHOO4"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 bufferri   r  r(   r}  )rg  ztorch.nn.Moduleri  r.   r   r  )ra  r  r  r  )rd   ri  r~  r  s       r:   r(   zGraph.get_attr  sr    4	 	25		2 )2L3
 MM#  
NiPPr9   c                    | j                   0| 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}  )ra  r  r  r  r  )rd   rY   r   r  r~  s        r:   r)   zGraph.call_module  s^    N *""00=EMM& ;f	   
 	
r9   c                .    | 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`.
        r'   r}  r  )rd   method_namer   r  r~  s        r:   r'   zGraph.call_method)  s(    F ;f	   
 	
r9   c                0    | j                  d|||||      S )ag  
        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.

            name (Optional[str]): The name of the node. If not specified, set to None

        Returns:

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

        .. note::
            The same insertion point and type expression rules apply for this method
            as :meth:`Graph.create_node`.
        r&   )r?   r~  r  )rd   the_functionr   r  r~  r?   s         r:   r&   zGraph.call_functionP  s*    L \4di   
 	
r9   c                    d| j                   v r| j                   d   dfS d| j                   v r| j                   d   dfS y)a  Read the example tensor stored on ``tensor_node`` under either
        ``meta['val']`` (export / proxy_tensor convention) or
        ``meta['example_value']`` (dynamo convention).

        Returns ``(value, key)`` where ``key`` is the meta key the value was
        found under (defaulting to ``"val"`` if no meta is present). Callers
        that emit a new node should mirror ``key`` so the new node matches
        the surrounding graph's convention.
        r  r  )Nr  )r  )tensor_nodes    r:   _get_tensor_meta_valzGraph._get_tensor_meta_valz  sO     K$$$##E*E11k...##O4oEEr9   c                    | j                  |      \  }}| j                  t        j                  j                  j
                  j                  ||f      }||j                  |      |j                  |<   |S )z0Create an FX node for ``tensor_node.size(dim)``.)	r  r&   rD   opsatensym_sizerr   rc  r  rd   r  rP  r  r  r  s         r:   create_size_nodezGraph.create_size_node  sb     ,,[9S!!%)).."9"9"="=S?QR? XXc]DIIcNr9   c                    | j                  |      \  }}| j                  t        j                  j                  j
                  j                  ||f      }||j                  |      |j                  |<   |S )z2Create an FX node for ``tensor_node.stride(dim)``.)	r  r&   rD   r  r  
sym_striderr   r  r  r  s         r:   create_stride_nodezGraph.create_stride_node  sb     ,,[9S!!%))..";";"?"?+sAST? ZZ_DIIcNr9   c                    | j                  |      \  }}| j                  t        j                  j                  j
                  j                  |f      }||j                         |j                  |<   |S )z7Create an FX node for ``tensor_node.storage_offset()``.)	r  r&   rD   r  r  sym_storage_offsetdefaultstorage_offsetr  )rd   r  r  r  r  s        r:   create_storage_offset_nodez Graph.create_storage_offset_node  se     ,,[9S!!IINN--55~
 ? //1DIIcNr9   c                   ddl }ddlm}m}m}m} |}	d}
|
t        |      k  r9||
   }|
dz   t        |      k  r||
dz      nd}t        ||      rt        |t        j                        ru|j                  }|j                  dk(  r| j                  |	|      }	n@|j                  dk(  r| j                  |	|      }	n| j                  |j                  |	|f      }	|
dz  }
nnt        ||      rE|j                  dk(  r| j                  |	      }	n| j                  |j                  |	f      }	|
dz  }
nt        |t        j                        r.| j!                  |j"                  |	|j                  f      }	|
dz  }
nt        ||      r)| j!                  t$        j&                  |	ddf      }	|
dz  }
nt        ||      rR|j(                  }t        |t$        j*                        r ||      }| j!                  |j,                  |	|f      }	|
dz  }
nBt        ||      r(| j!                  t.        |	|j0                  f      }	|
dz  }
nt3        d	|       |
t        |      k  r9|	S )
a  Walk an ``unbacked_bindings`` keypath, emitting FX ops on this
        graph to recover the bound SymInt from ``producer``'s result.

        ``lower_symint`` is invoked for the only keypath component that may
        carry a non-literal value: ``DivideByKey`` with a SymInt divisor.
        Callers must provide one (e.g. a wrapper around their sympy interp
        cache).
        r   N)CallMethodKeyConvertIntKeyDivideByKeyInnerTensorKeyr   rc  r  ri   r  zunrecognized keypath component )operator%torch.fx.experimental.symbolic_shapesr  r  r  r  r   r   rG   SequenceKeyr   r?   r  r  r'   r  r&   getitemrD   sym_itedivisorr  floordivrU   
inner_namero   )rd   producerkeypathlower_symintr  r  r  r  r  r  r  r  nxtr   r  s                  r:   _resolve_unbacked_bindingzGraph._resolve_unbacked_binding  s)    		
 	
 #g,
A$%ECL$8'!a%.dC!]+
3@R@R0Sgg66V#00s;DVVx'224=D++AFFT3K@DQA}-66--::4@D++AFFTG<DQAv112))(*:*:T155MJQA}-))%--$1FQA{+))gu||4*73G))(*;*;dG_MQA~.))'D!,,3GHQ$'Fqc%JKKE #g,F r9   c                     ddl ddlddlmm ddlm ddddt        j                  j                  j                          i i i dfd} j                  D ]G  }|j                  dk(  r |      }t        |t              rW|j                  j                   }t        |j"                        sX|vs]t        j                  j%                  | 	      |<   t        |t        j&                        st)        |j*                        D ]>  \  }}t        |t        j,                        s! ||j                  j                   ||       @ |j.                  j1                  d
      }|s|j3                         D ]"  \  }	}
j5                  |	|t7        |
      f       $ J ddlm ddlmm  dfddf	ddfdd  fdg }|D ]P  }t        |t        j,                        rnGt        |tB              r|jE                  |       AtG        dtI        |      jJ                   d|d      |j                  j                   }|jL                  r|jE                  tC        |             |jN                  D ]
  }	 |	         |      }t        |t        j                  j$                        sCt        |tB        tP        f      stS        d|d|      |jE                  tC        |             +|j                  } ||       |jE                  |       S |S )ay	  Materialize a list of ``SymInt``/``int`` values as FX subgraphs rooted
        at existing nodes in this graph whose meta produces the referenced
        symbols (typically SymInt placeholders or other sym ops).

        consider a graph with a tensor placeholder
        ``%x`` of shape ``(s32, s32)`` and we want to record this stride
        as an FX value to pass to a later op, two ways to do it.

        * ``g.create_stride_node(%x, 0)`` emits ``%t = aten.sym_stride.int(%x, 0)``.
          The semantics of this op are "ask ``%x`` for its current stride at
          dim 0". If a later pass (e.g. mkldnn channels-last conversion) mutates
          ``%x``'s layout, re-running ``FakeTensorProp`` will overwrite
          ``%t.meta["val"]`` with the NEW stride. This is the right behavior
          when you want a *live* query on the producer.

        * ``g.materialize_symints([%x.meta["val"].stride(0)])`` walks the sympy
          expression ``s32`` and emits an FX subgraph that recomputes it from
          the existing producer of ``s32`` (here the placeholder ``%x`` itself
          via ``aten.sym_size.int(%x, 0)``, or a SymInt placeholder if one
          exists). The resulting node's value is "what ``s32`` is at runtime"
          -- which is determined by the input's shape and is INDEPENDENT of any
          layout change to ``%x``. This is the right behavior when you want to
          *freeze* the trace-time stride into the graph.

        Note: like other ``Graph`` node-creation APIs (``call_function``,
        ``create_size_node``, etc.), nodes are emitted at the graph's current
        insertion point. The default insertion point (``Graph._root.prepend``)
        appends new nodes to the end of the graph, which on a graph that
        already has an ``output`` node means they land *after* ``return``
        (orphaned). Callers typically scope this in
        ``with graph.inserting_before(graph.output_node()):`` so the new
        nodes land in the body.

        Performance: each call performs an O(graph_size) producer-discovery
        scan and builds a per-call ``expr_to_proxy`` hash-cons cache. Prefer
        batching every SymInt you need to lift into a single call (or as few
        calls as possible) over calling it once per value -- this amortises
        the graph scan and lets symints with shared sub-expressions get
        hash-consed into a single subgraph.
        r   N)_run_sympy_handlersympy_interp)PythonReferenceAnalysisc                v    | j                   j                  d      }||S | j                   j                  d      S )Nr  r  )r  rq   rn  r  s     r:   	_node_valz,Graph.materialize_symints.<locals>._node_val$  s1    &&**U#C
66::o..r9   c                z    || j                   d<   t        d | j                  D              r|| j                   d<   yy)zSet ``n.meta['val']`` and, if any of ``n``'s input nodes carry
            ``"example_value"``, mirror it there too so the new node matches
            the surrounding graph's meta-key convention.r  c              3  \   K   | ]$  }t        |t              xr d |j                  v  & yw)r  N)r   r   r  )r   rW  s     r:   r   zCGraph.materialize_symints.<locals>._set_node_val.<locals>.<genexpr>/  s(     U:a&D?aff+DDUs   *,r  N)r  anyr   r  s     r:   _set_node_valz0Graph.materialize_symints.<locals>._set_node_val*  s7      AFF5MUaffUU*-' Vr9   c                   t        | j                        rj                  | ||df       yt        | j                        rt	        | j
                        dk(  r| j
                  \  }}t        |j                        rt        |j                        r||}}t        |j                        rEt        |j                        r.t        |      dkD  rj                  |||t        |      f       yyyyyy)aC  Register ``(node, dim)`` as a recoverable source for ``expr``.

            - bare ``Symbol``: divisor = 1.
            - ``Symbol * c`` (positive integer constant): divisor = c.
              Recovery is ``sym_size.int(ph, dim) // c``.
            - anything else: skipped (general inverse needs sympy.solve).
            r   Nri   r   )r   Symbolry   Mulr   r   Integerrr   )exprr  rP  rW  bsym_size_sourcessympys        r:   _record_shape_sourcez7Graph.materialize_symints.<locals>._record_shape_sourceF  s     $- ++D4a.A$		*s499~/Byy1a.:a3OaqAq%,,/"1emm4A
$//D#s1v3FG # 5 0 0C*r9   r*   tracerunbacked_bindings)BooleanAtom)r  free_unbacked_symbolsc                `    t        | t        j                  j                        r |       S | S r=   )r   rD   r  r   )rW  r  s    r:   _arg_meta_valz0Graph.materialize_symints.<locals>._arg_meta_valt  s$    !UXX]]+ |#Hr9   c           	       	 | v r|    S t        | j                  j                  j                  
f      r
 |       S  | j                  D cg c]
  } |       c}|       }t        |t
        j                  j                        s|S || <   |j                  }|j                  }t        |      s|S 	 t        fd|j                  D              }|j                  j                         D ci c]  \  }}| |       }}} | ||i |       |S c c}w c c}}w # t        t        t         f$ r"}	t"        j%                  d| |	       Y d }	~	|S d }	~	ww xY w)Nc              3  .   K   | ]  } |        y wr=   r8   )r   rW  r  s     r:   r   zJGraph.materialize_symints.<locals>._sympy_interp_cached.<locals>.<genexpr>  s     !Fq-"2!FrY  z8materialize_symints: skipping meta annotation for %s: %s)r   r  Numberr  r   rD   r  Proxyr  r   r  r   r  r   rA  
ValueErrorr  logdebug)r  r   resultr  r   	fake_argsr  r  fake_kwargsr   r  r  r  r  r  _sympy_interp_cachedexpr_to_proxyr  r  s             r:   r  z7Graph.materialize_symints.<locals>._sympy_interp_cachedy  sZ   }$$T**u}}ellELL+N $$;]DQQ''6:ii@s%c*@F
 fehhnn5"(M$;;D[[FF#	!!FDII!FF	?C{{?P?P?RStq!q-"22SSdFI$E$EF M) A Tz>: 		N 
 Ms0   D
<;D) 7D#
D) #D) )E=EEc                     | j                   j                        }t        |t        j                  j
                        r|j                   S |S r=   )r  r  r   rD   r  r   )dr   r  s     r:   _lower_symint_divisorz8Graph.materialize_symints.<locals>._lower_symint_divisor  s5    $QVV[[1A'588>>:166AAr9   c                   | v ry | v r!|    \  }}}j                  t        j                  j                  j                  j
                  ||f      } |      }t        |t        j                        r ||j                  |          |dk7  rvj                  j                  ||f      }t        |t        j                        r ||j                  |   |z         t        j                  j                  |      | <   y t        j                  j                  |      | <   y | v r |       st        d|  d      |    \  }}|D ]k  }	t        |	      st        |	j                  t        j                        s5|	j                  j                  j                   j"                  D ]
  }
 |
        m j%                  ||      }t        j                  j                  |      | <   y t        d|        )Nr   r  z#materialize_symints: backed symbol zV has no input producer (backed symbols cannot be recovered from non-placeholder nodes))r  z%materialize_symints: no producer for )r&   rD   r  r  r  rr   r   rb  r  r  r  r   ro   r  r  r  r  free_symbolsr  )symphrP  r  sym_nodetensordiv_nodeproducer_noder  r  s2r  r  _ensure_producedr  r  r  r  r  r  rd   r  sym_to_bindingr  s               r:   r  z3Graph.materialize_symints.<locals>._ensure_produced  s   m#&&#3C#8 C--eiinn.E.E.I.IBPS9U"2fell3!(FLL,=>a<  $11 ))Hg+> H "&%,,7%hS0AW0LM).)PM#&  */)PM#&n$,S1(=cU C6 7 
 *8)<&w  1A!![1j		5<<7 #$)).."5"5"B"B 1B,R01	1  99!79N :  &+XX^^HV^%Lc" #H!NOOr9   z1materialize_symints: expected SymInt or int, got z (r   z&materialize_symints: non-Proxy result z for non-constant target )rn  r   r   r   )rn  r   r  r   r   r   )r  
sympy.Exprr  r   rP  rr   r   r   )rW  r   r   r   )r  r  r   r   )r
  ztorch.SymIntr   
Node | int)r  zsympy.Symbolr   r   )*r  r  torch.utils._sympy.interpr  r  torch.utils._sympy.referencer  rD   r  proxyGraphAppendingTracerr  r}  r   r   r  r  r  r   rb  r  r  r  r  rq   r   ry   r   sympy.logic.boolalgr  r  r  r  rr   rv  rA  r   r3   	is_numberr  r  ro   )!rd   valuesr  r  r  r  rP  rR   r&  r  r  r  target_exprr  out_noder  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  s!   `              @@@@@@@@@@@@@@@@@@r:   materialize_symintszGraph.materialize_symints  s   \ 	NH	/	. 44T::< GINP	H, JJ 	ODww-'oc<088==D!$5$m:S.3hhnnT&n.Qd+U\\2"+CII"6 IQ%a60dCHI  99==)<=(0(8 OW&11#eGn7MNO	O" 	4	

	
 	  	D	B)	P )	P )	PV !# 	!A!U\\*As#

1GAw''(1%q2  &&++K$$

3q6""// & %&)+6Ffehhnn5 "&3+6(@
 K//:o?  

3v;'{{H(A&JJx =	!> 
r9   c                ,    | j                  |g      d   S )zDSingle-value convenience wrapper around :meth:`materialize_symints`.r   )r"  )rd   r   s     r:   materialize_symintzGraph.materialize_symint  s     ''033r9   c                    | S r=   r8   rL   s    r:   r   zGraph.<lambda>  s    PQ r9   c                   t        |j                  |      }t        |j                  |      }t        |t              st        dt        |             t        |t              st        dt        |             | j                  |j                  |j                  |||j                  |j                        }t        j                  |j                        |_        |S )aw  
        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``.
        zExpected args to be tuple, got z Expected kwargs to be dict, got )rv  r   r  r   r   ro   r   r  r  r}  r   r?   r  r  )rd   r  arg_transformr   r  result_nodes         r:   rw  zGraph.node_copy  s    2 tyy-0m4$& #B4:,!OPP&$' #CDL>!RSS&&GGT[[$		499
  99TYY/r9   c                .    | 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``.
        r+   )r}  r   r   r~  r  )rd   r  r~  s      r:   r+   zGraph.output 	  s'    , yI   
 	
r9   c                    t        |      r|j                  }n9t        |t              st	        dt        |             |}t        |      r|dd }t        |      }|S )NzExpected target to be str, got ri   )r  r3   r   r.   ro   r   rN   rS   )rd   r   r}  s      r:   r  zGraph._target_to_str:	  sY    FBfc*$'FtF|n%UVVB}"X_	r9   r+  c                  
 t               
d
fdt        d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.
        c                <    j                  | j                  |       S r=   )rw   r?   )rn  r<  s    r:   	node_reprz$Graph.python_code.<locals>.node_repr|	  s    ((33r9   c              3     K   i }| j                   D ]  }|j                  ||<   |_         	 d  | j                   D ]  }||   |_         y # | j                   D ]  }||   |_         w xY wwr=   )r  _repr_fn)r   orig_repr_fnsr  r.  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)rn  r   r   r.   )r   r#   r   Generator[None, None, None])r]   r
   _python_code)rd   r  r,  r-  r.  r/  r  r0  r1  r2  r<  r.  s             @@r:   python_codezGraph.python_codeF	  ss    ^ L		4 

	8 

	8  % 	$$--)' / % 
	 	 	s   AAc               `    | j                   j                  | j                  |||||||||	
      S )Nr+  )r^  r  r  )
rd   r  r<  r,  r-  r.  r/  r  r0  r1  s
             r:   r4  zGraph._python_code	  sB     }}--JJ))%#+ . 
 	
r9   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
        r   r  zgraph(r   r   r   r  )r  format_noder   )rd   placeholder_namesmaybe_return_typenamer  	node_strs	param_strrR   node_strs           r:   __str__zGraph.__str__	  s    
 (* -/4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)	r@  ImportErrorprintr  r}  r?   r   r   r  )rd   r@  rn  
node_specss       r:   print_tabularzGraph.print_tabular	  s    	) KO**UQqttQVVQXXqvvqxx@U
UZ)WX	
  	<
 	 Vs   A. A B.Bc                    dd fd}t               }t                j                  D ]  }|j                  t        vrt	        d| d|j                   d      |j
                   urt	        d| d      | j                  vrt	        d| d      |j                  D ]  } |||        j                  |       |j                  |v rt	        d	|j                   d      |j                  |j                           j                  r 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j+                  |d|       }
|	!t	        d| d|j                   d| d|
       |j                  dk(  rFt!        |	t        j,                  j.                        s"t	        d| d|j                   d| d|
 d	      |	}  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
        Nc                    |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   rn  context_strseen_valuesrd   s      r:   	check_argzGraph.lint.<locals>.check_arg	  s    01Jqc,sKyy$" Q{m 4UUYTZ\ 
 +%" Q{m 4``d_eg  &r9   zNode z had unknown opcode r  zNode 'z ' does not belong to this Graph!z ' is not added to the side tablezNode redefined name r&   z target z
 has type z but a Callable is expectedz but a str is expected)r(   r)   r   z" references nonexistent attribute z of r)   r  z  does not reference an nn.Moduler=   )r   r   rn  Node | Noner   r   )r`   r  r}  
_legal_opsr  r   r`  r  rs   r?   ra  r  r   r  rD   rI  r   r.   r   r  rU   r   rW   r  )rd   rK  
seen_namesr  r   target_atomsm_itrr  atom	new_m_itrseen_qualnamerJ  s   `          @r:   lintz
Graph.lint	  s   	  #u
!$JJ 	&Dwwj("U4&0DTWWIQ#OPPzz%"VD61Q#RSS4888"VD61Q#RSS(( %#t$%OOD!yyJ&"%9$))A#FGGNN499%	&  

 !*77o-#DKK0(#D6$++jX\XcXcIdHe f5 5 
 &dkk37(#D6$++jX\XcXcIdHe f0 0  7799#';;#4#4S#9L ..E#,\#: *4$+E4$>	(+bq1A(B$,"."'vXdkk]Bd#'&]O!=#   77m3J%uxx= #/"'vXdkk]!D6m_ ]= !=# 
 !*!*#!* r9   c                X  
 ddl m} | j                          d
t        j                  j
                  j                         r$t        j                  j                  j                  
d	
fd}t               }t        | j                        D ]P  } ||      rt        |j                        dk(  s%| j                  |       |j!                  |j"                         R t        |      dkD  }|rt$        j'                  d|       | j(                   |d | j+                  d      D              }| j(                  j-                         D ]\  \  }}	||v st/        |	t        j0                  j2                        s0||	j4                  j7                         z  }|	j9                          ^ |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.
        r   )
OrderedSetTc                :     |       S | j                        S r=   )	is_impure)r  impure_randomis_impure_nodes    r:   has_side_effectz2Graph.eliminate_dead_code.<locals>.has_side_effectb
  s#    )%d++>>-00r9   z1The following nodes were dead code eliminated: %sc              3  4   K   | ]  }|j                     y wr=   rQ  r  s     r:   r   z,Graph.eliminate_dead_code.<locals>.<genexpr>v
  s      ((s   r(   )r}  rT  )torch.utils._ordered_setrV  rT  rD   _guardsTracingContexttry_get	_inductorconfigfallback_randomr`   r  r  r   r~  r  rs   r?   r  infora  rS  named_childrenr   r  r%   r   eliminate_dead_code	recompile)rd   rZ  rV  r[  removed_nodesr  changedsubgraph_names
child_namechild_modulerY  s    `        @r:   rf  zGraph.eliminate_dead_code+
  se   Z 	8 			==''//1!OO22BBM	1 TZZ( 	-D"4(S_-A%!!$)),	-
 m$q(HHH-X )' ("&//Z/"@( N -1,>,>,M,M,O -(
L /J %(("6"65 |11EEGGG **,- r9   c                    || _         y r=   )r^  )rd   codegens     r:   set_codegenzGraph.set_codegen
  s	    r9   c                      j                   j                   |       j                   _        t        j                  d fd       } |       S )a-
  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r=   )r^  r   )on_gen_code_oldrd   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   r3  )r^  r   
contextlibr
   )rd   make_transformerrs  rr  s   `  @r:   on_generate_codezGraph.on_generate_code
  sK    R --99*:?*K'		"	"	B 
#	B 011r9   c                    t        | j                        D ]-  }|j                  j                          | j	                  |       / y r=   )r  r  r  clearr  rH  s     r:   _clear_nodeszGraph._clear_nodes
  s4    TZZ( 	"DIIOOOOD!	"r9   )NNN)ra  GraphModule | Nonerb  ztype[Tracer] | Nonerc  zdict[str, Any] | Noner   r   )r   rz  )rg  rz  r   r   )r   r   )r   r   )r}  r.   r   rU  rm  r  r   rV  )F)rx  r#   rt  zdict[Node, Node]ry  r  r   zArgument | Noner=   )r  zdict[int, Any] | Noner   r#   )NNNN)r}  r.   r   r   r   tuple[Argument, ...] | Noner  dict[str, Argument] | Noner?   
str | Noner~  
Any | Noner   r   r  r/  )r  r   r   r   )rn  rL  r   r   )r?   r.   r~  r~  r  r   r   r   )ri  r.   r~  r~  r   r   )
rY   r.   r   r{  r  r|  r~  r~  r   r   )
r  r.   r   r{  r  r|  r~  r~  r   r   )r  r  r   r{  r  r|  r~  r~  r?   r}  r   r   )r  r   r   ztuple[Any, str])r  r   rP  rr   r   r   )r  r   r   r   )r  r   r  ztuple[object, ...]r  z$Callable[[torch.SymInt], Node | int]r   r   )r  zSequence[torch.SymInt | int]r   zlist[Node | int])r   ztorch.SymInt | intr   r  )r  r   r'  zCallable[[Node], Argument]r   r   )r  r   r~  r~  )r   rU  r   r.   )r  r.   r,  r  r-  r  r.  r  r/  r  r  r  r0  r  r1  r  r   r!   )r  r.   r<  r]   r,  r  r-  r  r.  r  r/  r  r  r  r0  r  r1  r  r   r!   r   r~   )rZ  zCallable[[Node], bool] | Noner   r  )rn  r"   r   r   )ru  z7Callable[[TransformCodeFunc | None], TransformCodeFunc]r   z'contextlib.AbstractContextManager[None])0r3   r4   r5   r6   r   re   propertyra  setterr  rl  rS  r{  r  r  r%  r(  r  r  r  r
  r  r  r*   r(   r)   r'   r&   staticmethodr  r  r  r  r  r"  r$  rw  r+   r  r5  r4  r>  rF  rT  rf  ro  rv  ry  r8   r9   r:   r#   r#     s   -^ $/ -1*./3	@)@ (@ -	@
 
@ 0@* # # " "     %0 1 %0 37T"/>B	 12 $/NS!1GK	 08> $/
 -1-1 $LL L *	L
 +L L L 
L 0L\ %03 13 %02 12 $/&
 0&
P $/- 0-0 $/, 0,0 $/ !%$..44	UU U 	U
 
U 0U@ $/AQ 0AQF $/ -1-1 $2
2
 *2
 +	2

 2
 
2
 02
h $/ -1-1 $$
$
 *$
 +	$

 $
 
$
 0$
L $/ -1-1 $'
('
 *'
 +	'

 '
 '
 
'
 0'
R    %0 1 %0 1 %0 1 %0<< $< ;	<
 
< 1<| %0L2L	L 1L\ %04 14 $/FQ"")C"	" 0"H $/ 9=

+5
 0
0
 $/
 $$"!,0PP 	P
 P P P P P *P 
P 0Pn $$"!,0

 

 
 
 
 
 
 
 *
 

4$ $/
 0
* $/M* 0M*^ $/>BV;V	V 0Vp %0  1  %0R2QR2 
1R2 1R2h"r9   r#   c              #     K   t         j                  }	 | t         _        d  |t         _        y # |t         _        w xY wwr=   )r"   r   )overridetmps     r:   _override_sym_reprr  
  s3      

C $Cs   ?/ ?<?c                    | S r=   r8   rL   s    r:   r  r  
  s    Hr9   c                     d fd}|S )Nc                    d} |  | S )Nz[0mr8   )rR   resetr   s     r:   r  z_make_color_fn.<locals>.f
  s    s5'""r9   rR   r.   r   r.   r8   )r   r  s   ` r:   _make_color_fnr  
  s    # Hr9   z[33mz[36mz[32mz[34mz[31mz[2mz	[2m[34mz	[2m[32m)yellowcyangreenrR  rN  rP  rQ  rO  z# COUNTER: (\d+)z{} + {}z{} - {}z{} * {}z{} // {}z{} / {}z{} % {}z{} ** {}z{} << {}z{} >> {}z{} & {}z{} | {}z{} ^ {}z{}[{}]z{} @ {})rs   rm   mulr  truedivdivrg  powlshiftrshiftand_or_xorr  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)r?   r.   r/   r.   r1   r0   r   r   )rM   r.   r   r  r  )r1   r0   r   r  )ru   r.   r   r.   r   r.   r=   )r   r.   r   z&Callable[[str, str, str], bool] | Noner   z_ParsedStackTrace | None)r  r   r   r3  )rM   r.   r   r.   )r   r.   r   zCallable[[str], str])
__future__r   builtinsrt  r  r_  	functoolsr
  keywordloggingmathr  r  r   rA  rC  r  collectionsr   collections.abcr   r   r   r   r	   r
   dataclassesr   r   r   r   r   rD   torch.utils._pytreeutilsr   rG   torch._Cr   rv  r   torch._library.opaque_objectr   r   torch.typesr   torch.utils._dtype_abbrsr   r   rF   _compatibilityr   immutable_collectionsr   r  r   r   r   r   r   tensor_typer    	getLoggerr3   r  __all__r  _symbolic_tracer$   graph_moduler%   r!  Listr  Dictr`   Set	frozenset	FrozenSetr   TuplerF  fromkeysrM  r.   TransformCodeFuncr-   kwlistr0   r>   update__dict__r;   r7   r@   rA   rB   r   rE   rN   rS   partialr   rm   rP   rl   rj   	fullmatchrV   r[   r]   r!   r   r   r   r   r   r   r"   r  r  r4  rC  r#   r  r  r  _color_codesr   r  r  reflectable_magic_methodsr  r  )r  r  s   00r:   <module>r     s   "          	  	    # M M % ! : :  $ $ 6 R $ 0 " ) 1 I I # g!
, ') 	&++&++v	6<<  ]]X
 d3i[$s)34 Z  (/~~6!!VX+6   h'' (.0 + 0
  6 A  6 A %<d4j I .% 8 #=u|| L &Li X #I6 R3	& $)##JBJJ/C$D$H$H&Q !bjj!12  bjjBC #

3) 
N# N#b d+
   , . ."F F4%* % $T T T  KO!G2 e,c

 c

 -c

X'G 'TEVW EVP1I^ 1Ih!R !RH d+A" A" ,A"H.  4      !"	 0</A/A/CDtq!a""D
"**01  & 




   gV 7`U Es   O	.O