
    7h                        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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   \(       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K,J-r-J.r.  S SK/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<  \*Rz                  S\*R|                  S\*R~                  S\*R                  S\*R                  S\*R                  S0rCSqD  S{S jrES\R                  R                  4S jrH  S|S jrI    S}S  jrJS\R                  R                  S\K\L\4   4S! jrMS"\K\L\4   S#\R                  R                  SSSS4S$ jrNS#\R                  R                  4S% jrO S~S&\K\L\L4   S'\LS(\LS)\P4S* jjrQS+\6S\L4S, jrR SS-\\S\R                  4   S.\SS/\6S0\\S   SS4
S1 jjrUS2\V\R                  R                     SS4S3 jrX  SSSSSS4.S5\Y\   S6\\3   S7\\<   S8\\L   S9\\:   S:\\4   S;\PSS4S< jjjrZS=S>S?\R                  R                  S\P4S@ jr[S=S>S?\R                  R                  S\\R                  R                     4SA jr]S=S>S?\R                  R                  S\P4SB jr^S=S>S?\R                  R                  S\\R                     4SC jr`S=S>S?\R                  R                  S\P4SD jraS=S>S?\R                  R                  S\\R                     4SE jrbS#\R                  R                  SF\\R                  R                  /\\R                  R                  \P4   4   S\R                  R                  4SG jrcSH\V\R                  R                     S\V\R                  R                     4SI jrd\SJ 5       reS#\R                  R                  SS4SK jrfS#\R                  R                  4SL jrg SSH\V\R                  R                     S\\R                  R                     4SM jjrhSH\V\R                  R                     S\S4SN jriSH\V\R                  R                     S\V\R                  R                     4SO jrjSP\R                  R                  SQ\R                  R                  SS4SR jrkS#\R                  R                  S\R                  R                  SS4SS jrmST\R                  R                  S\\R                  R                     4SU jrnS\R                  R                  S\R                  4SV jrpSW rqS#\R                  R                  SS4SX jrrS#\R                  R                  SYSS\R                  R                  SZ\K\L\4   SS4
S[ jrsS\\KS]\PS\K4S^ jrtS#\R                  R                  S\R                  R                  R4                  4S_ jrw\S\R                  R                  4S` j5       rxSaSbS\P4Sc jrySaSbS\P4Sd jrzSaSbS\P4Se jr{SaSbS\P4Sf jr|SSg jr}Sh r~SSi jr\GR                   " SjSk9S\Sb   4Sl j5       rSm\GR                  GR                  S\Sb   4Sn jrS\Sb   4So jrSSp jr\Sq 5       rSr\S\R                  R                  S\K\L\\R                  \R                  R                  4   4   4Ss jrS5\Y\R                  R                     SS4St jrS5\Y\R                  R                     SS4Su jrSv rSw r " Sx Sy\R                  R                  5      rSz rg)    N)Iterable)contextmanager)ismethod	Parameter)AnyCallableOptionalTYPE_CHECKINGUnion)detect_fake_mode)
FakeTensorFakeTensorMode)FunctionalTensor)#first_call_function_nn_module_stack)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                M/var/www/fran/franai/venv/lib/python3.13/site-packages/torch/_export/utils.py_collect_and_set_constant_attrsrL   @   s     I$&N $///D99	((( 	15 	/  
 !()zz#D4&D  	$%E"5' ) #s   "C+C+C+rA   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.unflattenrN   rO   setgraphnodesoptorchfxgraph_module	_get_attrr7   
isinstanceTensor	_del_attrr5   r>   	recompile)rA   
state_dictrD   rN   rO   temp_registered_constantsnoder7   s           rK   _register_constants_as_buffersra   ^   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)
r3   r7   r   CONSTANT_TENSORr4   r6   output_specsr   BUFFER_MUTATIONRuntimeError)sigr_   rC   s      rK   7_override_graph_signature_for_temp_registered_constantsri   x   s     ;;33!11DI"DO  
   II33388DKK=(de  ! Jrb   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)r3   r4   r   r5   r6   r7   )old_sigrj   rC   rD   s       rK   /_overwrite_signature_for_non_persistent_buffersrm      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      $ )Nr1   )r9   r:   )ro   rp   prefixfieldtitems         rK   _getattr0_collect_param_buffer_metadata.<locals>._getattr   sD    "-D&A= =  q  rb   call_moduleTF)recurseremove_duplicater1   rP   call_functioncustom)rV   rW   GraphModulestrrS   rT   r7   metarU   rZ   nnModulenamed_parametersnamed_buffers_opsHigherOrderOperator_input_nodesproxy_COPY_META_FIELDS)rA   params_buffers_to_node_metarv   r`   r7   r   	submodulerE   _argentrys              rK   _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 '&rb   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<   rS   rT   rU   r7   inputs_to_parametersr8   r   inputs_to_buffers)	r   r   rj   metadatar`   
param_namekvbuffer_names	            rK   )_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 rb   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)
rS   rT   r   get_detect_fake_mode_from_gm	shape_envrZ   rV   SymIntr`   )r   r`   vals	fake_moder   s        rK   _get_shape_env_from_gmr      s     HHNN"D99==% 			%" 	  *"-I"""a&&66### s
   !B.B.name_map	orig_namerE   is_placeholderc                 n   X R                  5       ;   a  [        R                  " SU5      nU(       a2  U(       d+  UR                  S5      [	        UR                  S5      5      pROSnU SUS-    3=o`R                  5       ;   a$  US-  nU SUS-    3=o`R                  5       ;   a  M$  X`U'   X   $ X U'   X   $ )z
Renames nodes to avoid name collisions, with suffixing.
name_map: map from original name to new name
orig_name: mapping key
name: candidate name (potentially suffixed, e.g. mul_2)
is_placeholder: if the node is a placeholder, avoid detecting suffix
z
(.*)_(\d+)      r   r   )r   rematchgroupint)r   r   rE   r   r   ndup_names          rK   _rename_without_collisionsr      s        -kk!nc%++a.&9!A"V1QUG,,x1BBFA #V1QUG,,x1BB&  #rb   key_pathc                     U S   n[        U[        5      (       d   eUR                  S:X  a  S[        U SS 5       3$ U S   n[        U[        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   )rZ   r%   idxr#   r$   r~   )r   args_kwargs_key_path	kwarg_keyrE   s       rK   
get_keystrr     s     $A;*K88881$vhqrl+,--QK	)Z00009~a#x|,-..rb   symintr   keypathic                 j   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 X: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   rZ   rV   r   r`   expr	is_numbersympy@torch._export.passes.add_runtime_assertions_for_constraints_passr   torch.utils._sympy.solver   lenfree_symbolsnextitersubsr   rg   Symbolr   Eqmathinf)r   r   range_constraintsunification_mapr   r   r   r   r   r   symbolexisting_dimpathsolutionmin_valmax_vals                   rK   _check_symintr   /  s5    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 		'"=gaSN"D &6vhj N& &
 	
	 
rb   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   rg   zipr   r   rZ   r   rV   r[   r   typeshape	enumerater   r   floatr~   r   )r   flat_args_with_pathr   r   r   r   r   r`   node_valjarg_dimnode_dims               rK   "_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rb   )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: objr/   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fieldsrE   r:   append)r   	flattened
flat_names
none_namesfrE   r   r   s          rK   default_flatten_fn=register_dataclass_as_pytree_node.<locals>.default_flatten_fn  s}    	

##C(AVV 4#"4  %!!$'!!$' ) z222rb   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       rK   default_unflatten_fn?register_dataclass_as_pytree_node.<locals>.default_unflatten_fn  s1    !(
PT#j12PdmmJ6OPPrb   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         rK   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
   ``    `   rK   !register_dataclass_as_pytree_noder    s
    ##  G	@F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rb   programr   r`   c                 H    UR                   U R                  R                  ;   $ )zE
Checks if the given node is a parameter within the exported program
)rE   r?   r   r  r`   s     rK   is_paramr    s    
 99//DDDDrb   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  r?   r   rE   r^   )r  r`   parameter_names      rK   	get_paramr    s=      00EEdiiP!!.11rb   c                 H    UR                   U R                  R                  ;   $ )zB
Checks if the given node is a buffer within the exported program
)rE   r?   r   r  s     rK   	is_bufferr    s    
 99//AAAArb   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  r?   r   rE   rD   r@   r^   )r  r`   r   s      rK   
get_bufferr    s`     --??		J11HHH$$[11%%k22rb   c                 H    UR                   U R                  R                  ;   $ )zR
Checks if the given node is a lifted tensor constant within the exported program
)rE   r?   !inputs_to_lifted_tensor_constantsr  s     rK   is_lifted_tensor_constantr  #  s     99//QQQQrb   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  r?   r  rE   r@   )r  r`   lifted_tensor_names      rK   get_lifted_tensor_constantr"  .  sD     !//$44VVII
   !344rb   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  )r`   	split_maps    rK   <lambda>"sequential_split.<locals>.<lambda>U  s	    Yt_rb   T)keep_original_orderkeep_original_node_name)torch.fx.passes.split_moduler%  rS   rT   _codegenr]   )r   r#  r%  split_idr`   new_gmr'  s         @rK   sequential_splitr0  @  s     :IH$MH"	$ 
 

$  $F HH--FLL
Mrb   rT   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  rT   r#  r`   s      rK   nodes_filterr3  _  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    rK   $_disable_aten_to_metadata_assertionsr8  d  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      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   )dtypedevicelayoutargskwargs)(torch._export.passes._node_metadata_hookr;  r<  r6  rV   opsatentor?  r>  dtype_layoutrS   rT   r7   prev_assert_tensor_metadatadefaultrB  r   r   inserting_before	functoolspartialr{   r@  )r   r;  r<  aten_to_variantsr`   
tensor_vals         rK   $_insert_aten_to_metadata_assert_passrQ  o  s   
 '& 			  				&&
 ;;**		  EIINN$J$J$R$RRIIaLDIINN1$55 "iil//33E::
GXX..t46M%%+$(IIMM-$@7 HH**		>>FF"iil_%/%5%5&0&7&7&0&7&7  + 744 7 744s%   6I:A8I2I
II
I)	c           	         SSK JnJn  SSKJn  [
        R                  R                  R                  (       de  SnU" U [        R                  " X%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   r:  )_graph_output_nameszUFile "torch/fx/passes/runtime_assert.py", line 24, in insert_deferred_runtime_assertsr=  zexported program: T)export)rD  r;  r<  4torch._functorch._aot_autograd.input_output_analysisrS  rV   _dynamoconfigdo_not_emit_runtime_assertsrM  rN  r   r   r   rS   rQ  r]   user_outputs)r   r?   r;  r<  rS  r   r   s          rK   apply_runtime_assertion_passrZ    s     Y==;;1 	 %	!!"5O
 /r2I/()LRXX)V(WX	
 	-R0 LLN#6r#:O %
 
s   5B==
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r5  r  r`   s    rK   r(  nodes_first.<locals>.<lambda>  s    QUrb   r   N)r3  r   )rT   r#  rets      rK   nodes_firstr`    s,     unDU
VC
3x!|1vrb   c                 *    [        [        X5      5      $ )z:Returns the number of nodes that match the node_call_back.)r   r3  )rT   r#  s     rK   nodes_countrb    s    |E233rb   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  r2  s      rK   	nodes_maprd    s    
 t Lrb   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clearrS   
erase_node)re  rf  s     rK   node_replace_rl    s4     ""8,NNNNh'rb   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|   )rZ   rV   rW   r}   hasattrr   update)r   rA   s     rK   _update_gm_meta_if_possiblerp    s_    3,,--C   
#((8"456 ! ! 	.rb   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.
rx   Nc              3   H   #    U  H  oR                   S :X  d  M  Uv   M     g7f)r   NrU   .0r`   s     rK   	<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   outputNrt  ru  s     rK   rw  rx    s       +ww>W/W+ry  r{  rP   r   submod_r   c                 h    U R                   S:H  =(       a    U R                  [        R                  :H  $ )Nr{   )rU   r7   operatorgetitemr]  s    rK   r(  node_inline_.<locals>.<lambda>  s)    O!; "8x'7'77"8rb   c                 <   > [        U TU R                  S      5      $ Nr   )rl  rB  )get_item_node
new_outputs    rK   r(  r  %  s     -%"=#5#5a#89+rb   zUnsupported output type z2. Expect it to be a Node or a list/tuple of Nodes.) rU   rS   owning_modulerZ   r7   r~   r:   rT   r   rB  rV   rW   Noderl  rL  	node_copyrn  r=   r   ri  rj  r  r  r<   r3  keysrd  rk  NotImplementedErrorr   delete_all_unused_submodulesr]   )rq  r   sub_gmphsbodyr`   r{  phr   rf  new_target_namer   get_item_usersr  s                @rK   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   rB  self)
parameters)astparsecoder  r   POSITIONAL_OR_KEYWORDr8   r:   rB  r   r   inspect	Signature)
rA   ast_modast_func_defarg_type_map
param_listarg_type
param_typeaarg_name_listarg_names
             rK   &_get_torch_jit_trace_forward_signaturer  7  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)rZ   rV   jitScriptModuleTracedModuler  r   r  r  	signatureforwardbind_partial	arguments)rA   	fake_argsfake_kwargsrh   s       rK   _bind_signature_to_inputsr  P  s    #		..		0F0FGHH4S9 3>>"c)ns;7G&GG 	
J	
G
 , Ec	*44DDDrb   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[        UR                   R                  5       Ho  u  pU[        U5      :  a6  X   R                  XR                  '   X   R                  =Ul        Ul        MJ  [        XR                  UR                  5      Ul        Mq     [!        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)rS   rT   rU   rZ   r7   rV   r   r   _name_argsr   r:   r   r   rE   r   _name_hoo_subgraph_placeholdersr]   )r   subgraph_ph_tuplesr`   r   
true_graphfalse_graph	cond_argssubgraphr  
body_grapharrayrB  hoo_phsr   r   s                  rK   r  r  c  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#% !5!56GA3w<&-joo#*1*//9	DK6xDIIV	 7 	(1 0rb   export_graph_signaturer@   c           
      J  ^ 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
[        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[        X5       HO  u  u  nnnU(       d  M  [!        U
U["        [        R                     SR%                  U4S jU 5       5      -   SS9  MQ     UR                   H  nUR                  [        R                  :X  a  M#  UR                  [        R&                  :X  a  SnO U	" UR(                  5      R+                  5       n[,        R.                  " S	SU5      n[!        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
                   H5  nUR0                  S
:X  a  M  [!        XR                  UR                  5        M7     U R                  R
                   GH  nUR0                  S
:X  a  UR                  U
;   d   eXR                     =Ul        Ul        UR                  U;   aY  UR                  R3                  S5      c  XxR                     UR                  S'   O!UR                  S   XxR                     :X  d   e[        UR                  S   [4        5      (       a   UR                  UR                  S   l        M  M  UR                  U
;   d  GM   XR                     Ul        GM     [7        U 5        U R9                  5         UR                   H  nUR                  R                  U
;   d   eXR                  R                     UR                  l        UR                  [        R:                  :X  d  Mf  UR(                  U
;   d  Mx  XR(                     SS Ul        M     UR<                   H  nUR                  R                  U
;   a'  XR                  R                     UR                  l        UR                  [>        R@                  :X  d  Md  UR(                  U
;   d  Mv  XR(                     Ul        M     [C        URE                  5       5       H  nUU   nUU
;   d  M  [        U[        RF                  5      (       a  M1  U
U   nUU:w  d  M>  [,        RH                  " 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    rK   _strip_name,placeholder_naming_pass.<locals>._strip_name  sY    <<%%#l#%&A\\'""#g,.!AFF?C+rb   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 )rZ   r$   r   r  r~   keyr%   r   r!   rE   rg   r   r  s    rK   _extract_pytree_key4placeholder_naming_pass.<locals>._extract_pytree_key  s}    a$$SZ8AH;''quu::&&66M!4T!WI=NqcRSSrb   r   c              3   P   >#    U  H  nT" U5      R                  5       v   M     g 7fr   )lower)rv  r  r  s     rK   rw  *placeholder_naming_pass.<locals>.<genexpr>  s#     L8a.q177998s   #&T)r   r)   r  r   Nr      z
arg(\d+)_1)%rZ   rV   rW   r}   rS   rT   r   rE   r  r'   r3   r4   r   
USER_INPUTr   r   r   placeholder_prefixesjoinTOKENr7   r  r   r  rU   r   r   r  r]   
CUSTOM_OBJre   r   USER_INPUT_MUTATIONr  r  r[   r   )r   r  rA   r  r  fake_params_buffersr@   custom_metar`   r  r   combined_argsr   r   rC   user_input_namesarg_path_arguser_input_name	base_namerE   constantnew_namer  s                          @rK   placeholder_naming_passr    sq   6 #%K#uxx++,,IIOOD499$)-8)<II& $	T  "H .ckJM3MB +666D99	,,, 	6   .11D-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&) 34 77m#"8YY		B  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";;/3DK 3 '3388==H$$XX]]3DHHM99
6664;;(;R";;/DK	 4 Y^^%&T?8Jell%
 %
  ~HD HH]D11 4Y5I5I JT QQ&.	(#dO 'ss   &"V V 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   )r8   rn  delattrdetachclone)r^   r  r   r   new_state_dicts        rK   remove_proxy_from_state_dictr  /  s     $$&DAq'""
w/ ' $$&DAq'""$%HHJ$4$4$6!$%q!	 '
 rb   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)
rS   rT   rU   r   rZ   rV   r[   r   r   r   )r   	fake_inps	fake_valsr`   fake_vals        rK   r   r   D  s    %'I$&I77m#(:yy'H#
8U\\(J(J  * )K#^q tyy(ETYY,>H$))+99_5$))#99U+#
8U\\(J(J  *   I122rb   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_hooksrj  )rA   state_dict_hooksstate_dict_pre_hookss      rK   _disable_load_state_dict_hooksr  b  sn     ,01F1F,G04S5N5N0O!##%9 0$8! !1$8!s   AB"A3 &B3BBrU   r   c                    [         R                  R                  U R                  5       [         R                  R                  R
                  5      =(       d1    [         R                  R                  R
                  U R                  ;   $ r   )rV   _C%_dispatch_has_kernel_for_dispatch_keyrE   DispatchKeyCompositeImplicitAutograd
py_kernelsrt  s    rK   
_is_cia_opr  o  sX    66GGIuxx++EE	
 	K 8899R]]J	rb   c                 <    [        U 5      =(       a    [        U 5      $ r   )_check_valid_to_preserver  rt  s    rK   _is_preservable_cia_opr  x  s    #B':JrN:rb   c                 L    U R                  5       R                  S5      S   S:H  $ )N::r   rF  )rE   r9   rt  s    rK   _is_aten_opr  |  s!    779??4 #v--rb   c                 "    [        U 5      (       + $ r   )r  rt  s    rK   _is_custom_opr    s    2rb   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  r1   r   r   r   rK  N)rV   r  ,_dispatch_get_registrations_for_dispatch_keyr  r9   r   r:   rE  )cia_opsrU   	namespaceop_name
split_listop_overload_namer   s          rK   _materialize_cpp_cia_opsr    s    
 hhCC#G
 "288D>2	]]3'
:!#s:!';;;Q-$z?a)!}GGEIIy97CEUV rb   c                      [         $ )zU
This is an special marker that tells our infra that we shouldn't decompose this op.
)NotImplementedrA  s     rK   _special_op_to_preserve_ciar    s
     rb   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_fnsrn  r   r  r  
alias_info
is_mutablerV   r  _dispatch_has_kernelrE   )op_overloadr  r   r  is_mutating_or_aliasings        rK   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_namespacerV   rE  rF  r  rb   rK   -_collect_all_valid_cia_ops_for_aten_namespacer    s    3EIINNCCrb   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  rR   r:   	overloadsr  r>   )r  r  rU   	op_packetoverloadr  s         rK   r  r    sb      eGL-	!++-H!)6K%k22K( .  Nrb   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
rF  )rR   rV   rE  _dirrn  r:   rZ   r   _OpNamespacer  r  )r  op_namespace_namer  s      rK   _collect_all_valid_cia_opsr'    s     eG"YY^^&599&78888"599.?@L,

(?(?@@CLQQ A DFFG , Nrb   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)rV   r  r  r  r  rE   _op_dkAssertionError)rB  rC  r*  dks       rK   _special_op_to_decompose_cia9_get_decomp_for_cia.<locals>._special_op_to_decompose_cia  s    !8 XX!!;;8899KKM588//II
 
 ==5d5f55 F8#LM rb   )r*  )rV   r  r  r  r  rZ   rM  rN  )rU   r.  r/  s      rK   _get_decomp_for_ciar1    sj     
			7	7B	]]:bmmB.?AUAU#V#V}}R   9EErb   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r5  )rV   compiler_is_compiling_flag_is_exporting_flag)old_compiling_flagold_exporting_flags     rK   _compiling_state_contextr8    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)rz   T)static_shapes)r  r   r   r8   idfrom_tensor)r   rA   params_buffersfaked_params_buffersmemor  rF   fake_tensors           rK   _fakify_params_buffersrA    s    
s##U#;
<
s  % 8
9N
 "$D$**,
e9r%y/K#//T/JK)EO$/S! -  rb   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>.PrototypeModuleiW  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__rZ   rV   r   r   rn  rF  )r  mrB  rC  	__class__r   s       rK   rH  Fregister_module_as_pytree_input_node.<locals>.PrototypeModule.__init__X  sO    GQ000a1111t\2222!DOrb   c                 4    U R                   UR                   :H  $ r   rF  )r  others     rK   __eq__Dregister_module_as_pytree_input_node.<locals>.PrototypeModule.__eq__^  s    ??e&6&666rb   c                    > T" U " 5       5      $ r   r  )r  r?  PrototypeModules     rK   __deepcopy__Jregister_module_as_pytree_input_node.<locals>.PrototypeModule.__deepcopy__a  s    "46**rb   rM  )	__name__
__module____qualname____firstlineno__rH  rO  rS  __static_attributes____classcell__)rJ  rR  r   s   @rK   rR  rD  W  s    	"	7	+ 	+rb   rR  r   r/   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   r=  rR  s       rK   r   @register_module_as_pytree_input_node.<locals>.default_flatten_fnd  ss     4 4 67S..01>,>>N))+,$$&'C /
 
 	
rb   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 collectedrA   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__r8   named_childrenr=   )rA   r_  r   r   rE   childcopy_modules         rK   rc  Wregister_module_as_pytree_input_node.<locals>.default_unflatten_fn.<locals>.copy_moduley  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  )rv  r   os      rK   rw  Uregister_module_as_pytree_input_node.<locals>.default_unflatten_fn.<locals>.<genexpr>  s     =&<daqz&<s   T)tie_weightsstrict)
rg   rV   r   r   anyr   utils	stateless_reparametrize_moduler  )
r   r   r   refr   r   r   r_  rc  r   s
           @rK   r  Bregister_module_as_pytree_input_node.<locals>.default_unflatten_fnm  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   rB  r   r   r   s         rK   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   >r1   c                 T    U tp[         R                  " U/S /[        U5      -  Q5      $ r   )jsondumpsr   )r   r  r   s      rK   r   Aregister_module_as_pytree_input_node.<locals>.to_dumpable_context  s*    zz44D6CF?455rb   c                    > [         R                  " U 5      nT" [        R                  R	                  5       5      US'   U$ r  )rs  loadsrV   r   r   )dumpablesrR  s     rK   r   Cregister_module_as_pytree_input_node.<locals>.from_dumpable_context  s/    JJx uxx01!rb   r  c                 >   > T" U 5      u  p#X1R                   :X  d   eU$ r   )r   )r   rC   flatsr   r   s       rK   default_flatten_fn_specEregister_module_as_pytree_input_node.<locals>.default_flatten_fn_spec  s#    #C,,&&&rb   )
issubclassrV   r   r   weakrefrn  r   r  r  r   r   rV  rW  r   r   )r   r  r   r  r	  r   r   r   r   r}  rR  r   s   `         @@rK   $register_module_as_pytree_input_noder  3  s   @ c588??+++++ +'++ +
 
d3i.@(A 
Xc] W  8
# 
%S	78J2K 
 $J'L>>C/#2B2BB6
 19/3d3i 
 !rb   c                 0    [        U 5        [        U 5        g r   )r   r   )r   s    rK   &deregister_module_as_pytree_input_noder    s    C #C(rb   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 )Nr+  z to be a nn.Module)rZ   rV   r   r   _parametersr;   )srcdsts     rK   _sync_stater    s      + 
3%)*+    + 
3%)*+  ooCO<<CLrb   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_modulesrI  other_msother_ms       rK   
sync_stater    s%    
 -G#   rb   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   )rG  rH  r  __self__r  )r  methodrJ  s     rK   rH  _WrappedMethod.__init__  s!    FOOT*rb   )r  )rU  rV  rW  rX  rH  rY  rZ  )rJ  s   @rK   r  r    s     rb   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.
r+  z to be a method)r   r  )r  s    rK   wrap_methodr    s<       +	6(/*+  &!!rb   )r/   r   )rh   r   )rl   r   rj   r   )Fr   )NN)r/   N)r  r   )rU   r   )r  r_  r   rM  r  rs  r   r~  r   collections.abcr   
contextlibr   r   r   typingr   r   r	   r
   r   rV   torch._guardsr   torch._subclasses.fake_tensorr   r   #torch._subclasses.functional_tensorr   torch.fx._utilsr   torch.fx.passes.runtime_assertr   r2   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  	PARAMETERr5   rd   r  r  r  r6  rL   rW   r}   ra   ri   rm   r  r~   r   r   r   boolr   r   r   r   r   r  r  r   r   r  r  r   r  r  r[   r  r  r"  r0  r3  r8  rQ  rZ  r`  rb  rd  rl  r   rp  r  r  r  r  r  r  r  _subclassesr@  r   r  r  r  r  r  r  r  r  	lru_cacherR   r  r   r%  r  r'  r1  r8  rA  r  r  r  r  r  r  r  rb   rK   <module>r     s<   
        	 $ % ' @ @  * D @ ? J H',A Q Q   $ "dt&OOW  #( <%			%4	(#.D 6'(<(< 6'c3h 6'r)!%c3h)) $) 
	)8$uxx33 $& !	38n  	:/ /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 'TUXX%9%9 D 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&'(<(< ' 'T_$_$2_$ 
_$ CH~_$ 
_$DT T d *33
""11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 *}d588??.C } }@)UXX__0E )$ )
 "$UXX__ 	"rb   