
    9i                        S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J
r
  S SKJr  S SKJr  S SKJrJr  S SKJrJrJrJrJr  S SKrS SKJr  S SKJrJr  S S	KJr  S S
KJ r   S SK!J"r"  S SK#J$r$  \(       a  S SK%J&r&  S SK'J(r(  S SK)J*r*  S SK+J,r,  S SK+J-r-J.r.J/r/  S SK0J1r1J2r2  S SK3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>J?r?J@r@  \.R                  S\.R                  S\.R                  S\.R                  S\.R                  S\.R                  S0rGSqH  SS jrIS\R                  R                  4S jrL  SS  jrM    SS" jrNS\R                  R                  S\O\P\4   4S# jrQS$ rRS%\O\P\4   S&\R                  R                  S!SSS4S' jrSS&\R                  R                  4S( jrT SS)\O\P\P4   S*\O\P\U4   S+\V\P   S,\PS-\PS.\W4S/ jjrXS0\:S\P4S1 jrY SS2\\U\R                  4   S3\US4\:S5\\U   SS4
S6 jjr[S7\\\R                  R                     SS4S8 jr^  SSSSSS9.S:\_\   S;\\7   S<\\@   S=\\P   S>\\>   S?\\8   S@\WSS4SA jjjr`SBSCSD\R                  R                  S\W4SE jraSBSCSD\R                  R                  S\\R                  R                      4SF jrcSBSCSD\R                  R                  S\W4SG jrdSBSCSD\R                  R                  S\\R                     4SH jrfSBSCSD\R                  R                  S\W4SI jrgSBSCSD\R                  R                  S\\R                     4SJ jrhS&\R                  R                  SK\\R                  R                  /\\R                  R                  \W4   4   S\R                  R                  4SL jriSM\\\R                  R                     S\\\R                  R                     4SN jrj\SO 5       rkS&\R                  R                  SS4SP jrlS&\R                  R                  4SQ jrm SSM\\\R                  R                     S\\R                  R                     4SR jjrnSM\\\R                  R                     S\U4SS jroSM\\\R                  R                     S\\\R                  R                     4ST jrpSU\R                  R                  SV\R                  R                  SS4SW jrqS&\R                  R                  S\R                  R                  SS4SX jrsSY\R                  R                  S\\R                  R                     4SZ jrtS\R                  R                  S\R                  4S[ jrvS\ rwS] rxS&\R                  R                  SS4S^ jryS&\R                  R                  S_SS\R                  R                  S`\O\P\4   SS4
Sa jrzSb\OSc\WS\O4Sd jr{S&\R                  R                  S\\R                  R                  R8                     4Se jr~\S\R                  R                  4Sf j5       rSgShS\W4Si jrSgShS\W4Sj jrSgShS\W4Sk jrSgShS\W4Sl jrSSm jrSn rSSo jr\GR                  " SpSq9S\VSh   4Sr j5       rSs\GR                  GR                  S\VSh   4St jrS\VSh   4Su jrSSv jr\Sw 5       rSx\S\R                  R                  S\O\P\\R                  \R                  R                   4   4   4Sy jrS:\_\R                  R                     SS4Sz jrS:\_\R                  R                     SS4S{ jrS| rS} r " S~ S\R                  R                  5      rS rg)    N)defaultdict)Iterable)contextmanager)ismethod	Parameter)AnyCallableOptionalTYPE_CHECKINGUnion)detect_fake_mode)
FakeTensorFakeTensorMode)FunctionalTensor)#first_call_function_nn_module_stack)PreDispatchTorchFunctionMode)insert_deferred_runtime_assertsConstantAttrMap)OperatorBase)ExportedProgram)ExportGraphSignature)CustomObjArgument	InputKind
OutputKind)_deregister_pytree_flatten_specregister_pytree_flatten_spec)_deregister_pytree_node_register_pytree_nodeContextFlattenFuncFromDumpableContextFn
GetAttrKeyKeyPathkeystr
MappingKeySequenceKeyToDumpableContextFntree_flatten_with_pathUnflattenFunc p_b_c_obj_tokenFreturnc                    SSK Jn  U" 5       nU R                   Vs1 s HB  nUR                  [        R
                  :X  d  M#  UR                  (       a  M6  UR                  iMD     nnUR                  5        Hn  u  pxXv;   a  M  Un	UR                  S5      Gt pU
 H  n[        X5      n	M     U	R                  R                  US 5        [        XU5        UR                  X5        Mp     U$ s  snf )Nr   r   .)(torch._export.passes.lift_constants_passr   input_specskindr   BUFFER
persistenttargetitemssplitgetattr_bufferspopsetattradd)graph_signature	constantsmodr   constant_attrsspecnon_persistent_buffersnamevalue_modatomsattratoms                S/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/torch/_export/utils.py_collect_and_set_constant_attrsrN   B   s     I$&N $///D99	((( 	15 	/  
 !()zz#D4&D  	$%E"5' ) #s   "C+C+C+rC   c                 r   SSK JnJn  [        5       nU R                  R
                   H  nUR                  S:X  d  M  [        R                  R                  R                  XR                  5      n[        U[        R                  5      (       d  Mi  UR                  U;  d  M{  UR                  U;  d  M  [        R                  R                  R                  XR                  5        U" XpUR                  UR                  S5        UR!                  UR                  5        M     U R#                  5         U$ )Nr   )_assign_attr	_AttrKindget_attrF)torch.export.unflattenrP   rQ   setgraphnodesoptorchfxgraph_module	_get_attrr9   
isinstanceTensor	_del_attrr7   r@   	recompile)rC   
state_dictrF   rP   rQ   temp_registered_constantsnoder9   s           rM   _register_constants_as_buffersrc   `   s     ? #		77j XX**44S++FF&%,,// KKz1KK'==HH))33CE dkk9;K;KUS-11$++>   MMO$$    r   c                 @   U R                    H1  nUR                  U;   d  M  [        R                  Ul        S Ul        M3     U R                   HL  nUR                  [        R                  :X  d  M#  UR                  U;   d  M5  [        SUR                   S35      e   U $ )Nz	Constant z< is mutated in the forward method. Pls register it as buffer)
r5   r9   r   CONSTANT_TENSORr6   r8   output_specsr   BUFFER_MUTATIONRuntimeError)sigra   rE   s      rM   7_override_graph_signature_for_temp_registered_constantsrk   z   s     ;;33!11DI"DO  
   II33388DKK=(de  ! Jrd   new_sigc                 Z   U R                    Vs1 s HB  nUR                  [        R                  :X  d  M#  UR                  (       a  M6  UR
                  iMD     nnUR                    H<  nUR                  [        R                  :X  d  M#  UR
                  U;   d  M5  SUl        M>     U$ s  snf )NF)r5   r6   r   r7   r8   r9   )old_sigrl   rE   rF   s       rM   /_overwrite_signature_for_non_persistent_buffersro      s     '''D99	((( 	15 	'   ##99	(((T[[<R-R#DO $ Ns   "B(B(B(c                    0 nS[         R                  R                  S[        4S jnU R                  R
                   GH  nUR                  nUR                  nUR                  S:X  aw  U" X5      n[        U[         R                  R                  5      (       aF  UR                  SSS9 H  u  pxXQUS-   U-   '   M     UR                  SSS9 H  u  pxXQUS-   U-   '   M     UR                  S	:X  a5  U" X5      n[        U[         R                  R                  5      (       d  XQU'   UR                  S
:X  d  M  [        UR                  [         R                  R                  5      (       a  GM0  UR                    Hb  n	U	R                  S	:X  d  M  [         R                  R"                  R$                   H%  n
U
S:X  a  M  X;   d  M  XZ   XR                     U
'   M'     Md     GM     U$ )a  
Param/buffer metadata needs to be saved before lowering to aten IR
because aten IR lifts them, as a result, automatic preservation doesn't work.
This is intended to be called on the strict mode tracing right before lowering to
aten IR OR run_decomposition pass.
model	attr_namec                 v    UR                  S5      Gt p#U nU H  n[        XES 5      nUb  M   e   [        XC5      $ )Nr3   )r;   r<   )rq   rr   prefixfieldtitems         rM   _getattr0_collect_param_buffer_metadata.<locals>._getattr   sD    "-D&A= =  q  rd   call_moduleTF)recurseremove_duplicater3   rR   call_functioncustom)rX   rY   GraphModulestrrU   rV   r9   metarW   r\   nnModulenamed_parametersnamed_buffers_opsHigherOrderOperator_input_nodesproxy_COPY_META_FIELDS)rC   params_buffers_to_node_metarx   rb   r9   r   	submodulerG   _argentrys              rM   _collect_param_buffer_metadatar      s    #%!,, ! ! 		yy77m# -I)UXX__55(99 5  :  GD HLt0CD 
  )66 5  7  GD HLt0CD 
 77j  -Ii)=)=>>6:F3
 77o%jKK77/
 /
 ((66Z'!&!A!A H,$ =MQ[7

CEJ "B )7  H '&rd   c                  T   [         R                  R                  5       (       d  g [         R                  R	                  5       n U  Vs/ s H  n[        U[        5      (       d  M  UPM     nn[        U5      S::  d   S[        U5       35       e[        U5      S:X  a  g US   nU$ s  snf )N   z6Expected only one PreDispatchTorchFunctionMode, found r   )rX   _C_is_torch_function_mode_enabled	overrides _get_current_function_mode_stackr\   r   len)torch_function_mode_stackmodepre_dispatch_tf_modess      rM   +_maybe_find_pre_dispatch_tf_mode_for_exportr      s    883355 % P P R .-Dd89 	-   $%* 
@EZA[@\]*  !Q& #DKs   B%$B%r   gmc                 d   U R                  5        H'  nUR                  SS5        UR                  SS5        M)     UR                  R                   H  nUR                  S:X  d  M  UR
                  UR                  ;   aG  UR                  UR
                     nXP;   a)  X   R                  5        H  u  pgXtR                  U'   M     UR
                  UR                  ;   d  M  UR                  UR
                     nX;   d  M  X   R                  5        H  u  pgXtR                  U'   M     M     g)ze
Given that we collected param'buffer metadata before, we put them back in
newly traced graph module
nn_module_stackNstack_traceplaceholder)
valuesr>   rU   rV   rW   r9   inputs_to_parametersr:   r   inputs_to_buffers)	r   r   rl   metadatarb   
param_namekvbuffer_names	            rM   )_populate_param_buffer_metadata_to_new_gmr      s     0668&-]D) 9 77m#{{g:::$99$++F
< ; G M M O'(		! !P{{g777%77D= ; H N N P'(		! !Q rd   c                 f   U R                   R                   Vs/ s H1  nUR                  R                  SS 5      c  M"  UR                  S   PM3     nn[	        U 5      nUb  UR
                  $ U H:  n[        U[        R                  5      (       d  M$  UR                  R
                  s  $    g s  snf )Nval)
rU   rV   r   get_detect_fake_mode_from_gm	shape_envr\   rX   SymIntrb   )r   rb   vals	fake_moder   s        rM   _get_shape_env_from_gmr   
  s     HHNN"D99==% 			%" 	  *"-I"""a&&66### s
   !B.B.name_mapfind_available
used_names	orig_namerG   is_placeholderc                    [         R                  " SU5      nUnU(       a*  U(       d#  UR                  S5      UR                  S5      pUnUn
X;   a  U SX   S-    3n
[         R                  " SU
5      nU(       a?  UR                  S5      UR                  S5      p[        U	5      X   :  a  [        U	5      X'   XU'   UR	                  U
5        X   $ )aI  
Renames nodes to avoid name collisions, with suffixing.
name_map: map from original name to new name
find_available: map prefix to available suffix
used_names: cache of used names
orig_name: mapping key
name: candidate name (potentially suffixed, e.g. mul_2)
is_placeholder: if the node is a placeholder, avoid detecting suffix

(.*)_(\d+)r      r   )rematchgroupintr@   )r   r   r   r   rG   r   r   keyrt   nnew_names              rM   _rename_without_collisionsr     s    " HH]D)E
C^KKNEKKNHU!N/!345HH]H-EKKNEKKNq6N**%(VN""YNN8rd   key_pathc                     U S   n[        U[        5      (       d   eUR                  S:X  a  S[        U SS 5       3$ U S   n[        U[        [
        45      (       d   e[        U5      SS nU [        U SS 5       3$ )z}For a given index into the flat_args, return a human readable string
describing how to access it, e.g. "*args["foo"][0].bar"
r   z*argsr   Nr   )r\   r'   idxr%   r#   r&   r   )r   args_kwargs_key_path	kwarg_keyrG   s       rM   
get_keystrr   A  s     $A;*K88881$vhqrl+,--QK	)j*%=>>>>9~a#x|,-..rd   symintr   keypathic                 ~   SSK Jn  [        U[        R                  5      (       a%  UR
                  R                  R                  (       a  [        X5      (       a  g SS KnSSK	J
n  SSKJn	  [        U [        R                  5      (       Ga2  [        U R
                  R                  R                  5      S:X  Ga  [        [!        U R
                  R                  R                  5      5      n
X;   aV  U R
                  R                  R#                  U5      nX:w  a+  [%        U5      nUb	  USU S3-  n['        SU S	U S
U 35      eO[        U R
                  R                  UR(                  5      (       a  [+        U5      X:'   OU	" UR-                  U R
                  R                  U5      U
5      nUcC  [%        U5      nUb	  USU S3-  n['        SU SU SU R
                  R                   SU
 S3	5      e[+        US   5      X:'   U R
                  R                  U;   a  U" X R
                  R                     5      u  pUS:  a0  X:  a+  [%        U5      nUb	  USU S3-  n['        SU SU S
U 35      eU[.        R0                  :  a1  X:  a+  [%        U5      nUb	  USU S3-  n['        SU SU S
U 35      eg g g [        U [        R                  5      (       a&  U R
                  R                  R                  (       d  g U[+        U 5      :w  a,  [%        U5      nUb	  USU S3-  n['        SU S	U  S
U S35      eg )Nr   )_IntWrapper)_convert_range_to_int)	try_solver   z.shape[]Expected input at  to be equal to 
, but got zExpected input z = z to be of the form z, where z is an integerr   z
 to be >= z
 to be <= zt. If you meant for this dimension to be dynamic, please re-export and specify dynamic_shapes (e.g. with Dim.DYNAMIC))torch.export.dynamic_shapesr   r\   rX   r   rb   expr	is_numbersympy@torch._export.passes.add_runtime_assertions_for_constraints_passr   torch.utils._sympy.solver   r   free_symbolsnextitersubsr   ri   Symbolr   Eqmathinf)r   r   range_constraintsunification_mapr   r   r   r   r   r   symbolexisting_dimpathsolutionmin_valmax_vals                   rM   _check_symintr   S  s<    8 	3%%''c''
 	 3&%,,''C0@0@0M0M,NRS,Sd6;;++889:$!;;++00AL"!'*=gaSN*D"(.>|nJWZV[\ 	 # &++**ELL99
 +.c('$UXXfkk.>.>%DfM#%g.D}'!A.&)$s3% 8''-{{'7'7&8X 
 /2(1+.>O+;;004!++"2"23 G {=%g.D}'!A.&,TF*WIZPSuU  !=%g.D}'!A.&,TF*WIZPSuU 	 ! " 1* 
FELL	)	)&++2B2B2L2L 		F	'"=gaSN"D &6vhj N& &
 	
	 
rd   input_placeholdersc           
         SS K n[        U5      [        U 5      :w  a$  [        S[        U 5       S[        U5       S35      e0 n[        X5       GH  u  u  pVnUR                  R                  S5      n[        U[        5      (       a  [        U[        R                  5      (       d#  [        S[        U5       S[        U5       35      e[        UR                  5      [        UR                  5      :w  a2  [        S[        U5       S	UR                   SUR                   S35      e[        [        UR                  UR                  5      5       H  u  n	u  p[        XX$XY5        M     GM  [        U[        [         ["        45      (       a=  [        U5      [        U5      :w  d  Xh:w  a  [        S[        U5       S
U SU 35      eGM{  [        U[        R$                  5      (       d  GM  [        XX$US 5        GM     g )Nr   z&Unexpected number of inputs (expected z, got )r   r   z to be a tensor, but got z,Unexpected number of dimensions in input at z.shape (expected r   r   )r   r   ri   zipr   r   r\   r   rX   r]   r   typeshape	enumerater   r   floatr   r   )r   flat_args_with_pathr   r   r   r   r   rb   node_valjarg_dimnode_dims               rM   "_check_input_constraints_for_graphr     s    
3'9#::/01<O8P7QQRT
 	
 02O!$%8!M99=='h
++c5<<00"(H)=(>>WX\]`XaWbc  8>>"c#))n4"B:hCWBX Y!!) 0syykD 
 +4C		8>>4R*S&&G'88 +T
 3s"344CyDN*co"(H)=(>>NxjXbcfbgh  /> %,,//08T3 "Nrd   )serialized_type_nameto_dumpable_contextfrom_dumpable_contextreturn_none_fieldscls
flatten_fnunflatten_fnr   r   r   r   c          
        ^ ^^ [         R                  " T 5      (       d
   ST  35       eS[        S[        [        [           [
        4   4U4S jjnS[        [           S[
        S[        4U 4S jjnS[        S[        [        [           [
        4   4U4S jjn	Tb  TOUmUb  UOUnUS L US L -  (       a  [        S	T  S
35      e[        T TUUU	UUS9  g )Nz7Only dataclasses can be registered with this function: objr1   c                   > / n/ n/ n[         R                  " U 5       Hb  nUR                  [        XR                  5      peUc  T(       a$  UR	                  U5        UR	                  U5        MQ  UR	                  U5        Md     XU/4$ N)dataclassesfieldsrG   r<   append)r  	flattened
flat_names
none_namesfrG   r   r   s          rM   default_flatten_fn=register_dataclass_as_pytree_node.<locals>.default_flatten_fn  s}    	

##C(AVV 4#"4  %!!$'!!$' ) z222rd   r   contextc           
      j   > Uu  p#T" S0 [        [        X 5      5      D[         R                  U5      D6$ )N )dictr   fromkeys)r   r  r	  r
  r   s       rM   default_unflatten_fn?register_dataclass_as_pytree_node.<locals>.default_unflatten_fn  s1    !(
PT#j12PdmmJ6OPPrd   c                    > T" U 5      u  nu  p#[        X!5       VVs/ s H  u  pE[        U5      U4PM     snnU4$ s  snnf r  r   r&   )r  r  r	  _none_namesr   r   r   s         rM   default_flatten_fn_with_keysGregister_dataclass_as_pytree_node.<locals>.default_flatten_fn_with_keys  sC    /9#,	,J/2:/IJ/ItqA"/IJJVVJs   <z7Both to_dumpable_context and from_dumpable_context for z must be None or registered.r   flatten_with_keys_fnr   r   )	r  is_dataclassr   tuplelistr    r   
ValueErrorr   )
r   r   r   r   r   r   r   r  r  r  s
   ``    `   rM   !register_dataclass_as_pytree_noder     s    ##C(( 
A#G(3 3d3i.@(A 3QXc] QW Q QW# W%S	78J2K W  *5;MJ#/#;<AULt#(=(EFEcU K% %
 	

 19/3rd   programr   rb   c                 H    UR                   U R                  R                  ;   $ )zE
Checks if the given node is a parameter within the exported program
)rG   rA   r   r!  rb   s     rM   is_paramr$    s    
 99//DDDDrd   c                     [        X5      (       a2  U R                  R                  UR                     nU R                  U   $ g)z
Returns the parameter associated with the given node in the exported program.
Returns None if the node is not a parameter within the exported program
N)r$  rA   r   rG   r`   )r!  rb   parameter_names      rM   	get_paramr'    s=      00EEdiiP!!.11rd   c                 H    UR                   U R                  R                  ;   $ )zB
Checks if the given node is a buffer within the exported program
)rG   rA   r   r#  s     rM   	is_bufferr)  ,  s    
 99//AAAArd   c                     [        X5      (       aZ  U R                  R                  UR                     nX R                  R                  ;   a  U R
                  U   $ U R                  U   $ g)z
Returns the buffer associated with the given node in the exported program.
Returns None if the node is not a buffer within the exported program
N)r)  rA   r   rG   rF   rB   r`   )r!  rb   r   s      rM   
get_bufferr+  4  s`     --??		J11HHH$$[11%%k22rd   c                 H    UR                   U R                  R                  ;   $ )zR
Checks if the given node is a lifted tensor constant within the exported program
)rG   rA   !inputs_to_lifted_tensor_constantsr#  s     rM   is_lifted_tensor_constantr.  G  s     99//QQQQrd   c                     [        X5      (       a2  U R                  R                  UR                     nU R                  U   $ g)z
Returns the lifted tensor constant associated with the given node in the exported program.
Returns None if the node is not a lifted tensor constant within the exported program
N)r.  rA   r-  rG   rB   )r!  rb   lifted_tensor_names      rM   get_lifted_tensor_constantr1  R  sD     !//$44VVII
   !344rd   node_call_backc                 
  ^ SSK Jn  0 mSnU R                  R                   H  nU" U5      (       a  US-  nUTU'   M     U" U U U4S jSSS9nU R                  R                  UR                  l        UR                  5         U$ )a+  
sequential_split creates a new graph module that splits the input graph module into multiple submodules
based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return
True if the node is a delimiter.  Delimiter will be the first node in the next submodule.
r   )split_moduler   c                    > TU    $ r  r  )rb   	split_maps    rM   <lambda>"sequential_split.<locals>.<lambda>y  s	    Yt_rd   T)keep_original_orderkeep_original_node_name)torch.fx.passes.split_moduler4  rU   rV   _codegenr_   )r   r2  r4  split_idrb   new_gmr6  s         @rM   sequential_splitr?  d  s     :IH$MH"	$ 
 

$  $F HH--FLL
Mrd   rV   c                 N    U  Vs/ s H  o!" U5      (       d  M  UPM     sn$ s  snf )z:Returns the nodes that match the node_call_back as a list.r  rV   r2  rb   s      rM   nodes_filterrB    s!    ";UTnT&:DU;;;s   ""c               #   8   #    [         n Sq  S v   U q g ! U q f = f7fNT)_DISABLE_ATEN_TO_ASSERTION_PASS)orig_vals    rM   $_disable_aten_to_metadata_assertionsrG    s&      /H&*#3*2'('s   	 c                    SSK JnJn  [        (       a  g [        R
                  R                  R                  R                  [        R
                  R                  R                  R                  [        R
                  R                  R                  R                  /nU R                  R                   GH  nUR                  U;   d  M  UR                  R                  [        R
                  R                  R                  R                   :X  a,  UR"                  S   UR                  R"                  S   :X  a  M  UR"                  S   R$                  R'                  S5      =nc  M  U R                  R)                  U5         U" U [*        R,                  " UUR$                  R'                  S5      UR$                  R'                  S5      S.S95         U R                  R/                  [        R
                  R                  R                  R                   UR"                  S   4UR                  UR                  UR0                  S.S	9  S S S 5        S S S 5        GM     g ! , (       d  f       N= f! , (       d  f       GM  = f)
Nr   _node_metadata_hook_set_node_metadata_hookr   r   r   )r   r   r   )dtypedevicelayoutargskwargs)(torch._export.passes._node_metadata_hookrJ  rK  rE  rX   opsatentorN  rM  dtype_layoutrU   rV   r9   prev_assert_tensor_metadatadefaultrQ  r   r   inserting_before	functoolspartialr}   rO  )r   rJ  rK  aten_to_variantsrb   
tensor_vals         rM   $_insert_aten_to_metadata_assert_passr`    s   
 '& 			  				&&
 ;;**		  EIINN$J$J$R$RRIIaLDIINN1$55 "iil//33E::
GHH--d3+!))//3yy}}]/K3799==AR3S&	 HH**		>>FF"iil_%/%5%5&0&7&7&0&7&7  + 	 43 	 	 43s&   AI5A8I$I5$
I2.I55
J	c           	         SSK JnJn  SSKJn  [
        R                  R                  R                  (       dh  SnU" U [        R                  " USU0S95         [        U 5      nU(       a"  [        U US[        U R                  5       3SS	9  S S S 5        [        U 5        U R!                  5         U" U 5      Ul        X4$ ! , (       d  f       N9= f)
Nr   rI  )_graph_output_nameszUFile "torch/fx/passes/runtime_assert.py", line 24, in insert_deferred_runtime_assertsr   rL  zexported program: T)export)rS  rJ  rK  4torch._functorch._aot_autograd.input_output_analysisrb  rX   _dynamoconfigdo_not_emit_runtime_assertsr\  r]  r   r   r   rU   r`  r_   user_outputs)r   rA   rJ  rK  rb  r   r   s          rM   apply_runtime_assertion_passri    s     Y==;;1 	 %#}k.J
 /r2I/()LRXX)V(WX	
  	-R0 LLN#6r#:O +
 
s   5C  
Cc                 V    [        X(       a  UOS 5      n[        U5      S:  a  US   $ g)z
Returns the first node that matches the node_call_back. If no node matches, returns None.
When node_call_back is None, returns the first node in the node list.
c                     grD  r  rb   s    rM   r7  nodes_first.<locals>.<lambda>  s    QUrd   r   N)rB  r   )rV   r2  rets      rM   nodes_firstro    s,     unDU
VC
3x!|1vrd   c                 *    [        [        X5      5      $ )z:Returns the number of nodes that match the node_call_back.)r   rB  )rV   r2  s     rM   nodes_countrq    s    |E233rd   c                 (    U  H  nU" U5        M     U $ )z
Sequentially visit the nodes list and invoke node_call_back on each element.
Returns the nodes list after the node_call_back is invoked on each element.
r  rA  s      rM   	nodes_maprs    s    
 t Lrd   old_nodenew_nodec                     U R                  U5        U R                  R                  5         U R                  R	                  U 5        g)z-
Replace all uses of old_node with new_node.
N)replace_all_uses_withusersclearrU   
erase_node)rt  ru  s     rM   node_replace_r{    s4     ""8,NNNNh'rd   c                     [        U[        R                  R                  5      (       aN  [	        US5      (       a<  SUR
                  ;   a+  U R
                  R                  SUR
                  S   05        g g g g )Nr   r~   )r\   rX   rY   r   hasattrr   update)r   rC   s     rM   _update_gm_meta_if_possibler    s_    3,,--C   
#((8"456 ! ! 	.rd   call_mod_nodec           
      b  ^ U R                   S:X  d   eU R                  R                  nUc   e[        U R                  [
        5      (       d   e[        XR                  5      nS UR                  R                   5       nS UR                  R                   5       nUR                  R                   Vs/ s H  oUR                   S:X  d  M  UPM     nn[        X0R                  5       H;  u  px[        U[        R                  R                  5      (       d   e[        Xx5        M=     UR                  R                  U 5         U H  nUR                  R                  U5      n	UR                   S:X  a~  U	R                  n
[!        X5      (       a3  SnSU 3n
[!        X5      (       a  US-  nSU 3n
[!        X5      (       a  M  Xl        [#        XR                  [        X%R                  5      5        [        XY5        M     [%        U5      S	:  GaC  [%        U5      S:X  a  [%        US	   R                  5      S:X  d   eUS	   R                  S	   m[        T[        R                  R                  5      (       a'  TR&                  R)                  5         [        U T5        O[        T[*        [,        45      (       a  T H!  nUR&                  R/                  US	   5        M#     [1        [+        U R&                  R3                  5       5      S
 5      n[5        UU4S j5        U R                  R7                  U 5        O3[9        S[;        T5       S35      eU R                  R7                  U 5        SSS5        UR=                  5         UR?                  5         U$ s  snf ! , (       d  f       N5= f)z
Inline the submodule of the given node into the parent module.
Note: we only support the case where submodule takes tensors inputs.
rz   Nc              3   H   #    U  H  oR                   S :X  d  M  Uv   M     g7f)r   NrW   .0rb   s     rM   	<genexpr>node_inline_.<locals>.<genexpr>!  s     
K.D'']2J44.   "	"c              3   H   #    U  H  oR                   S ;  d  M  Uv   M     g7f))r   outputNr  r  s     rM   r  r  "  s       +ww>W/W+r  r  rR   r   submod_r   c                 h    U R                   S:H  =(       a    U R                  [        R                  :H  $ )Nr}   )rW   r9   operatorgetitemrl  s    rM   r7  node_inline_.<locals>.<lambda>L  s)    O!; "8x'7'77"8rd   c                 <   > [        U TU R                  S      5      $ Nr   )r{  rQ  )get_item_node
new_outputs    rM   r7  r  R  s     -%"=#5#5a#89+rd   zUnsupported output type z2. Expect it to be a Node or a list/tuple of Nodes.) rW   rU   owning_moduler\   r9   r   r<   rV   r   rQ  rX   rY   Noder{  r[  	node_copyr}  r?   r   rx  ry  r  r  r>   rB  keysrs  rz  NotImplementedErrorr   delete_all_unused_submodulesr_   )r  r   sub_gmphsbodyrb   r  phr   ru  new_target_namer   get_item_usersr  s                @rM   node_inline_r    s   
 },,,				*	*B>>m**C0000R--.F
KFLL..
KC++D  &||11I1tWW5Hd1FIs../#uxx}}----b 0 
	"	"=	1Dxx))$/Hww*$"*//2//A(/smO!"66Q,3A3- ""66 #2OOWV[[-IJ$)  v;?v;!#F1INN(;q(@@@*J*ehhmm44   &&(mZ8Ju66&DJJNN6!9- ' ".,,11348" " ##..}=).tJ/?.@@rs  **=9e 
2h ##%LLNIy J 
2	1s    7NNA>N F,N  
N.c                    [         R                  " U R                  5      nUR                  S   nS[        R
                  0n/ nUR                  5        Hj  u  pV[        UR                  U5       Vs/ s H  owR                  PM     nnU H0  n	U	S:X  a  M  UR                  [        R                  " X5      5        M2     Ml     [        R                  " US9$ s  snf )z
Get source code and parse argument names using AST. The function returns
a signature of the forward() function.

# TODO: Directly provide inspect.signature compatible TS-d module.
r   rQ  self)
parameters)astparsecoder  r   POSITIONAL_OR_KEYWORDr:   r<   rQ  r   r  inspect	Signature)
rC   ast_modast_func_defarg_type_map
param_listarg_type
param_typeaarg_name_listarg_names
             rM   &_get_torch_jit_trace_forward_signaturer  d  s     ii!G$+LLOL I;;<L J , 2 2 4(/0A0A8(LM(L1(LM%H6!g//EF & !5 
33 Ns   1Cc                    [        U [        R                  R                  [        R                  R                  45      (       aA  [        U 5      n[        UR                  5      [        U5      [        U5      -   :X  d   S5       eO [        R                  " U R                  5      n0 UR                  " U6 R                  EUE$ )NzyArguments other than POSITIONAL_OR_KEYWORD kinds in forward() are not supported in _get_torch_jit_trace_forward_signature)r\   rX   jitScriptModuleTracedModuler  r   r  r  	signatureforwardbind_partial	arguments)rC   	fake_argsfake_kwargsrj   s       rM   _bind_signature_to_inputsr  }  s    #		..		0F0FGHH4S9 3>>"c)ns;7G&GG 	
J	
G
 , Ec	*44DDDrd   c                     UR                  U 5        [        R                  " SU 5      nU(       aA  UR                  S5      UR                  S5      pT[	        U5      X   :  a  [	        U5      X'   g g g )Nr   r   r   )r@   r   r   r   r   )rG   r   r   r   rt   r   s         rM   _build_cacher    s]    NN4HH]D)EKKNEKKNq6N**%(VN" + rd   c           	         / nU R                   R                   GHv  nUR                  S:X  d  M  [        UR                  [
        R                  R                  5      (       d  MK  UR                  R                  S:X  a]  UR                  u  p4pVUR                  [        XR                  5      U45        UR                  [        XR                  5      U45        M  UR                  R                  S:X  aF  UR                  S   UR                  SS pUR                  [        XR                  5      U45        GM"  UR                  R                  S:X  d  GM?  UR                  u  pnUR                  [        X	R                  5      X-   45        GMy     U H  u  p|0 n[        [        5      n[        5       n[        UR                   R                  5       H  u  nnU[!        U5      :  aN  UU   R"                  XR"                  '   UU   R"                  =Ul        Ul        [%        UR"                  X5        Mc  ['        XXR"                  UR"                  5      Ul        M     [)        U5        UR+                  5         M     g)a  
Propagate placeholder names from the top-level graph into HigherOrderOp subgraphs,
and handle collisions with non-placeholders by count suffixing.
Different HOO subgraph types have different input schemas, so we first enumerate them
and gather the top-level named placeholder nodes.
r}   condwrap_with_set_grad_enabledr   r   Nmap_impl)rU   rV   rW   r\   r9   rX   r   r   _name_argsr  r<   r   r   rT   r   r   rG   r  r   _name_hoo_subgraph_placeholdersr_   )r   subgraph_ph_tuplesrb   r   
true_graphfalse_graph	cond_argssubgraphr  
body_grapharrayrQ  hoo_phsr   r   r   r   s                    rM   r  r    s    RT77o%*KK77+
 +
 {{  F*8<

5{"))727H7H+I9*UV"))727I7I+JI*VW""&BB $

1tzz!"~#"))72+G*MN""j0*.**'
4"))R!2!23U\B & 0#%)4S)9"u
 !5!56GAt3w<&-ajoo#*1!*//9	DKTYYC6j))TYY	 7 	(1! 0rd   export_graph_signaturerB   c                   ^ 0 n[        U[        R                  R                  5      (       aJ  UR                  R
                   H0  nSUR                  ;   d  M  UR                  S   XxR                  '   M2     S n	S m0 n
[        [        5      n[        5       n[        X#U5      n[        U5      u  pUR                   Vs/ s H9  nUR                  [        R                   :X  d  M#  UR"                  R                  PM;     nn[%        UU5       HQ  u  u  nnnU(       d  M  ['        U
UUU[(        [        R                      SR+                  U4S jU 5       5      -   SS9  MS     UR                   H  nUR                  [        R                   :X  a  M#  UR                  [        R,                  :X  a  SnO U	" UR.                  5      R1                  5       n[2        R4                  " S	SU5      n['        U
UUUR"                  R                  [(        UR                     U-   SS9  UU;   d  M  UU   XzUR"                  R                     '   UU	 M     U R                  R
                   H6  nUR6                  S
:X  a  M  ['        XXR                  UR                  5        M8     U R                  R
                   GH  nUR6                  S
:X  a  UR                  U
;   d   eXR                     =Ul        Ul        UR                  U;   aY  UR                  R9                  S5      c  XxR                     UR                  S'   O!UR                  S   XxR                     :X  d   e[        UR                  S   [:        5      (       a   UR                  UR                  S   l        M  M  UR                  U
;   d  GM   XR                     Ul        GM     [=        U 5        U R?                  5         UR                   H  nUR"                  R                  U
;   d   eU
UR"                  R                     UR"                  l        UR                  [        R@                  :X  d  Mg  UR.                  U
;   d  My  U
UR.                     SS Ul        M     URB                   H  nUR"                  R                  U
;   a(  U
UR"                  R                     UR"                  l        UR                  [D        RF                  :X  d  Me  UR.                  U
;   d  Mw  U
UR.                     Ul        M     [I        URK                  5       5       H  nUU   nUU
;   d  M  [        U[        RL                  5      (       a  M1  U
U   nUU:w  d  M>  [2        RN                  " SU5      (       d  M\  U[(        [        R@                     U-   :w  d  M|  UUU'   UU	 M     gs  snf )a  
This pass is run at the end of _export_non_strict() to assign better placeholder node names:
    - User inputs:
        These follow the signature of mod.forward(), e.g. forward(x, y) produces nodes x, y.
        For nested inputs from dictionaries, lists, tuples, or dataclasses,
        the names are a concatenation of the path to the tensor.
            e.g. x = {
                'a': torch.randn(),
                'b': [torch.randn(), torch.randn()]
            }
        produces nodes x_a, x_b_0, x_b_1.
    - Parameters/buffers/constants/custom objects:
        These follow the FQN of the object, prefixed by "p", "b", "c", "obj" respectively.
            e.g. self.bar.l0.weight produces "p_bar_l0_weight".
    - Effect tokens:
        These are named token, token_1, ...
r~   c                     U R                  S5      (       a  U [        S5      S  n O$U R                  S5      (       a  U [        S5      S  n [        R                  " SSU 5      n U $ )N
L__self___self_[^a-zA-Z0-9]r   )
startswithr   r   subxs    rM   _strip_name,placeholder_naming_pass.<locals>._strip_name  sY    <<%%#l#%&A\\'""#g,.!AFF?C+rd   c                 P   [        U [        5      (       a-  [        R                  " SS[	        U R
                  5      5      n U $ [        U [        5      (       a  [	        U R                  5      $ [        U [        5      (       a  U R                  $ [        S[        U 5       SU  35      e)Nr  r   zPytree key of type z not handled for )r\   r&   r   r  r   r   r'   r   r#   rG   ri   r   r  s    rM   _extract_pytree_key4placeholder_naming_pass.<locals>._extract_pytree_key  s}    a$$SZ8AH;''quu::&&66M!4T!WI=NqcRSSrd   r   c              3   P   >#    U  H  nT" U5      R                  5       v   M     g 7fr  )lower)r  r  r  s     rM   r  *placeholder_naming_pass.<locals>.<genexpr>  s#     L8a.q177998s   #&T)r   r+   r  r   Nr      z
arg(\d+)_1)(r\   rX   rY   r   rU   rV   r   rG   r   r   rT   r  r)   r5   r6   r   
USER_INPUTr   r   r   placeholder_prefixesjoinTOKENr9   r  r   r  rW   r   r   r  r_   
CUSTOM_OBJrg   r   USER_INPUT_MUTATIONr  r  r]   r   )r   r  rC   r  r  fake_params_buffersrB   custom_metarb   r  r   r   r   combined_argsr   r   rE   user_input_namesarg_path_arguser_input_name	base_namerG   constantr   r  s                            @rM   placeholder_naming_passr    s   6 #%K#uxx++,,IIOOD499$)-8)<II& $	T  "H%0%5N5J .ckJM3MB +666D99	,,, 	6   .11DFV-W)4/?&$Y%9%9:((L8LLM# .X '2299	,,,99	'I#DKK0668IFF?C;	"HHMM +i7	
 # 4?y3IK/0I&- 38 77m#"j))TYY	
  77m#99(((&.yy&99DIyyK'99==*2*5ii*@DIIh'99X.+ii2HHHH $))E*,=>>(,				% % ?YY(" +DI " $B' LLN '22xx}}((( /II---$++2I"4;;/3DK 3 '3388==H$$TXX]]3DHHM99
6664;;(;R"4;;/DK	 4 Y^^%&T?8Jell%
 %
  ~HD HH]D11 4Y5I5I JT QQ&.	(#dO 's   ?"W%Wr`   in_placec                 0   U(       a<  U R                  5        H&  u  p#[        US5      (       d  M  [        X   S5        M(     U $ 0 nU R                  5        H<  u  p#[        US5      (       a"  UR                  5       R	                  5       XB'   M8  X4U'   M>     U$ )z
If `in_place` is false, return a new copy of `state_dict` with "proxy" removed from `v.__dict__`.
`v` is the values in the dictionary.
If `in_place` is true, modify `state_dict` in place.
r   )r:   r}  delattrdetachclone)r`   r  r   r   new_state_dicts        rM   remove_proxy_from_state_dictr  s  s     $$&DAq'""
w/ ' $$&DAq'""$%HHJ$4$4$6!$%q!	 '
 rd   c                    / n/ nU R                   R                   GH  nUR                  S:X  aX  SUR                  ;   aH  UR                  S   nUb4  [	        U[
        R                  5      (       a  UR                  U5        Mh  Mj  Ml  [        U5      S:X  d  M}  SUR                  ;   d  SUR                  ;   d  M  SnSUR                  ;   a  UR                  S   nOSUR                  ;   a  UR                  S   nUc  M  [	        U[
        R                  5      (       d  GM  UR                  U5        GM     [        X-   5      $ )a  
For a given graph module, we look at the "val" of placeholder nodes to find the fake inputs.
Additionally, if gm doesn't have placeholders, we further look at the "example_value" or "val" of other nodes.
If no fake mode is found, we return None for fake_mode.
r   r   Nr   example_value)
rU   rV   rW   r   r\   rX   r]   r  r   r   )r   	fake_inps	fake_valsrb   fake_vals        rM   r   r     s    %'I$&I77m#(:yy'H#
8U\\(J(J  * )K#^q tyy(ETYY,>H$))+99_5$))#99U+#
8U\\(J(J  *   I122rd   c              #     #    [        U R                  5      n[        U R                  5      nU R                  R                  5         U R                  R                  5          S v   Xl        X l        g ! Xl        X l        f = f7fr  )r  _state_dict_hooks_state_dict_pre_hooksry  )rC   state_dict_hooksstate_dict_pre_hookss      rM   _disable_load_state_dict_hooksr    sn     ,01F1F,G04S5N5N0O!##%9 0$8! !1$8!s   AB"A3 &B3BBrW   r   c                    [         R                  R                  U R                  5       [         R                  R                  R
                  5      =(       d1    [         R                  R                  R
                  U R                  ;   $ r  )rX   r   %_dispatch_has_kernel_for_dispatch_keyrG   DispatchKeyCompositeImplicitAutograd
py_kernelsr  s    rM   
_is_cia_opr
    sX    66GGIuxx++EE	
 	K 8899R]]J	rd   c                 <    [        U 5      =(       a    [        U 5      $ r  )_check_valid_to_preserver
  r  s    rM   _is_preservable_cia_opr    s    #B':JrN:rd   c                 L    U R                  5       R                  S5      S   S:H  $ )N::r   rU  )rG   r;   r  s    rM   _is_aten_opr    s!    779??4 #v--rd   c                 "    [        U 5      (       + $ r  )r  r  s    rM   _is_custom_opr    s    2rd   c            	         [         R                  R                  S5      n U  H  n[        UR	                  S5      5      u  p#UR	                  S5      n[        U5      S:X  d  [        U5      S:X  d   eUS   nSn[        U5      S:X  a  US   n[        [        [        [         R                  U5      U5      U5      nM     g)	zu
Utility function to query C++ dispatcher to get the all
possible CIA ops and populate them into torch.ops namespace
r  r  r3   r   r   r   rZ  N)rX   r   ,_dispatch_get_registrations_for_dispatch_keyr  r;   r   r<   rT  )cia_opsrW   	namespaceop_name
split_listop_overload_namer   s          rM   _materialize_cpp_cia_opsr    s    
 hhCC#G
 "288D>2	]]3'
:!#s:!';;;Q-$z?a)!}GGEIIy97CEUV rd   c                      [         $ )zU
This is an special marker that tells our infra that we shouldn't decompose this op.
)NotImplementedrP  s     rM   _special_op_to_preserve_ciar    s
     rd   c                    SSK Jn  U" U 5      (       a  gU [        R                  ;   a  g[	        U S5      (       d  g[        U R                  R                   Vs/ s H  o"R                  c  M  UPM     sn5      nUS:g  =(       d    U R                  R                  nU(       a  g[        R                  R                  U R                  5       5      (       d  ggs  snf )Nr   )#_should_decompose_because_unsafe_opF_schemaT)torch._decompr  r   metadata_fnsr}  r   r   r  
alias_info
is_mutablerX   r   _dispatch_has_kernelrG   )op_overloadr  r   r#  is_mutating_or_aliasings        rM   r  r    s    A*;77&333;	**''11N1q\\1NJ )AoO1D1D1O1O88(()9)9);<< 	Os   C-Cr   )maxsizec                  H    [        [        R                  R                  5      $ r  )(_collect_all_valid_cia_ops_for_namespacerX   rT  rU  r  rd   rM   -_collect_all_valid_cia_ops_for_aten_namespacer+    s    3EIINNCCrd   op_namespacec                     [        5         [        5       nU  HS  n[        X5      nUR                  5        H1  n[        X45      n[	        U5      (       d  M   UR                  U5        M3     MU     U$ r  )r  rT   r<   	overloadsr  r@   )r,  r  rW   	op_packetoverloadr&  s         rM   r*  r*    sb      eGL-	!++-H!)6K%k22K( .  Nrd   c                  n   [        5       n [        R                  R                   H  nUS:w  av  [	        [        R                  U5      (       d   e[        [        R                  U5      n[        U[        R                  R                  5      (       a  U [        U5      -  n M}  M  U [        5       -  n M     U $ )a  
This is an util function that gets the all CIA functional ops.

The algorithm is in 2 steps:
  1. We first query C++ dispatcher to get the list of CIA ops
     and then we call getattr on torch.ops.aten to lazily populate
     them.

  2. Sometimes, handful of ops have CIA registered in python dispatcher
     but not on the C++ side, these can't be caught at the first step.
     So we walk again to get the final list.

Note that the output of this function should never be modified
rU  )rT   rX   rT  _dirr}  r<   r\   r   _OpNamespacer*  r+  )r  op_namespace_namer,  s      rM   _collect_all_valid_cia_opsr5    s     eG"YY^^&599&78888"599.?@L,

(?(?@@CLQQ A DFFG , Nrd   c                     [         R                  R                  R                  nXR                  ;   aE  [        U R                  U   [         R                  R                  5      (       d  U R                  U   $ S n[        R                  " X S9$ )Nc                  N   US   nUS	 [         R                  R                  R                  n[         R                  R	                  UR                  5       [         R                  R                  R                  5      (       a  UR                  " U/U Q70 UD6$ [        SU S35      e)Nkernel	Expected z) to have CompositeImplicitAutograd kernel)rX   r   r  r  r  rG   _op_dkAssertionError)rQ  rR  r8  dks       rM   _special_op_to_decompose_cia9_get_decomp_for_cia.<locals>._special_op_to_decompose_ciaC  s    !8 XX!!;;8899KKM588//II
 
 ==5d5f55 F8#LM rd   )r8  )rX   r   r  r  r	  r\   r\  r]  )rW   r<  r=  s      rM   _get_decomp_for_ciar?  8  sj     
			7	7B	]]:bmmB.?AUAU#V#V}}R   9EErd   c               #     #    [         R                  R                  n [         R                  R                  n S[         R                  l        S[         R                  l        S v   U [         R                  l        U[         R                  l        g ! U [         R                  l        U[         R                  l        f = f7frD  )rX   compiler_is_compiling_flag_is_exporting_flag)old_compiling_flagold_exporting_flags     rM   _compiling_state_contextrF  U  sx     ::::?,0),0),>),>) -?),>)s   5C .B &+C ,B==C r   c                 "   0 [        UR                  SS95      E[        UR                  SS95      En0 n0 nUR                  5        HD  u  pV[	        U5      U;   a  U[	        U5         nOU R                  USS9nXt[	        U5      '   XsU'   MF     U$ )NF)r|   T)static_shapes)r  r   r   r:   idfrom_tensor)r   rC   params_buffersfaked_params_buffersmemor   rH   fake_tensors           rM   _fakify_params_buffersrO  b  s    
s##U#;
<
s  % 8
9N
 "$D$**,
e9r%y/K#//T/JK)EO$/S! -  rd   c           
      .  ^ ^
^ [        T [        R                  R                  5      (       d   eSSKn " U
U 4S jSUR
                  5      m
S[        S[        [        [           [        4   4U
4S jjnS[        [           S	[        S[        4U4S
 jjnS[        S[        [        [           [        4   4U4S jjnUmUnT R                  S-   T R                  -   nS nU
4S jn[        T TUUUUUS9  S[        [           4U4S jjn	[        T U	5        g)a  
Registers a module as a valid input type for :func:`torch.export.export`.

Args:
    mod: the module instance
    serialized_type_name: The serialized name for the module. This is
    required if you want to serialize the pytree TreeSpec containing this
    module.

Example::

    import torch


    class Module(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.linear = torch.nn.Linear(3, 3)

        def forward(self, x):
            return self.linear(x)


    torch._export.utils.register_module_as_pytree_node(InputDataClass)


    class Mod(torch.nn.Module):
        def forward(self, x, m):
            return m(x) + x


    ep = torch.export.export(Mod(), (torch.randn(3), Module()))
    print(ep)

r   Nc                   >   >^  \ rS rSrU U4S jrS rU4S jrSrU =r$ )=register_module_as_pytree_input_node.<locals>.PrototypeModulei  c                    > [         TU ]  " U/UQ70 UD6  [        U[        R                  R
                  5      (       d   e[        U S5      (       a   eTU l        g )N
_proto_cls)super__init__r\   rX   r   r   r}  rT  )r  mrQ  rR  	__class__r   s       rM   rV  Fregister_module_as_pytree_input_node.<locals>.PrototypeModule.__init__  sO    GQ000a1111t\2222!DOrd   c                 4    U R                   UR                   :H  $ r  rT  )r  others     rM   __eq__Dregister_module_as_pytree_input_node.<locals>.PrototypeModule.__eq__  s    ??e&6&666rd   c                    > T" U " 5       5      $ r  r  )r  rM  PrototypeModules     rM   __deepcopy__Jregister_module_as_pytree_input_node.<locals>.PrototypeModule.__deepcopy__  s    "46**rd   r[  )	__name__
__module____qualname____firstlineno__rV  r]  ra  __static_attributes____classcell__)rX  r`  r   s   @rM   r`  rR    s    	"	7	+ 	+rd   r`  r  r1   c                    > [        U R                  5       5      n[        U R                  5       5      n0 UEUEn[        UR	                  5       5      [        UR                  5       5      T" U 5      /4$ r  )r  r   r   r  r   r  )r  r   r   rK  r`  s       rM   r  @register_module_as_pytree_input_node.<locals>.default_flatten_fn  ss     4 4 67S..01>,>>N))+,$$&'C /
 
 	
rd   r   r  c           	        >^ Uu  p#Ub  U" 5       c  [        S5      eU" 5       nT	c   eT	" U5      u  pVS[        R                  R                  4U4S jjm[	        S [        X5       5       5      (       aY  [        R                  R                  R                  R                  U[        [        X 5      5      SSS9   T" U5      nS S S 5        U$ UnU$ ! , (       d  f       W$ = f)Nz!Module has been garbage collectedrC   c                 P  > [         R                   " U 5      nU R                  R                  5        VVs0 s H0  u  p#[         R                   " U5      [         R                   " U5      _M2     snnUl        UR                  5        H  u  pE[	        XT" U5      5        M     U$ s  snnf r  )copy__dict__r:   named_childrenr?   )rC   rn  r   r   rG   childcopy_modules         rM   rq  Wregister_module_as_pytree_input_node.<locals>.default_unflatten_fn.<locals>.copy_module  s{    ))C.CCF<<CUCUCWXCW41DIIaL$))A,6CWXCL"113;u#56  4J Ys   7B"c              3   ,   #    U  H
  u  pXLv   M     g 7fr  r  )r  r   os      rM   r  Uregister_module_as_pytree_input_node.<locals>.default_unflatten_fn.<locals>.<genexpr>  s     =&<daqz&<s   T)tie_weightsstrict)
ri   rX   r   r   anyr   utils	stateless_reparametrize_moduler  )
r   r  r	  refr  r  r   rn  rq  r   s
           @rM   r  Bregister_module_as_pytree_input_node.<locals>.default_unflatten_fn  s    !
;#%-BCCe%%%!#		UXX__ 	 =c&&<===))??T#j12T @  "#& 
 C
  
s   ;	C
C!c                    > T" U 5      u  ntp#[        X!5       VVs/ s H  u  pE[        U5      U4PM     snnU/UQ4$ s  snnf r  r  )r  r  r	  rQ  r   r   r   s         rM   r  Jregister_module_as_pytree_input_node.<locals>.default_flatten_fn_with_keys  sW    )3C&	&J/2:/IJ/ItqA"/IJM
M
 
 	
Js   >r3   c                 T    U tp[         R                  " U/S /[        U5      -  Q5      $ r  )jsondumpsr   )r  r  r   s      rM   r   Aregister_module_as_pytree_input_node.<locals>.to_dumpable_context  s*    zz44D6CF?455rd   c                    > [         R                  " U 5      nT" [        R                  R	                  5       5      US'   U$ r  )r  loadsrX   r   r   )dumpablesr`  s     rM   r   Cregister_module_as_pytree_input_node.<locals>.from_dumpable_context  s/    JJx uxx01!rd   r  c                 >   > T" U 5      u  p#X1R                   :X  d   eU$ r  )r  )r  rE   flatsr  r   s       rM   default_flatten_fn_specEregister_module_as_pytree_input_node.<locals>.default_flatten_fn_spec  s#    #C,,&&&rd   )
issubclassrX   r   r   weakrefr|  r   r  r  r    r   rd  re  r   r   )r   r  r  r  r  r   r   r   r   r  r`  r   s   `         @@rM   $register_module_as_pytree_input_noder  w  s   H c588??+++++ +'++ +
 
d3i.@(A 
Xc] W  8
# 
%S	78J2K 
 $J'L>>C/#2B2BB6
 19/3d3i 
 !rd   c                 0    [        U 5        [        U 5        g r  )r   r   )r   s    rM   &deregister_module_as_pytree_input_noder    s    C #C(rd   c                    [        U [        R                  R                  5      (       d   SU  S35       e[        U[        R                  R                  5      (       d   SU S35       eU R                  Ul        U R
                  Ul        g )Nr9  z to be a nn.Module)r\   rX   r   r   _parametersr=   )srcdsts     rM   _sync_stater     s      + 
3%)*+    + 
3%)*+  ooCO<<CLrd   c                  B    U (       a  U tpU H  n[        X5        M     gg)z
Sync state between exported modules corresponding to wrapped methods.
This might be necessary after serializing/deserializing due to copying.
N)r  )wrapped_method_modulesrW  other_msother_ms       rM   
sync_stater    s%    
 -G#   rd   c                   (   ^  \ rS rSrU 4S jrSrU =r$ )_WrappedMethodi  c                 Z   > [         TU ]  5         [        UR                  U 5        Xl        g r  )rU  rV  r  __self__r  )r  methodrX  s     rM   rV  _WrappedMethod.__init__  s!    FOOT*rd   )r  )rc  rd  re  rf  rV  rg  rh  )rX  s   @rM   r  r    s     rd   r  c                 N    [        U 5      (       d   SU  S35       e[        U 5      $ )z
Wrap a method as a module so that it can be exported.
The wrapped module's forward points to the method, and
the method's original module state is shared.
r9  z to be a method)r   r  )r  s    rM   wrap_methodr  %  s<       +	6(/*+  &!!rd   )r1   r   )rj   r   )rn   r   rl   r   )Fr  )NN)r1   N)r&  r   )rW   r   )r  rm  r  r\  r  r  r   r  r   collectionsr   collections.abcr   
contextlibr   r   r   typingr   r	   r
   r   r   rX   torch._guardsr   torch._subclasses.fake_tensorr   r   #torch._subclasses.functional_tensorr   torch.fx._utilsr   "torch.fx.experimental.proxy_tensorr   torch.fx.passes.runtime_assertr   r4   r   
torch._opsr   torch.exportr   torch.export.graph_signaturer   r   r   r   torch.fx._pytreer   r   torch.utils._pytreer   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r  	PARAMETERr7   rf   r  r  r  rE  rN   rY   r   rc   rk   ro   r  r   r   r   r   r   r   rT   boolr   r   r   r   r  r  r   r   r   r$  r   r'  r)  r]   r+  r.  r1  r?  rB  rG  r`  ri  ro  rq  rs  r{  r   r  r  r  r  r  r  r  r  r  _subclassesrN  r   r  r
  r  r  r  r  r  r  	lru_cacher+  r   r3  r*  r5  r?  rF  rO  r  r  r  r  r  r  r  rd   rM   <module>r     sr   
        	 # $ % ' @ @  * D @ ? K J H',A Q Q   $ "dt&OOW  #( <%			%4	(#.D 6'(<(< 6'c3h 6'r.)!%c3h)) $) 
	)8$uxx33 $* !%38n%cN% C% 	%
 % %P/ /S /0 [
#u||#$[
	[

 [
 }[
 
[
|)UXX]]+)	)\ )-,04
 +/9==A$4	c4%4 =)4
 #3-4 ""564 $$9:4 4 
4nE' Euxx}} E E
((-- ehh  ! B( B B$ B
((-- ell&RR
((--R 
R
((-- ell$ehhmm_eEHHMM44G.HHI XX><UXX]]+ <UXX]]@S <
 3 3-UXX-A-A -d -`!UXX%9%9 !J 04

ehhmm
4tEHHMM* 4s 4
T%((--( T%((--=P (EHHMM (UXX]] (t (7EHH$8$8 7uxx 7SW 7L L(588;O;O2P L^4 4GDUDU 42E&,-(<(< - -`g$g$2g$ 
g$ CH~g$ 
g$TT T d *33e++::;3< 	9 	9 	9> d ;~ ;$ ;.N .t .n  W.4 QDs>7J D  D**))"C$7 8F: 	? 	?  	  
#uU\\588#5#556
67 *Ad588??.C A AH)UXX__0E )$ )
 "$UXX__ 	"rd   