
    N jb3                   X   % S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	r	S SK
r
S SKr
S SKrS SKrS SKJrJr  S SKJr  S SKJrJr  S SKJrJr  S SKrS SKrS SKrS SKJr  S SKJs  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-J.r.  S SK/J0r0  S SK1J2r2  S SK3J4r4J5r5  S SK6J7r7  S SK8J9r9  S SK:J;r;  S SK<J=r=J>r>  S SK?J@r@JArA  S SKBJCrCJDrDJErEJFrFJGrGJHrH  S SKIJJrJ  S SKKJLrL  S SKMJNrN  SS
KOJ*r*  SSKPJQrQ  SSKRJSrSJTrTJUrUJVrV  SSKWJXrX  SSKYJZrZJ[r[J\r\  SSK]J^r^  SSK_J`r`  SSKaJbrbJcrcJdrdJereJfrf  SS KgJhrhJiriJjrj  \(       a  S SKkrlS SKmrm\*R                  roS!\pS"'   \R                  " \r5      rsS#\pS$'   \R                  R                  ru\R                  R                  rv\ " S% S&5      5       rw\ " S' S(5      5       rx\ " S) S*5      5       rySoS+ jrzSpS, jr{SpS- jr|SqS. jr} " S/ S05      r~SoS1 jr\~" 5       rSrS2 jrSsS3 jr      StS4 jr  Su             SvS5 jjrSoS6 jrSoS7 jrSoS8 jrSoS9 jrSoS: jrSoS; jrSoS< jrSoS= jr      SwS> jrSxS? jr    SyS@ jr   Sz           S{SA jjr                S|SB jrS}SC jrS~SD jrSSE jrSSF jrSSG jrSSH jrSSI jr        SSJ jr S         SSK jjrSSL.           SSM jjrSSSN.           SSO jjr\" SP5      rSSQ jrSqSR jrSSS jr\GRD                  SST j5       r      SSU jrSSV jr                  SSW jr          SSX jrSSY jrSSZ jrSS[ jrSoS\ jr      SS] jr S         SS^ jjr    SS_ jrSS` jr    SSa jrSSb jrSSc jr              SSd jrS SeKJr  SSf jrSSg jr S       SSh jjr      SSi jr      SSj jr        SSk jr SSSl.           SSm jjjr     S               SSn jjrg)    )annotationsN)defaultdictdeque)Callable)	dataclassreplace)AnyTYPE_CHECKING)countersis_node_meta_valid)(create_structured_trace_for_min_cut_info)is_with_effects)config)CustomKnapsackSolverCustomRuntimeEstimator)FakeScriptObject)
is_builtin)
LazyStringtrace_structured)	trace_log)extract_tensor_metadata)BackwardState)is_sym_nodepy_sym_types)magic_methodsmethod_to_operator)find_symbol_binding_fx_nodesfree_symbolsis_symbol_binding_fx_node	size_hintstatically_known_falsestatically_known_true)graph_drawer)
OrderedSet)CheckpointPolicy   )GraphInfoProvider)dp_knapsackdp_knapsack_sliding_hirschberggreedy_knapsackilp_knapsack)KnapsackEvaluator)	AOTOutputSavedForBackwardsAOTOutput#SavedForBackwardsNoVcCheckAOTOutput)_is_functional_graph)get_aot_graph_name)_is_bwd_seed_offset_is_fwd_seed_offset
_is_primal_is_tangentget_cuda_generator_meta_val)fx_graph_cseget_aten_targetraise_getitemsboolAOT_PARTITIONER_DEBUGzlogging.Loggerlogc                  ~    \ rS rSr% SrS\S'   S\S'   S\S'   S\S'   S\S'   SS	 jrSS
 jrSS jrSS jr	SS jr
Srg)OpTypes]   z8Class for keeping track of different operator categorieszOrderedSet[Callable[..., Any]]fusible_opscompute_intensive_ops
random_opsview_opsrecomputable_opsc                2    [        U5      U R                  ;   $ N)r8   r@   selfnodes     n/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/torch/_functorch/partitioners.py
is_fusibleOpTypes.is_fusibleg   s    t$(8(888    c                2    [        U5      U R                  ;   $ rF   )r8   rA   rG   s     rJ   is_compute_intensiveOpTypes.is_compute_intensivej   s    t$(B(BBBrM   c                2    [        U5      U R                  ;   $ rF   )r8   rB   rG   s     rJ   	is_randomOpTypes.is_randomm   s    t$77rM   c                2    [        U5      U R                  ;   $ rF   )r8   rC   rG   s     rJ   is_viewOpTypes.is_viewp   s    t$55rM   c                2    [        U5      U R                  ;   $ rF   )r8   rD   rG   s     rJ   is_recomputableOpTypes.is_recomputables   s    t$(=(===rM    NrI   fx.Nodereturnr:   )__name__
__module____qualname____firstlineno____doc____annotations__rK   rO   rR   rU   rX   __static_attributes__rZ   rM   rJ   r>   r>   ]   s=    B//99..,,449C86>rM   r>   c                      \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S'   S	\S
'   S\S'   \R                  SS j5       rSS jrSS jr	SS jr
SS jrSrg)NodeInfow   list[fx.Node]inputsOrderedSet[fx.Node]_required_fw_nodesrequired_bw_nodestangents_closureunclaimed_nodesdict[fx.Node, int]fw_orderstatic_lifetime_input_nodesc                B   ^  [        S T R                   5       U 4S jS9$ )Nc              3  $   #    U  H  ov   M     g 7frF   rZ   .0ns     rJ   	<genexpr>-NodeInfo.required_fw_nodes.<locals>.<genexpr>   s     0/1Q/s   c                "   > TR                   U    $ rF   )rp   )rv   rH   s    rJ   <lambda>,NodeInfo.required_fw_nodes.<locals>.<lambda>   s    a@PrM   key)sortedrk   rH   s   `rJ   required_fw_nodesNodeInfo.required_fw_nodes   s!    0//06P
 	
rM   c                    XR                   ;   $ rF   )rk   rH   rv   s     rJ   is_required_fwNodeInfo.is_required_fw   s    ++++rM   c                    XR                   ;   $ rF   )rl   r   s     rJ   is_required_bwNodeInfo.is_required_bw   s    ****rM   c                    XR                   ;   $ rF   )rn   r   s     rJ   is_unclaimedNodeInfo.is_unclaimed   s    ((((rM   c                \    XR                   ;  a  [        SU S35      eU R                  U   $ )NNode z not in fw nodes!)rk   AssertionErrorrp   r   s     rJ   get_fw_orderNodeInfo.get_fw_order   s2    +++ 5+<!=>>}}QrM   rZ   N)r]   rh   )rv   r\   r]   r:   )rv   r\   r]   int)r^   r_   r`   ra   rc   	functoolscached_propertyr   r   r   r   r   rd   rZ   rM   rJ   rf   rf   w   sZ     ++**))((  !44
 

,+) rM   rf   c                  H    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S'   Srg	)
MinCutOptions   r:   ban_if_used_far_apartban_if_long_fusible_chainsban_if_materialized_backwardban_if_not_in_allowlistban_if_reductionrZ   N)r^   r_   r`   ra   rc   rd   rZ   rM   rJ   r   r      s      $$"&&!!rM   r   c                |    U R                   R                  SS 5      [        R                  [        R                  4;   $ )N	recompute)metagetr%   MUST_RECOMPUTEPREFER_RECOMPUTErI   s    rJ   must_recomputer      s5    99==d+''))0  rM   c                b    U R                   R                   H  n[        U5      (       d  M    g   g)NTF)graphnodesr   fx_grI   s     rJ   has_recomputable_opsr      s)    

  $ ! rM   c                   U R                   R                   Hf  n[        U5      (       d  M  [        UR                  S5      (       d  M2  [
        R                  R                  UR                  R                  ;   d  Mf    g   g)NtagsTF)	r   r   r   hasattrtargettorchTagnondeterministic_seededr   r   s     rJ   has_recomputable_rng_opsr      sV    

  4  V,,		11T[[5E5EE ! rM   c                   [        U R                  S   [        R                  [        R                  45      (       a  g[        U R                  S   [        R
                  5      (       d$  [        S[        U R                  S   5       35      eg)Nvalr&   z.expected node.meta['val'] to be SymFloat, got    )
isinstancer   r   SymIntSymBoolSymFloatr   typer   s    rJ   sym_node_sizer      sm    $))E"U\\5==$ABBdii&77<T$))EBR=S<TU
 	
 rM   c                      \ rS rSrSS jrSrg)InvalidNodeBase   c                    g)NzInvalid NoderZ   r   s    rJ   __repr__InvalidNodeBase.__repr__   s    rM   rZ   N)r]   str)r^   r_   r`   ra   r   rd   rZ   rM   rJ   r   r      s    rM   r   c                6    [        U R                  SS 5      S:g  $ )N	namespace_c10d_functional)getattrr   r   s    rJ   is_not_collectiver      s    4;;T26HHHrM   c                t   U R                   [        R                  :w  a  gU R                  S   nU R                  S   n[	        U[
        R                  5      (       a  UR                  S:w  a  gSUR                  ;  a  gUR                  S   nX#;  a  gX2   n[	        U[
        R                  5      (       a  U$ g)zGiven a getitem node, check if it extracts from a higher-order op
that has kwargs mapping the key back to an original input.

Returns the original input node if found, None otherwise.
Nr   r&   call_functionkwargs)	r   operatorgetitemargsr   fxNodeopr   )getitem_node	ho_resultr}   r   original_inputs        rJ   _get_ho_op_original_inputr      s     h...!!!$I


A
Ci))Y\\_-Ly'''h'F
[N."''**rM   c                L   U R                   [        R                  R                  R                  R
                  [        R                  R                  R                  R
                  4;  a  gU R                  S   n[        U[        R                  5      (       d  g[        U5      $ )zCheck if node is a view/reshape of a higher-order op output that aliases an input.

Returns the original input node from the higher-order op's kwargs if the pattern
matches, None otherwise.
Nr   )r   r   opsatenviewdefaultreshaper   r   r   r   r   )rI   sources     rJ   _is_copy_node_bw_onlyr      sl     {{599>>..66		8N8N8V8VWWYYq\Ffbgg&&$V,,rM   c                    [        U 5      nUb   X!;   a  [        X   [        5      (       d  X   $ [        U 5      nUb   X!;   a  [        X   [        5      (       d  X   $ g)a  Try to find a valid input replacement for an invalid forward output.

This handles cases where a forward output depends on backward nodes but
semantically aliases an input. For example, a view of a getitem from a
triton kernel that mutates a buffer in backward, or a direct getitem from
such a higher-order op. The original input may be a primal or a valid
intermediate node already present in the forward graph.
N)r   r   r   r   )rI   envr   s      rJ   _find_input_for_invalid_outputr      se     +40N"!3.@@"".t4N"!3.@@""rM   c                  ^ [         R                  " 5       n0 mU H4  nUR                  UR                  5      nUR                  Ul        UTU'   M6     U R
                   GHo  nU(       dL  [        U5      (       a  US:w  a  Xq;  a  [        TU'   M1  [        U5      (       a  US:w  a  Xq;  a  [        TU'   MW  UT;   a  M_  UR                  S:X  a  [        TU'   Mz  UR                  S:X  a  [        R                  " UR                  0 UR                  D6n	U	 V
s/ s H7  n
[        U
[         R                  5      (       d  M$  [        TU
   [         5      PM9     n	n
[#        U	5      (       a  [        TU'   GM  UR%                  UU4S j5      TU'   GM0  UR                  S:X  a  UR%                  UU4S j5      TU'   GM\  UR                  S:X  d  GMo  GMr     / n['        X#5       GH  u  p[        U
[         R                  5      (       GaV  U
T;  a  [)        S	U
 S
35      e[        TU
   [         5      (       Ga  SnU
R*                  [,        R.                  R0                  R2                  R4                  L a  [        U
5      (       a  [7        U
R                  5      S:  av  [        U
R                  S   [         R                  5      (       aJ  U
R                  S   T;   a7  [        TU
R                  S      [         5      (       d  TU
R                  S      nUc  [9        U
T5      nUb  UR;                  U5        GMV  [=        S	U
 S35      eUR;                  TU
   5        GM|  UR;                  U
5        GM     UR?                  [A        U5      5      nX>R                  S'   URC                  5         URE                  5         U$ s  sn
f )au  
Given a graph, extracts out a subgraph that takes the specified nodes as
inputs and returns the specified outputs.

This includes specifying non-placeholder nodes as inputs.

The general strategy is to initialize all inputs with proxies as we
encounter them, and trace through the graph, only keeping values which take
in valid proxies. Then, all dead code is eliminated.
backwardforwardplaceholderr   c                   > TU    $ rF   rZ   xr   s    rJ   rz   4_extract_graph_with_inputs_outputs.<locals>.<lambda>Y  	    CFrM   get_attrc                   > TU    $ rF   rZ   r   s    rJ   rz   r   \  r   rM   outputr   z couldn't be found in envNr&   r   z was invalid, but is outputdesc)#r   Graphr   namer   r   _must_be_in_backwardInvalidNode_must_be_in_forwardr   pytreearg_tree_leavesr   r   r   r   r   any	node_copyzipRuntimeErrorr   r   r   r   copy_r   lenr   appendr   r   tupleeliminate_dead_codelint)joint_graphri   outputsoutputs_descssubgraphignore_must_be_in_fw_bw	new_graphrI   new_nodeall_argsr   output_valuesx_descreplacementoutr   s                  @rJ   "_extract_graph_with_inputs_outputsr	    s%   $ 
I"$C ((3		D	  !!&$T**
*&'D	 $D))	)&'D	3; WW%#CIWW'--tyyHDKKHH "!Aa) 4
3q6?3!  
 8}}'D	!++D2BCCIWW
"!++D2BCCIWW S "T M0	a!!|"U1#-F#GHH#a&/22 # HH		 4 4 < <<,Q//AFFq("166!9bgg66q	S(&s166!9~GG"%affQi.K &"@C"HK*!((5$uQC/J%KLL  Q(  #= 1> 

5/
0C$HHV!!#NNis   #N<>N<c                >   [         R                  =(       a    [        U R                  [        R
                  R                  5      =(       a    [        U R                  5      (       + =(       d1    U R                  [        R                  R                  R                  :H  $ rF   )r   is_non_builtin_to_includer   r   r   _ops
OpOverloadr   r   higher_order triton_kernel_wrapper_functionalr   s    rJ   r  r    s`    ++ 	DKK!6!6	7	W
4;;@W<W 	R;;%))00QQQrM   c                    U R                   S:H  =(       a)    [        U R                  R                  S5      [        5      $ )Nr   r   )r   r   r   r   r   r   s    rJ   _is_backward_stater    s*    77m#W
499==3G(WWrM   c                @    U R                   R                  SS 5      S:H  $ )Npartitioner_tagis_backwardr   r   r   s    rJ   _has_tag_is_backwardr    s    99==*D1]BBrM   c                @    U R                   R                  SS 5      S:H  $ )Nr  
is_forwardr  r   s    rJ   _has_tag_is_forwardr    s    99==*D1\AArM   c                @    U R                   R                  SS 5      S:H  $ )Nr  must_be_in_forwardr  r   s    rJ   _has_tag_must_be_in_forwardr    s    99==*D15IIIrM   c                @    U R                   R                  SS 5      S:H  $ )Nr  must_be_in_backwardr  r   s    rJ   _has_tag_must_be_in_backwardr    s    99==*D15JJJrM   c                .   [        U 5      (       a  g[        U R                  [        R                  R
                  5      =(       a     U R                  R                  R                  n[        U 5      (       + =(       a    [        U 5      (       + =(       a    U$ NT)
r  r   r   r   r  r  _schema
is_mutabler  r  rI   r#  s     rJ   r   r     sq    "4(( 	4;;

 5 56 	+KK** 
 !&& 	,T22	rM   c                    [        U 5      (       a  g[        U R                  [        R                  R
                  5      =(       a     U R                  R                  R                  n[        U 5      =(       a    U$ r!  )	r  r   r   r   r  r  r"  r#  r  r$  s     rJ   r   r     sW    #D))4;;

 5 56 	+KK**   %4*4rM   c          
     \   [         R                  " S U R                  R                  SS9 5       6 n[         R                  " [	        [        U R                  R                  SS95      5      R                  R                  SS /[        U5      -  5      5      nUS U nX!S  nUS U nX1S  nXEXg4$ )Nc              3  8   #    U  H  oR                   v   M     g 7frF   r   ru   rI   s     rJ   rw   +_extract_fwd_bwd_outputs.<locals>.<genexpr>  s     	K J)) J   r   r   r   )	r   r   r   
find_nodesnextiterr   r   r   )joint_modulenum_fwd_outputsr   r   fwd_outputsbwd_outputsfwd_outputs_descsbwd_outputs_descss           rJ   _extract_fwd_bwd_outputsr6    s     $$	K 2 2 = = = J	KG **T,$$//8/<=>CCGGTFS\)	
M
 *?+K*+K%&67%&67%6IIrM   c                \    U  H&  nUR                   U:X  d  M  U R                  U5          g    g rF   )r   remove)saved_valuesr   saved_values      rJ   _remove_by_namer;    s+    #t#, $rM   c                    [        U 5      n[        [        U 5      S-
  SS5       H  n[        X   5      (       a  M  US-   n  U$    U$ )Nr&   )r   ranger   )fwd_module_outputsidxis      rJ   find_first_sym_noderB    sT      
!C3)*Q.B7-011a%CJ	 8 JrM   c           	        U R                  U5         U R                  [        R                  R                  R
                  R                  U4S9n[        R                  R                  R
                  R                  UR                  S   5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  US/S4S9n[        R                  R                  R                  R                  UR                  S   S/S5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  U[        R                  4S9n[        R                  R                  R                  R                  UR                  S   [        R                  5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  Xs4S9n[        R                  R                  R                  R                  UR                  S   U5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  U4S9n	[        R                  R                  R                  R                  UR                  S   5      U	R                  S'   [        U	R                  S   5      U	R                  S'   S S S 5        U R                  W	5         U R                  [        R                  R                  R                  R                   X4S9n
[        R                  R                  R                  R!                  U	R                  S   U5      U
R                  S'   [        U
R                  S   5      U
R                  S'   S S S 5        U R                  W
5         U R                  [        R                  R                  R                  R                  U
[        R"                  4SU SUR$                   3S9n[        R                  R                  R                  R                  U
R                  S   [        R"                  5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U$ ! , (       d  f       GN= f! , (       d  f       GN_= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GNc= f! , (       d  f       W$ = f)	Nr(  r   tensor_metar=  Tfp8_scale_pos__r   r   )inserting_afterr   r   r   r   absr   r   r   amaxprimsconvert_element_typefloat64	clamp_min
reciprocalmulTensorfloat32r   )r   rI   maxminpositionabs_node	amax_nodeamax_64_nodeclamp_min_nodereciprocal_nodemul_node
scale_nodes               rJ   calculate_quantization_scalingr]    s    
		t	$&&IINN&& ' 
  %yy~~1199$))E:JKe'>x}}U?S'Tm$ 
% 
		x	(''IINN''RD$' ( 
	 !&		 3 3 ; ;MM% 2$!
	u )@	u@U(V	}% 
) 
		y	)**IIOO0088U]]+ + 
 $)99??#G#G#O#ONN5!5==$
%  ,Ce$,
-( 
* 
		|	,,,IINN$$,,$ - 
 &+YY^^%=%=%E%Ee$c&
E" .E&.
M* 
- 
		~	.--IINN%%-- " . 
 ',iinn&?&?&G&G&'
U# /F  '/
]+ 
/ 
			/&&IINN%%!' ' 
  %yy~~1188  ' 
e (?x}}U?S'Tm$ 
0 
		x	(((IIOO0088EMM*!(1TYYK8 ) 


 "'!E!E!M!MMM% %--"

 *AQVAW)X
& 
) I 
%	$ 
)	( 
*	) 
-	, 
/	. 
0	/ 
)	( sZ   B0WB6W)*CW;B1XB0X$B1X1.CY
W&)
W8;
X

X
X.1
Y 
Yc           	     	   U R                  U5         U R                  [        R                  R                  R
                  R                  U[        R                  4S9n[        R                  R                  R
                  R                  UR                  S   [        R                  5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  Xr4S9n[        R                  R                  R                  R                  UR                  S   UR                  S   5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [        R                  R                  R                  R                  X4S9n	[        R                  R                  R                  R                  UR                  S   U5      U	R                  S'   [        U	R                  S   5      U	R                  S'   S S S 5        U R                  W	5         U R                  [        R                  R                  R                  R                  X4S9n
[        R                  R                  R                  R                  U	R                  S   U5      U
R                  S'   [        U
R                  S   5      U
R                  S'   S S S 5        U R                  W
5         U R                  [        R                  R                  R
                  R                  X4SU SUR                   3S9n[        R                  R                  R
                  R                  U
R                  S   U5      UR                  S'   [        UR                  S   5      UR                  S'   S S S 5        U$ ! , (       d  f       GNW= f! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN"= f! , (       d  f       W$ = f)Nr(  r   rD  fp8_quant_pos_rF  rG  )rH  r   r   r   rK  rL  r   rR  r   r   r   rP  rQ  rN  	clamp_maxr   )r   rI   r\  
quant_typerN  r`  rU  target_node_32scaled_target_nodeclamp_min_scaled_nodeclamp_max_scaled_nodequant_activation_nodes               rJ   perform_quantizationrg  -  s    
		z	*,,IIOO0088& - 
 &+YY__%I%I%Q%QIIeemm&
E" .E&.
M* 
+ 
		~	."00IINN%% - 1 
 */););)B)B&
(>*
& 2I##E*2
. 
/ 
		1	2 % 3 3IINN$$,,$0 !4 !
 -2IINN,D,D,L,L##E*I-
""5) 5L!&&u-5
""=1 
3 
		4	5 % 3 3IINN$$,,'3 !4 !
 -2IINN,D,D,L,L!&&u-y-
""5) 5L!&&u-5
""=1 
6 
		4	5 % 3 3IIOO0088'4!(1TYYK8 !4 !
 IIOO0088%**51: 	""5)
 5L!&&u-5
""=1 
6 ! u 
+	* 
/	. 
3	2 
6	5 
6	5 ! s@   CP09B>QB1QB1Q&$CQ80
P?
Q
Q#&
Q58
Rc                P    U R                  5       nU R                  5       nX-  S-  $ )z
Calculate the size of a PyTorch tensor in megabytes (MB).

Args:
    tensor (torch.Tensor): Input tensor

Returns:
    float: Memory size in MB
i   )numelelement_size)tensornum_elementsrj  s      rJ   calculate_tensor_sizerm  s  s+     <<>L&&(L'K88rM   c            	         [         R                  R                  R                  S   R	                  SS5      n U R                  S5       Vs/ s H%  n[        [         UR                  S5      S   5      PM'     n nU $ s  snf )N!activation_quantization_aten_passallowed_dtypesztorch.bfloat16;.r=  )r   	_inductorr   post_grad_fusion_optionsr   splitr   )rp  dtypes     rJ   get_allowed_dtypesrw    s}    __++DD+	c
,-  ;I:N:Ns:S:Su{{3'+,:S   s   ,A;c                n   [        5       n[        U 5      (       a  U R                  S   R                  U;  a  g[        R
                  R                  R                  S   R                  SS5      n[        U R                  S   5      n[        R
                  R                  R                  S   R                  SS5      (       d  X2:  $ [        R
                  R                  R                  S   R                  SS5      (       a&  [        X2:  5      =(       d    [        X2:  5      (       + $ [        X2:  5      $ )Nr   Fro  
size_in_mbd   skip_dynamo_guardsquantize_dynamic_shape)rw  r   r   rv  r   rs  r   rt  r   rm  r"   r!   )rI   rp  size_thresholdry  s       rJ   should_quantizer~    s   ')Nd##tyy'7'='=^'S__++DD+	c,  'tyy'78J??!!::+	c
&' ++ ??!!::/

#&
./ ), J+J,HIIJ
 ))EFFrM   c                     [         R                  R                  R                  S   R	                  SS5      n [        [         U R                  S5      S   5      $ )Nro  ra  ztorch.float8_e5m2rr  r=  )r   rs  r   rt  r   r   ru  )ra  s    rJ   get_quant_typer    sN    ''@@+	c,+,  5***3/344rM   c                ^    [         R                  " U 5      nUR                  UR                  4$ )z
Calculate the range of values for a given torch.dtype.
Args:
    dtype (torch.dtype): The input dtype.
Returns:
    tuple: A tuple containing the minimum and maximum values.
)r   finforT  rS  )rv  infos     rJ   calculate_ranger    s%     ;;uD88TXXrM   c           
        U R                  SS9S   nUR                  S   n[        5       n[        U5      u  pE[	        5       n/ n/ n[        U5       GH  u  pU
R                  R                  SS5      (       d  M)  [        R                  R                  R                  S   R                  SS5      (       aP  [        X
US	U	5      n[        X
XXEU	5      n[        U5      (       d  UR                  U5        OUR                  U5        OU R!                  U
5         U R#                  [        R$                  R&                  R(                  R*                  X4S
U	 SU
R,                   3S9n[        R$                  R&                  R(                  R+                  U
R                  S   U5      UR                  S'   [/        UR                  S   5      UR                  S'   S S S 5        WXi'   GM     [        U5       VV
s/ s H  u  pUR                  X5      PM     nnn
[1        U5      nXx-   nU(       a  US U U-   XS  -   nUR3                  S[5        U5      5        [6        S   S==   S-  ss'   g ! , (       d  f       N= fs  sn
nf )Nr   r,  r   saved_for_quantizationFro  use_scalingT-q=r_  rF  rG  r   rD  inductor%activation_quantization_fwd_aten_passr&   )r-  r   r  r  dict	enumerater   r   r   rs  r   rt  r]  rg  r   r   rH  r   r   rK  rL  r   r   r   rB  
update_argr   r   )r   r   r2  ra  rN  r`  position_to_quanttensor_scale_nodessym_scale_nodesrU  rI   r\  
quant_noderA  output_updated_argsr@  scale_nodess                    rJ   quantize_activation_fwr    s_   *1-F++a.K!J*:6I(*%'O#K099==1599%%>>3c-&' <E8

 2x
 #:..&--j9#**:6 **40!&!4!4		<<DD"/-hZqD "5 "J 		<<DD IIe,j OOE*
 6M".6JOOM2 1 +5'K 1T 7@6L6L71a&6L  
 1
2C$6K%36I$6OO 	 a234Z@AQFAA 10&s   CI,9I=,
I:	c           
     R
  ^	 U R                    Vs/ s H  oR                  S:X  d  M  UPM     nnS nU GH  nUR                  R                  SS5      (       d  M'  UR                  R	                  S5        UR                  R	                  S5      n[
        R                  R                  R                  S   R                  SS5      (       Ga  U R                  U5         SUR                  R                  SS	5      -   m	[        U	4S
 jU 5       5      nS S S 5        U R                  W5         U R                  [
        R                  R                  R                   R"                  X4S9n[
        R                  R                  R                   R#                  UR                  S   U5      UR                  S'   [%        UR                  S   5      UR                  S'   S S S 5        U R                  U5         U R                  [
        R                  R&                  R(                  R*                  X54S9n[
        R                  R&                  R(                  R+                  UR                  S   UR                  S   5      UR                  S'   [%        UR                  S   5      UR                  S'   S S S 5        U R                  W5         U R                  [
        R                  R                  R                   R"                  Xd4S9n[
        R                  R                  R                   R#                  UR                  S   U5      UR                  S'   [%        UR                  S   5      UR                  S'   S S S 5        OU R                  U5         U R                  [
        R                  R                  R                   R"                  X4S[-        UR                  5      -   S9n[
        R                  R                  R                   R#                  UR                  S   U5      UR                  S'   [%        UR                  S   5      UR                  S'   S S S 5        [/        UR0                  R3                  5       5       H#  nUW:w  d  M  X:w  d  M  UR5                  X5        M%     GM     [6        S   S==   S-  ss'   g s  snf ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GNH= f! , (       d  f       N= f! , (       d  f       N= f)Nr   r  Fdequant_typero  r  
fp8_scale_
fp8_quant_ c              3  L   >#    U  H  nUR                   T:X  d  M  Uv   M     g 7frF   r   )ru   	bwd_input
scale_names     rJ   rw   )quantize_activation_bw.<locals>.<genexpr>  s&      &)2I$>>Z7 "	)2s   $	$r(  r   rD  dequant_rG  r  %activation_quantization_bwd_aten_passr&   )r   r   r   r   popr   rs  r   rt  rH  r   r   r.  r   r   rK  rL  r   r   r   divrQ  r   listuserskeysreplace_input_withr   )
r   rI   	bw_inputsactivation_noder  r\  divided_target_node_32dequant_nodeuserr  s
            @rJ   quantize_activation_bwr    s,   "'++J+$M1I+IJO99==1599IIMM2399==8L%%>>3c-'( **40!-		0A0A,PR0S!SJ!% &)2& "J 1 **:6&+&9&9		<<DD"1 ': 'O
 		<<DD IIe,l $((/
 ;R',,U3;O((7 7 **?;-2-@-@		**11-: .A .* :?9K9K9R9R',,U3Z__U5K:*//6 00F0K0KE0RS +//> < **+AB#(#6#6		<<DD4C $7 $L
 		<<DD277> !%%e,
 8O$))%08L%%m4 CB **40#(#6#6		<<DD"1'#dii.8 $7 $L 		<<DD IIe,l !%%e,
 8O$))%08L%%m4 1 TZZ__./<'D,C++D? 0M T Z@AQFAY K 10 76 <; CB 10sJ   SS5S,B1S#6B>S5B1TCT
S 	#
S2	5
T	
T	
T&	c                  ^ ^ [        SS U 4S jS9  [        T R                  5        [        SS U 4S jS9  [        SS U4S jS9  T R                  R                  S	S
9S   R                  S   nU H  nSUR
                  ;   d  M  U[        R                  " SSUR
                  5         nTR                  R                  U5         TR                  R                  UR
                  S9nS S S 5        UR                  S   nWR                  R                  UR                  5        SUR                  S'   XvR                  S'   UR                  U5        TR                  R                  U5        GM     [        R                  R                   R"                  S   R%                  SS5      (       a  ['        TR                  R                  SS
95      nUS   n	[)        U5       H  n
[+        U
5      (       a  M  U
n	  O   T R                  R                  S	S
9S   R                  S   nU H  nSUR
                  ;   d  M  TR                  R                  U	5         TR                  R                  UR
                  S9nS S S 5        WR                  R                  UR                  5        Un	M     [-        TR                  5        [        SS U4S jS9  g ! , (       d  f       GN= f! , (       d  f       Nq= f)Nartifactc                     SSS.$ )N,before_activation_quantization_fwd_aten_passstringr   encodingrZ   rZ   rM   rJ   rz   5perform_fp8_activation_quantization.<locals>.<lambda>T      B 
rM   c                 &   > T R                  SSSS9$ NFTprint_outputinclude_strideinclude_deviceprint_readable
fwd_modules   rJ   rz   r  X      :44tD 5 
rM   metadata_fn
payload_fnc                     SSS.$ )N+after_activation_quantization_fwd_aten_passr  r  rZ   rZ   rM   rJ   rz   r  a      A 
rM   c                 &   > T R                  SSSS9$ r  r  r  s   rJ   rz   r  e  r  rM   c                     SSS.$ )N,before_activation_quantization_bwd_aten_passr  r  rZ   rZ   rM   rJ   rz   r  l  r  rM   c                 &   > T R                  SSSS9$ r  r  
bwd_modules   rJ   rz   r  p  r  rM   r   r,  r   r  z^fp8_quant_pos_\d+_r  r  r  Tr  ro  r  r   r=  r  c                     SSS.$ )N+after_activation_quantization_bwd_aten_passr  r  rZ   rZ   rM   rJ   rz   r    r  rM   c                 &   > T R                  SSSS9$ r  r  r  s   rJ   rz   r    r  rM   )r   r  r   r-  r   r   resubrH  r   r   updatereplace_all_uses_with
erase_noder   rs  r   rt  r   r  reversedr5   r  )r  r  bwd_module_inputsquant_fwd_module_outputsfwd_noder  quant_bwd_inputr  quant_bwd_module_inputsbwd_input_locbw_inputscaled_fwd_module_outputsscale_bwd_inputs   ``           rJ   #perform_fp8_activation_quantizationr  M  s   
 

	 :++,

	 

	  *//::h:GJOOPQR,8==()-r8==AI !!11)<","2"2">">HMM">"R =$>>.9L  ''6=AO  !9:3?  0++O<''	2 - 66+	c- #'z'7'7'B'Bm'B'T"U/3 !89Hx(( ( :
 %/$4$4$?$?8$?$LQ$O$T$TUV$W!1Hx}},%%55mD&0&6&6&B&B&B&VO E$$++HMM: / 2 :++,

	? =<0 EDs   $K$K)
K&	)
K7	c                t   [         R                  R                  SS 5       c  g U(       a  U Vs/ s H  oDR                  PM     snO/ nU  Vs0 s H  oDR                  U_M     nn[        R
                  R                  R                  S   R                  SS5      (       a/  U  Vs0 s H"  nSUR                  ;  d  M  UR                  U_M$     nnUR                  R                  SS9S   R                  S   nUR                  R                  SS9 Vs0 s H  oDR                  U_M     nnSn	U H  nUR                  U;   d  M  [        U5      (       d  M'  UR                  U;   a"  [        R                  S	UR                  5        MY  S
UR                  S'   UR                  S   R                  UR                  S'   S
XR                     R                  S'   UR                  S   R                  XR                     R                  S'   S
n	M     U	(       a  [        XU5        g g s  snf s  snf s  snf s  snf )Nro  exclude_primalsFprimalsr   r,  r   r   z*Skipping quantization of static input %s: Tr  r   r  )inductor_configrt  r   r   r   rs  r   r   r-  r   r~  r<   debugr   rv  r  )
r9  r  r  rq   rI   static_input_namessaved_values_namesr?  r  should_perform_fp8_quants
             rJ   enable_activation_quantizationr    s    	0044/	
 	
 	 '  ;;:t:; 
 7CCld))T/lC66+	c
U#$ )5
(4	8RODIItO 	 
 $))444A!DII!L$.$4$4$?$?=$?$Q$QD		4$Q    %"99**t/D/Dyy..		F		R26DII./(,		%(8(>(>DIIn%JNii(--.FG@D		%@P@V@Vii(--n='+$ #  +JDUV  9 	< D
s   H&H+%H0=H0H5)rq   c               	   [        XS9u  pVpxU R                  R                  SS9n	/ [        [        U	5      Qn
/ [        [
        U	5      Qn/ [        [        U	5      Qn/ [        [        U	5      Qn/ [        [        U	5      Qn[        U R                  X!-   U-   U-   UUS5      n[        R                  R                  5       nUR                  SS9 H  nUR                  (       d.  [        UUR                  5        [        UUR                  5        MB  U(       aO  [!        S UR                   5       5      (       a.  [        UUR                  5        [        UUR                  5        M  [        U5      (       d  M  [        UUR                  5        U(       a  M  [#        S5      e   [%        5       n/ n/ nU HJ  n['        U5      nU(       a$  UR)                  U5        UR+                  U5        M9  UR+                  U5        ML     [-        U R                  5      n[.        R0                  " UX5       Hc  nSUR2                  ;  a  M  [5        UR2                  S   5      U-
  n[7        US S	9 H  nUU;  a  M  UR+                  UU   5        M!     UU-  nMe     UR9                  5         UR;                  UU-   5        / n/ n/ nU H  n[=        UR2                  R?                  S5      [@        5      (       a  UR+                  U5        MD  UR2                  R?                  S
S5      (       a  UR+                  U5        Mx  UR+                  U5        M     UR9                  5         UR;                  UU-   5        [C        U5      n[E        U5       HL  u  nnUU:  d  M  UR2                  R?                  S
S5      (       a  M1  [#        SU SU S[C        U5       35      e   [        U R                  X-   XQ-   U-   U-   U[G        [C        U5      [C        U5      -   [C        U5      -   5       Vs/ s H.  nUU:  a  U[C        U5      :  a  [I        U5      O
[K        U5      PM0     sn-   S5      n[        U R                  UU-   U-   U-   U-   U-   UUS5      n[L        RN                  RQ                  U U5      n[L        RN                  RQ                  X5      n [S        UUU U5        UU 4$ s  snf )Nr1  r   r,  r   c              3     #    U  H^  nUR                   [        R                  R                  R                  R
                  L =(       a    [        UR                  5      S :H  v   M`     g7fr   N)r   r   r   r   wait_tensorr   r   r  rt   s     rJ   rw   +_extract_fwd_bwd_modules.<locals>.<genexpr>  sR      )
   HH		22>>FFF "AGG!"s   A&A(z'backward_state_inputs must not be emptyr   c                    U R                   $ rF   r  )ss    rJ   rz   *_extract_fwd_bwd_modules.<locals>.<lambda>"  s    166rM   r|   saved_tensor_with_no_vc_checkFzi=z, no_vc_check_start_idx=z, len(saved_values)=r   )*r6  r   r-  filterr4   r5   r3   r2   r  r	  r   distributedis_availabler  r;  r   allr   r$   r   addr   r   	itertoolschainr   r   r~   clearextendr   r   r   r   r  r>  r/   r.   r   _lazy_graph_module_make_graph_moduler  )!r0  r9  saved_sym_nodesr1  rq   r2  r3  r4  r5  placeholdersprimal_inputstangent_inputsfwd_seed_offset_inputsbwd_seed_offset_inputsbackward_state_inputs	bwd_graphdistributed_enabledrI   saved_symbolssaved_sym_nodes_bindingsaved_sym_nodes_derivedsymbolsymbol_bindingsnew_symbolsr  saved_values_with_vc_checksaved_values_no_vc_checksaved_opaque_objectsno_vc_check_start_idxrA  	fwd_graphr  r  s!                                    rJ   _extract_fwd_bwd_modulesr    s    	!O CK/  %%00M0BL7fZ67M9vk<89NIv&9<HIIv&9<HIGf%7FG2&7:PPI  ++88:$$$6zzL$))4OTYY7
 !S )
 ZZ)
 &
 &

 L$))4OTYY7%%L$))4(($%NOO) 74 /9lM    *40f%#**40#**40   3<3E3EFO 7V		!"499U#34}D)9:A '#**?1+=> ; 	$ W" 25LLM "$!diimmE*,<== ''-YY]]:EBB$++D1&--d3  25MMN :; \*4%%99==!@%HH$34I3JJ^_bco_p^qr  + 3."%99OK
 L!C(<$==O@TT	
 ))a#l2C.C 02+A./	
	
 	I 3
	
	 	 !		!
  	  	I &&99,	RJ&&99,RJ"j*.I z!!9
s   #5S)static_lifetime_input_indicesrq   c                 ^ / nSnU R                   R                   H7  n[        U5      (       d"  [        U5      (       d  [	        U5      (       d  M5  UnM9     Uc  [        S5      eU R                   R                   H*  n[        U5      (       d  UR                  U5        XvL d  M*    O   [        S U 5       5      n[        U 5      n	[        U 5      n
U	(       aE  [        U R                   5      S   b"  [        R                  " S5        [        U UUUS9$ [        U SS9n [         R"                  (       d  [%        U 5        ['        U 5        [)        U 5        Uc  / n[+        XU5      n/ n/ n[,        R.                  R1                  5       mSS	 jnSS
 jnSU4S jjnU R                   R                   GH  nUR2                  U;  a  M  UR4                  S:X  a'  UR2                  S U R7                  5        5       ;   a  MM  UR8                  [,        R:                  R<                  R>                  R@                  [,        R:                  RB                  RD                  R@                  [,        R:                  RB                  RF                  R@                  [,        R:                  RB                  RH                  R@                  [,        R:                  RB                  RH                  RJ                  4;   a  GMA  [M        U5      (       a  UR                  U5        GMe  U" U5      (       a  GMu  URN                  RQ                  S5      [R        RT                  :X  a  UR                  U5        GM  U" U5      (       a6  U	(       a  [        SU SUR8                   35      eUR                  U5        GM  U" U5      (       d  UR4                  S:X  a  [        SU S35      eURV                   Vs/ s H  nUR2                  U;  d  M  UPM     nn[Y        S U 5       5      (       a  UR[                  U5        GM~  []        U5      (       a  GM  UR                  U5        GM     [_        [`        Rc                  U5      Re                  5       5      n[_        [`        Rc                  U5      Re                  5       5      n[         Rf                  (       a  [g        U R                   U5      nUc  URh                  n[k        U UUUUS9u  nnUR                   Rm                  [n        S9  UR                   Rm                  [n        S9  U	(       a,  U
(       a  [q        U UU[s        U5      5      u  nn[u        U5      n[         Rv                  (       a  SSK<J;n  U" UUUU5        [{        U5      n[{        U5      n[}        USS9n[s        UR~                  5      S:  a
  [}        USS9nUU4$ s  snf )a  
Partitions the :attr:`joint_module` in a manner that closely resembles the
behavior observed in the original ``.forward()`` and ``.backward()`` of the
callable, i.e., the resulting forward graph contains those operators that
are executed in the original ``.forward()`` callable passed to
:func:`aot_function`.

The default partitioner collects the operators that are between the forward
inputs and the forward outputs. This helps in finding the tensors which have
to be stashed for the backward pass. These stashed tensors become the output
of the generated forward graph. The remaining operators are then placed in
the backward graph.

.. warning::
    This API is experimental and likely to change.

Args:
    joint_module(fx.GraphModule): The joint forward and backward graph. This
        is the result of AOT Autograd tracing.

Returns:
    Returns the generated forward and backward Fx graph modules.
Nzlast_node must not be Nonec              3  \   #    U  H"  oR                   S :w  d  M  UR                  v   M$     g7fr   Nr   r   r)  s     rJ   rw   $default_partition.<locals>.<genexpr>  s"      $+dww(/B			m   ,,r   zxTrying to unsafely apply AC to a non-functional graph with the default partitioner. Falling back to min-cut partitioner.)r1  r  Tis_default_partitionc                    SU R                   ;   =(       d=    [        U R                   R                  S5      [        R                  R
                  5      $ )NrD  r   )r   r   r   r   _subclasses
FakeTensorr   s    rJ   	is_tensor$default_partition.<locals>.is_tensor  s=    		) 
ZIIMM% %"3"3">">.
 	
rM   c                x    [        S U R                   5       5      =(       a    [        U R                  5      S:  $ )Nc              3  Z   #    U  H!  oR                   [        R                  :H  v   M#     g 7frF   )r   r   r   ru   r  s     rJ   rw   =default_partition.<locals>.is_multi_output.<locals>.<genexpr>  s     GJDx///Js   )+r   )r  r  r   r   s    rJ   is_multi_output*default_partition.<locals>.is_multi_output  s.    GDJJGG $DJJ!#	
rM   c                   > U R                  SS9=(       a^    U R                  S;  =(       aH    T(       + =(       d:    U R                  [        R                  R
                  R                  R                  L$ )NF)impure_random)r   r   )	is_impurer   r   r   r   r   r  r   )rI   r  s    rJ   r)  $default_partition.<locals>.is_impure  sc     NNN/ 		 (' U;;eii&@&@&L&L&T&TT	
rM   r   c              3  *   #    U  H	  u  pUv   M     g 7frF   rZ   )ru   kvs      rJ   rw   r    s      3
6$!A6s   r   z.Trying to apply AC on a graph with impure op: z, r   z	Expected z to be a tensorc              3  8   #    U  H  n[        U5      v   M     g 7frF   r   rt   s     rJ   rw   r    s     7!{1~~r+  r  r1  rq   )is_impure_noder&   enable_activation_offloadingFr  r[   )@r   r   r  r4   r3   r   r5   r   r$   r   r   r0   warningswarn#min_cut_rematerialization_partitioncleanup_recompute_tagsr   (unsafe_allow_optimization_of_collectivesforce_save_collectivesforce_save_effectful_opsforce_save_bw_mutation_srcclassify_nodesr   r  r  r   r   named_modulesr   r   r   _assert_scalarr   profiler_record_function_enter_new_record_function_enter_record_function_exit_RecordFunctionr   r   r   r%   	MUST_SAVEr  r  r  r   r  r  fromkeysr  _sync_decision_cross_ranksrq   r  r   r   functionalize_rng_opsr   #reordering_to_mimic_autograd_enginer3  ,_activation_offloading.activation_offloadingr9   thread_graphsafe_rng_from_hopsrl   )r0  _joint_inputsr1  r  rq   forward_nodes	last_noderI   forward_node_namesgraph_has_recomputable_opsgraph_has_recomputable_rng_ops	node_infor9  r  r  r%  r)  rv   backward_usages	fw_module	bw_moduler3  r  s                         @rJ   default_partitionrV  y  s   @ MI""((t$$
4(8(8<OPT<U<UI ) 9::""((4    &	 )
 $ $+$  "6l!C%=l%K"! 2 23A6B MML 7 /.K	  .lQUV::|,\*|,$,(*%_I LO++88:



$ ""((99..77j TYY 3
&4463
 &
 ;;IINN))11 II99AAII55==II44<<II44DD	
 	
 t ""4(4  99==%)9)C)CC%T??)$DTF"T[[MZ  %477o#= 9TF/!BCC&*jjUjAFFBT4T1jU7777 ""?3d##%g )j l388:;L4==9>>@AO((1,2D2DlS"*&/&K&K#3''$?Iy OO''7H'IOO''7H'I!)#8iC4H$ Iy 8	B	 **	
 	%'		
 y)Iy)I.yeLI
9&&'!+29$O	iA Vs   !W9Wg    .Ac                    XR                   -  $ rF   )itemsize)ri  rv  s     rJ   _tensor_nbytesrY  U  s    >>!!rM   c                  ^ SS jmSU R                   ;   a  U R                   S   n[        U[        5      (       a  g[        U[        [        45      (       a  [        U4S jU 5       5      $ [        U[        5      (       a#  [        U4S jUR                  5        5       5      $ [        U[        R                  5      (       a  T" U5      $ [        S[        U5       SU  35      eU R                  S:X  d;  U R                  [        R                  R                  R                   R"                  L a  g	[        S
U  S35      e)Nc                    [        U [        R                  5      (       d  g[        [	        U R                  5       SS9U R                  5      $ )Nr      fallback)r   r   rQ  rY  r    ri  rv  r   s    rJ   object_nbytes_size_of.<locals>.object_nbytesZ  s4    !U\\**i	DA177KKrM   r   r&   c              3  4   >#    U  H  nT" U5      v   M     g 7frF   rZ   )ru   rv   r`  s     rJ   rw   _size_of.<locals>.<genexpr>g  s     5A}Q''   c              3  8   >#    U  H  u  pT" U5      v   M     g 7frF   rZ   )ru   rF  rv   r`  s      rJ   rw   rc  i  s     @KDA}Q''Ks   zUnknown metadata type z	 on node r   r   r   zO didn't have `val` metadata; we should always have `val` metadata on the nodes.)r   objectr]   r   )r   r   r   r  r   sumr  itemsr   rQ  r   r   r   r   r   r   r?  r   )rI   r   r`  s     @rJ   _size_ofri  Y  s    L
 		iic<(( dE]++5555T""@CIIK@@@U\\** %%3DI;ivNOOww*uyy~~/L/L/T/T T

vde rM   c           	     4   SSK Jn  U" [        5      nU R                   H5  nUR                  S:X  d  M  X#R
                  R                  ==   S-  ss'   M7     [        R                  S[        UR                  5       [        R                  " S5      SS95        g )Nr   )r   r   r&   %sTr}   reverse)collectionsr   r   r   r   r   r^   r<   r  r~   rh  r   
itemgetter)r   r   cntrI   s       rJ   
_count_opsrq  v  sk    '%c*C77o%$$%*%  HHT6#))+8+>+>q+A4PQrM   c                    / n [        [        R                  R                  5       H  n[	        [        R                  R                  U5      n[        U[        R                  R                  5      (       d  MR  UR                  5        HJ  n[	        X#5      n[        R                  R                  UR                  ;   d  M8  U R                  U5          M     M     U $ rF   )dirr   r   r   r   r   r  OpOverloadPacket	overloadsr   	pointwiser   r   )r   	attr_nameopoverloadpacketoverloadop_overloads        rJ   pointwise_opsr{    s    -/C(	"599>>9=*EJJ,G,GHH(224H!"2=Kyy""k&6&66

+, 5 ) JrM   c                    U  Vs0 s H=  n[        U[        R                  R                  R                  5      (       d  M8  X!U   _M?     nn[        UR                  5       [        R                  " S5      SS9$ s  snf )Nr&   Trl  )	r   r   r   rI   r   r~   rh  r   ro  )r   	depth_maparg
arg_depthss       rJ   sort_depthsr    sk     (,'+z#uxx}}?Q?Q/Rs^t   *""$(*=*=a*@$OOs   7A8 	A8c                  ^
^^ [         R                  " 5       m0 m
U R                  R                  SS9 H  nTR	                  UU
4S j5      T
U'   M     [        U R                  R                  5       VVs0 s H  u  p!X_M	     snnmSU
UU4S jjn[        [        [        U R                  R                  5      5      nSn[        R                  nU H(  nUR                   H  nTU   U:  d  M  TU   nUnM     M*     Uc  U $ [        U R                  R                  5      STU     HZ  nUR                  S:X  d  M  UR                  [        R                   R"                  R$                  R&                  L d  MR  U" U5        M\     [        U R                  R                  5      TU   S  H  nU" U5        M     [        R                   R)                  U T5      n	U	$ s  snnf )a|  
This pass finds the first bwd node in the graph (by looking at users of
tangents) and then reorders the graph by walking from this node to all the
way to the end of the graph. At each op in this traversal, we insert this op
in a new graph and try to bring only the relevant subgraph from the other
non-bwd edges relevant for this op. This closely mimics the behavior of
autograd engine.

Why is this pass required in the first place?

This is an artifact of how partitioners work today. The starting point of
partitioner is a joint graph, which is fwd and then bwd graph. In the case
of checkpointing, we keep portions of fwd graph in their original place in
the joint graph, while obtaining a bwd graph. As a result, the resulting bwd
graph has copies of recomputed fwd subgraphs followed by the original bwd
graph. If we run this naively, this leads to bad memory footprint, because
the fwd subgraphs are live for way longer duration than necessary. This pass
reorders the operations such that we prioritize the ops for the original bwd
graph while only realizing those ops from the fwd graph that are necessary
at any given point in the graph.
r   r,  c                   > TU    $ rF   rZ   r   s    rJ   rz   5reordering_to_mimic_autograd_engine.<locals>.<lambda>  s	    ArM   c                8  > U /n[        5       n[        U5      S:  aM  UR                  5       n X;   d  U T;   a  M,  UR                  U 5        XR                  -  n[        U5      S:  a  MM  [        UU4S jS9nU H  n TR                  U U4S j5      TU '   M     g )Nr   c                   > TU    $ rF   rZ   )rv   orders    rJ   rz   Sreordering_to_mimic_autograd_engine.<locals>.insert_node_in_graph.<locals>.<lambda>  s	    %(rM   r|   c                   > TU    $ rF   rZ   r   s    rJ   rz   r    r   rM   )r$   r   r  r  all_input_nodesr~   r   )rI   	cur_nodesinsertable_nodesr   r  r  s      rJ   insert_node_in_graphAreordering_to_mimic_autograd_engine.<locals>.insert_node_in_graph  s    F	0:)nq ==?D'43;  & ---I )nq  ""28JK$D!++D2BCCI %rM   Nr   rI   r\   r]   None)r   r   r   r-  r   r  r   r  r  r5   mathinfr  r   r   r   r   r   r   r   GraphModule)gmrI   r@  r  r  first_node_in_bwdminimum_ordertangentr  new_gmr   r  r  s             @@@rJ   rI  rI    s   . 
I"$C ##}#5''.>?D	 6 )2"((..(AB(A93TY(ABED D& &bhhnn=>NHHM!MMDT{]* %d$(! " "  	 RXX^^$%?u->'?@77o%$++9M9M9U9U*U & A RXX^^$U+<%=%?@T" A XX!!"i0FM[ Cs   6Gc                   UR                   nUc  [        S5      eU R                  n	UR                  n
[        R                  R
                  R                  nU R                  R                  U5         U R                  R                  SU 35      n[        U5      UR                  S'   UnSSS5        UR                  R                  U5         UR                  R                  SU 35      n[        U5      UR                  S'   UnSSS5        [        UR                  5      nWUS'   U R                  R                  U5         U	R                  SUUR                  /UR                  Q7US9nSSS5        UR!                  W5        U	R#                  U5        [        UR                  5      nWUS'   U
R%                  U5         U
R                  SUUR                  /UR                  Q7US9nUR!                  U5        U
R#                  U5        SSS5        Xg4$ ! , (       d  f       GNx= f! , (       d  f       GN.= f! , (       d  f       N= f! , (       d  f       Xg4$ = f)	a  
Note [CUDA Graph Safe RNG Functionalization]

CUDA Graph capture doesn't work with get_rng_state and set_rng_state because these functions operate on CPU values,
while CUDA Graph RNG capture uses on-device CUDA tensors. To solve this, we use graphsafe_set_state with a
CUDA Generator registered to the CUDA Graph before capture begins. graphsafe_set_state updates the generator's pointer
to reference a different GeneratorImpl, ensuring subsequent calls are correctly forwarded to the desired generator
(and its cuda-tensor RNG state during graph capture).

For each RNG operation's forward/backward pair:

- We create two generators initialized with identical values
- Each forward and backward call advances its respective generator equally
- This keeps generators synchronized so forward and backward operations use matching RNG values

When forward is called multiple times before backward (causing desynchronization):

- We save the forward RNG state
- We update the backward Generator's state before executing backward

Before each CUDA Graph replay, replay_prologue updates captured RNG pointers with current states, ensuring backward Generator
changes are reflected during replay.

This function modifies both forward and backward computation graphs by:

Creating RNG state placeholders for both passes
Updating the forward node to use graph-safe RNG state
Updating the backward node to use graph-safe RNG state

For more details: https://github.com/pytorch/pytorch/issues/113541
Nzdevice_idx must not be Nonefwd_rng_state_r   bwd_rng_state_	rng_stater   r   r   )indexr   r   r   _prims	rng_primsgraphsafe_run_with_rng_staterH  r   r6   r   r  r   create_noder   r   r  r  inserting_before)rT  rU  fw_nodebw_nodedevice	rng_countlast_fwd_inputlast_bwd_input
device_idxfw_graphbw_graphr  fwd_rng_statebwd_rng_state	fw_kwargsfunctional_fw_node
bwd_kwargs
rng_outputs                     rJ   %apply_graphsafe_rng_functionalizationr    s   R J:;;HH#(<<#9#9#V#V  
	(	(	8!33nYK4PQ$?
$K5!& 
9 
	(	(	8!33nYK4PQ$?
$K5!&	 
9 W^^$I*Ik		(	(	1%11(..07<<0	 2 
 
2 !!"45  gnn%J+J{		"	"7	+))(..07<<0	 * 

 	%%j1G$ 
, ))M 
9	8 
9	8 
2	1 
,	+ ))s1   29H9H.+I AI
H+.
H= 
I
I!c                  ^' [         R                  " 5       nSS jnSS jm'SS jnU" U 5      nU" U5      nU" U5      n	0 n
U R                  R                   H  n[	        U5      (       d  M  [        UR                  S5      (       d  M2  [        R                  R                  UR                  R                  ;   d  Mf  UR                  U;  d  UR                  U	;  a  M  X{R                     nXR                     nXR                     nXS.X'   M     [        R                  R                  R                  n[        R                  R                  R                  nS nUR                  R!                  SS9 H  nSUR                  ;   d  M  Un  O   Uc  [#        S	5      e/ n[%        ['        UR                  R!                  SS95      5      n[%        ['        UR                  R!                  SS95      5      n[)        U'4S
 jU
R+                  5        5       5      nUR-                  [        R.                  " S5      5        [1        U5      S:  n[        R2                  R4                  n[4        R6                  =(       a<    U(       + =(       a.    UR8                  (       + =(       d    UR:                  R<                  n[?        U
R+                  5       5       GH   u  nnUS   nUS   nT'" U5      nUR                  nUR                  nU(       a*  Ub'  UR@                  S:X  a  [C        UUUUUUUU5      u  nnMb  URE                  U5         URG                  SUUR                  /URH                  Q7URJ                  S9nURG                  S[L        RN                  US40 S9nU" U5      URP                  S'   URG                  S[L        RN                  US40 S9n [R        RR                  " URP                  5      U l(        URU                  U 5        URW                  U5        URY                  U5        S S S 5        URE                  U5         S[%        U5       3n!UR[                  U!5      n"U" U5      U"RP                  S'   S S S 5        URE                  U5         URG                  SUW"UR                  /URH                  Q7URJ                  S9n URU                  U 5        URW                  U5        S S S 5        GM#     U(       a  [%        []        UR                  R!                  SS95      5      n#U#RH                  S   n$[1        U$5      U-
  n%U$S U% [_        U5      -   U$U%S  -   n&UR                  Ra                  U&5        UR                  RW                  U#5        URc                  5         URc                  5         X4$ ! , (       d  f       GN= f! , (       d  f       GNV= f! , (       d  f       GM  = f)Nc                &   0 nU R                   R                   Ht  nUR                  S:X  d  M  [        UR                  S5      (       d  M2  [
        R                  R                  UR                  R                  ;   d  Mf  X!UR                  '   Mv     U$ )Nr   r   )
r   r   r   r   r   r   r   r   r   r   )gmodrandom_nodesrI   s      rJ   get_rng_ops*functionalize_rng_ops.<locals>.get_rng_opsb  sh    +-JJ$$D?*DKK00II559I9II*.TYY' % rM   c                B   SU R                   ;  a  gU R                   S   n[        U[        5      (       d  U4nU HL  n[        U[        R                  5      (       d  M$  UR
                  R                  S:X  d  M@  UR
                  s  $    [        R
                  " S5      $ )zF
Check the example value of the node outputs to find the device type.
r   Ncudacpu)r   r   r   r   rQ  r  r   )rI   
candidates	candidates      rJ   
get_device)functionalize_rng_ops.<locals>.get_devicem  s     		!YYu%
*e,,$J#I)U\\22##((F2$+++ $
 ||E""rM   c                L   SSK Jn  U" 5       nUc  [        S5      eU   U bF  U R                  S:X  a6  UR	                  [
        R                  R                  5       5      sS S S 5        $ UR	                  [
        R                  " 5       5      sS S S 5        $ ! , (       d  f       g = f)Nr   )detect_fake_modezfake_mode must not be Noner  )torch._guardsr  r   r   from_tensorr   r  get_rng_state)r  r  	fake_modes      rJ   get_sample_rng_state3functionalize_rng_ops.<locals>.get_sample_rng_state  sx    2$&	 !=>>!fkkV&; ,,UZZ-E-E-GH Y (()<)<)>? YYs   A B(#B
B#r   )fwdbwdr   r,  r  zaCouldn't find tangent node in graph inputs. This is unexpected, please file a bug if you see thisc              3  :   >#    U  H  nT" US    5      v   M     g7f)r  NrZ   )ru   	node_pairr  s     rJ   rw   (functionalize_rng_ops.<locals>.<genexpr>  s"      6W
9U#$$6Ws   r  r&   r  r  r  r   r  r   r   rng_state_output_r   )r  fx.GraphModuler]   dict[str, fx.Node])rI   r\   r]   torch.device | None)r  r  r]   torch.Tensor)2r  countr   r   r   r   r   r   r   r   r   r   r  r  run_and_save_rng_staterun_with_rng_stater-  r   r.  r  r$   valuesdiscardr  r   rs  r   graphsafe_rng_functionalizationfallback_randomtest_configs*graphsafe_rng_func_ignores_fallback_randomr  r   r  r  r  r   r   r   r   r   copyr  r  r   r   r/  r   r   	recompile)(r0  rT  rU  num_sym_nodesuidr  r  joint_graph_rng_opsfw_graph_rng_opsbw_graph_rng_opsrecomputable_rng_ops_maprI   	base_noder  r  run_and_save_rngr  bw_tangent_start_nodefw_rng_state_outputsr  r  devicesmulti_cuda_devices
ind_config'use_rng_graphsafe_rng_functionalizationr  r  r  r  r  r  stater  
state_namebw_rng_state_nodefw_output_node
fw_outputssym_node_start_idxr   r  s(                                          @rJ   rH  rH  G  s   2 //
C	#$	@ &l3"9-"9-!""((4  V,,		11T[[5E5EE
 yy 00DIIEU4U+II6I&yy1G&yy1G:A2R$/ )  ||--DD//BB **m*<		!$(! = $o
 	
 +-(9??#=#=#=#OPQN(9??#=#=#=#OPQN 6N6U6U6W G OOELL'( W) ''J.. 	
""	
 *** R&&QQ , !**B*I*I*K L	9E"E"G$???? 4"v%-R	.*NN **73%-%9%9#$    #>> &: 	&" !,,#$$,a0	 -  %9$@

5!%11#$$*  2 
 #'))GLL"9
--j9##G,$++E2C 4H **+@A0c<
$,$8$8$D!0DV0L!&&u- B
 **73%11#& * !
 #>> 2 

 --j9##G, 43E !Mj d9??#=#=#=#JKL#((+
 _}<**+()*+,-. 	
 	w'"">2S 43H BA
 43s&   C&V65WAW6
W	
W	
W*	c                >   U R                   R                   H  n[        UR                  [        R
                  R                  5      (       d  M8  UR                  R                  S:X  d  MT  [        U5      (       a  Mf  [        R                  UR                  S'   M     g)z
By default, the partitioner is not allowed to recompute collectives
unless they come from a user-annotated AC region.
See Note [Recomputing collectives in the partitioner]
r   r   N)r   r   r   r   r   r  r  r   r   r%   rE  r   )r0  rI   s     rJ   r:  r:  +  sg     ""((t{{EJJ$9$9::%%);;"4((%5%?%?DIIk" )rM   c                   ^ SU4S jjmU R                   R                   HA  n[        U5      (       d  M  [        U5      (       a  M'  [	        U5      (       a  M9  T" U5        MC     g)a8  
Force save outputs from with_effects nodes wrapping effectful ops.

Effectful ops (registered via _register_effectful_op) should not be recomputed
because they may have arbitrary global side effects (I/O, RNG state, collectives,
etc.). We mark the tensor outputs of with_effects as MUST_SAVE to prevent
recomputation of the effectful op.

The with_effects node returns a tuple (token, result). We recursively find all
leaf outputs extracted via getitem and mark them as MUST_SAVE. Since these are
saved, the with_effects op doesn't need to be recomputed in backward.
c                   > U R                    H}  nUR                  [        R                  L d  M"  T" U5        [	        UR
                  R                  S5      [        [        45      (       a  M`  [        R                  UR
                  S'   M     g )Nr   r   )r  r   r   r   r   r   r   r   r  r%   rE  )rI   r  mark_getitem_outputss     rJ   r  6force_save_effectful_ops.<locals>.mark_getitem_outputsH  s]    JJD{{h...$T*!$))--"6FF-=-G-GDIIk*	 rM   Nr  )r   r   r   r   r  )r0  rI   r  s     @rJ   r;  r;  :  sJ    H ""((D!!"4(((.. & )rM   c                   [        5       n[        U R                  R                  5       H  nUR                  S:X  a  M  UR
                  [        R                  R                  R                  R                  L nU(       a  [        U5      (       a  UR                  UR                  S   5        [        U5      (       aA  UR                  S   U;   a,  [        R                   UR                  S   R"                  S'   M  M  M    g    g )Nr   r   r&   r   )r$   r  r   r   r   r   r   r   r   r   r   r  r  r   r  r%   rE  r   )r0  has_mutation_in_bwrI   is_copy_s       rJ   r<  r<  X  s     5?L++11277h;;%)).."6"6">">>+D11"&&tyy|4*400TYYq\EW5W1A1K1K		!!!+. 6X0 ! 3rM   c                   U R                   [        R                  :w  a  gU R                  S   n[	        U5      [
        R                  La  [        S[	        U5       35      eSUR                  ;  =(       a    U R                  S:H  $ )NFr   z#expected parent to be fx.Node, got rD  r   )
r   r   r   r   r   r   r   r   r   r   )rI   parents     rJ   is_getitem_of_multi_outputr  o  sh    {{h&&&YYq\FF|277"B4<.QRR+J?0JJrM   c               \   U R                   R                   GH  n[        U5      (       a  UR                   Hx  n[        U5      (       d  M  SUR                  ;   d  M'  SUR                  ;   d  M9  UR                  S   UR                  S   :  d  M[  [
        R                  UR                  S'   Mz     UR                  R                  SS5      (       aB  [        S UR                   5       5      (       d  [
        R                  UR                  S'   M  M  GM  SUR                  ;  d  GM  [        S UR                   5       5      (       d  GM9  [        U5      (       a   SUR                  S   R                  ;   a  GMi  U(       d  GMs  [
        R                  UR                  S'   GM     U $ )z
If there are two consecutive checkpointed blocks with no operator in
between, we would still want to stash the tensor at the boundary of
checkpointed blocks. The following pass makes the last output node
non-recomputable to allow for that.
ac_graph_idr   has_backward_hookFc              3  8   #    U  H  n[        U5      v   M     g 7frF   r   r#  s     rJ   rw   )cleanup_recompute_tags.<locals>.<genexpr>  s      E1;t$$r+  c              3  8   #    U  H  n[        U5      v   M     g 7frF   r   r#  s     rJ   rw   r    s     @ZTN4((Zr+  r   )r   r   r   r  r   r%   rE  r   r   r  r   )r0  r  rI   r  s       rJ   r8  r8  x  sH    ""(($

"4((%2%2		-0499]3KK-=-G-GDIIk* # yy}}0%88 E15E B B& *:)C)C		+&'B8* *@TZZ@@@ +400]diiPQlFWFW5W$$ &6%?%?DIIk"W )X rM   c                z  ^^^^=^>^?^@^A^B^C^D^E^F^G^H^I^J^K^L Tc
  [        5       m[        5       mJ[        (       aQ  [        S U R                   5       5      nU[        S TJR                   5       5      -
  n[
        R                  SU5        SNS jm>SNS jm?SNU>U?UJ4S jjmB SS KmHSOUBUUJ4S	 jjmDSPUDUUJ4S
 jjnSOUB4S jjmC      SQUCUJ4S jjnTHR                  " 5       mI[        5       m=SRSSU=UUIUJ4S jjjn	U R                   GH  n
U
R                  S:X  a  M  U
TR                  ;   am  U
TR                  ;  a.  TIR                  U
R                  S-   S[         R"                  SS9  O/TIR                  U
R                  S-   S[         R"                  SS9  M  [%        U
5      (       a/  TIR                  U
R                  S-   S[         R"                  SS9  M  ['        U
5      (       a
  U	" U
S5        O[)        U
5      (       a	  U	" U
S5        U" U
5      nTR+                  U
5      (       a  U(       a  U	" X5        SU
R,                  ;  =(       a    SU
R,                  ;  =(       dB    SU
R,                  ;   =(       a,    [/        U
R,                  S   [0        R2                  5      (       + n[5        U
5      (       a  [7        [9        U
5      5      nS nOhU(       aL  [/        U
R,                  R;                  S5      [<        [>        45      (       a  SnS nO([         R"                  nSnOU" U
TR@                  5      u  pU(       aN  U[         R"                  :X  d
  U[B        :X  a0  TIR                  U
R                  S-   U
R                  S-   USU 3S9  O+TIR                  U
R                  S-   U
R                  S-   US9  U
RD                   H=  nTIR                  U
R                  S-   UR                  S-   [         R"                  SS9  M?     GM     STUBU4S  jjnTRF                  (       GaR  TRH                   GHA  nURD                   Vs/ s H,  nTR+                  U5      (       d  M  TRK                  U5      PM.     nnURD                   Vs/ s H  nTR+                  U5      (       d  M  UPM     nn[M        U5      S:  d  M  U" U[O        U5      5      n[Q        URD                  5       H  nTR+                  U5      (       d  M  TRK                  U5      U:  d  M2  TB" UU5      (       d  MB  UT=;   a  MJ  [
        R                  S!UTRK                  U5      UUTRK                  U5      5        U	" U5        M     GMD     TRR                  (       Ga  [        5       nU R                   GHi  nTR+                  U5      (       d  M  TRK                  U5      U4/nTRK                  U5      n[M        U5      S:  d  MR  [T        RV                  " U5      u  nnUU;   a  M2  URY                  U5        TRK                  U5      US"-   :  aP  [M        U5      S:X  aA  [
        R                  S#UUTRK                  U5      TRK                  U5      5        U	" U5        M  URD                   H[  nTR+                  U5      (       d  M  TB" UU5      (       d  M+  UT=;  d  M3  [T        RZ                  " UTRK                  U5      U45        M]     [M        U5      S:  a  GM  GMl      THR\                  " TIS$S5      u  nnUu  n5mG[        5       n6UI4SE jU5 5        H"  u  mLn7U6R                  UGUL4SF jU7 5       5        M$     [        5       n8U6 H?  u  n9n:U9S SG U:S SH :w  a  [        SIU9S SG  SJU:S SH  35      eU9S SG n-U8RY                  U-5        MA     [        U 5      mE[        U R                  5       V;V
s0 s H  u  n;oU;_M
     sn
n;mF[        UE4SK jU8 5       UF4SL jSM9n<U<T=4$ ! [         a  n[        S5      UeS nAff = fs  snf s  snf ! THR^                   Ga0  n[a        [b        Rd                  5      nS nS mAU Rf                  n  U (       a  U Ri                  S%S&S&S'9O
[k        U 5      mA[m        S(S) UA4S* jS+9  [o        S,S-5      n[q        US.5       n!U!Rs                  TA5        S S S 5        O.! , (       d  f       O = f! [t         a  nS/U S03n S nAOS nAff = fS1Rw                  THRx                  Rz                  R}                  TI5      5      m@[m        S(S2 U@4S3 jS+9  [        TI5      n"U"(       Ga  0 n#S$/n$SUS4 jn%U" H  u  n&n'n(U$R                  U'5        U&S$:X  a+  U%" U'5      n)U#R                  U)/ 5      R                  U(5        MI  U'S:X  a+  U%" U&5      n)U#R                  U)/ 5      R                  U(5        Mz  U%" U&5      U%" U'5      :X  a+  U%" U&5      n)U#R                  U)/ 5      R                  U(5        M  U%" U&5      n*U%" U'5      n+U#R                  U+/ 5      R                  S5U* 35        M     / n,U#R                  5        H8  u  n-n.U,R                  S6U- S735        U. H  n/U,R                  S8U/ 35        M     M:     S1Rw                  U,5      n0S9Rw                  U$5      n1[        TI5      u  n2mKTK(       a  [m        S(S: UK4S; jS+9  U(       a  S<U S13OSn3U2(       a	  U3S=U2 S13-  n3Sn4U(       a  S>n4[        S?U0 S@U1 S1U3 U4 35      Ue[
        R                  SA5        [
        R                  SB[        UHUI4SC j5      5        [        TI5        e S nAf[t         aF    [
        R                  SA5        [
        R                  SB[        UHUI4SD j5      5        [        TI5        e f = fs  sn
n;f )VNc              3     #    U  HS  nUR                   S :X  d  M  [        UR                  S5      (       d  M2  [        UR                  R                  5      v   MU     g7f)r   _overloadpacketN)r   r   r   r   r  r)  s     rJ   rw    solve_min_cut.<locals>.<genexpr>  sK      &
)ww/) -.5dkkCT.U -C++,,)s   AA&Ac              3  8   #    U  H  n[        U5      v   M     g 7frF   )r   ru   rA  s     rJ   rw   r    s      4
5qCFF5r+  z&Ops banned from re-materialization: %sc                X   UR                   [        R                  R                  R                  :w  a  gUR
                  S   n[        R                  R                  R                  U5      u  nnU H6  nUR                  U   nXL a    g[        U[        5      (       d  M/  X;   d  M6    g   gNFr   T)r   r   r   r  auto_functionalizedr   _higher_order_opsauto_functionalizeget_mutable_argsr   r   r  )ab
mutable_opmutable_arg_namesrF  r   r~  s          rJ   !can_fuse_into_auto_functionalized8solve_min_cut.<locals>.can_fuse_into_auto_functionalized  s    88uyy--AAAVVAY
 ##66GG
	

 &D((4.Cx#t$$8 & rM   c                    UR                   [        R                  R                  R                  :w  a  gUR
                  S   nU H*  nUR
                  S   nUc  [        S5      eXC   nXL d  M*    g   g)NFtensors_to_cloner   zkwargs must not be NoneT)r   r   r   r  r  r   r   )r  r  r  r   r   r~  s         rJ   .can_fuse_into_triton_kernel_wrapper_functionalEsolve_min_cut.<locals>.can_fuse_into_triton_kernel_wrapper_functional  sn    88uyy--NNNHH%78%D((8,F~$%>??,Cx & rM   c                  > [        U5      [        R                  :X  a  gT" X5      (       a  gT" X5      (       a  gU R                  [        R
                  L a?  U R                  S   R                  [        R                  R                  R                  L a  gTR                  U 5      =(       a    TR                  U5      $ )NTr   F)r8   r   catr   r   r   r   r   r   r  r  rK   )r  r  r  r  op_typess     rJ   rK   !solve_min_cut.<locals>.is_fusible  s     1),Q229!??HH(((q	  yy%%FFG
 ""1%@(*=*=a*@@rM   r   zANeed networkx installed to perform smart recomputation heuristicsc                n  > TR                  U 5      (       a  g[        U /5      n[        U5      S:  a  UR                  5       nUR                   HQ  nTR                  U5      (       d  T" X#5      (       d    gTR                  U5      (       d  M@  UR                  U5        MS     [        U5      S:  a  M  gr
  )rU   r$   r   r  r  r   r  )rI   r  curr  rK   rR  r  s       rJ   is_materialized_backwards0solve_min_cut.<locals>.is_materialized_backwards   s    D!!v&	)nq --/C		 //55j>S>S##D))MM$'	 " )nq  rM   c                  > U R                   S:w  a  gU R                  [        R                  L a  gU R                  R                  SS5      [        R                  :X  a  g[        R                  (       a  TR                  U 5      (       a  gU R                  [        R                  R                  [        R                  R                  4;   a  gTR                  (       a  TR!                  U 5      (       d  gO?TR#                  U 5      (       a  gTR%                  U 5      (       a  g['        U 5      (       a  gTR(                  (       a8  T" U 5      (       a+  [*        R-                  S	U [/        U R0                  5      5        g
U R2                  S:  a  U R2                  [        R4                  :  a  gTR6                  (       a1  [9        S U R:                   5       5      n[=        U 5      nUS-  U:  a  gg)zRReturns reason string if node should be banned from recomputation, None otherwise.r   Nr   zmarked MUST_SAVEznot in recomputable allowlistz	random opzcompute intensive opznon-builtin opzmaterialized backwards: %s %szmaterialized in backwardi  ztoo far from backwardc              3  z   #    U  H1  n[        U[        R                  5      (       d  M$  [        U5      v   M3     g 7frF   )r   r   r   ri  r  s     rJ   rw   Bsolve_min_cut.<locals>.should_ban_recomputation.<locals>.<genexpr>A  s(      %%.*Q2HYs   #;;r   zreduction op)r   r   r   r   r   r   r%   rE  r   recompute_viewsrU   r   lift_fresh_copyr   
lift_freshr   rX   rR   rO   r  r   r<   r  r   r  dist_from_bwmax_dist_from_bwr   rg  r   ri  )rI   input_tensors_sizeoutput_sizer  min_cut_optionsr  s      rJ   should_ban_recomputation/solve_min_cut.<locals>.should_ban_recomputation  s   77o%;;(***99==d+/?/I/II%!!h&6&6t&<&<;;4//779P9PQQ22++D116 2 !!$''",,T22-(..' 77<U=
 =
 II5tU4::=NO- $):):V=T=T)T* ++!$ %%)YY% " #4.KQ!33%rM   c                r   >^  T R                   S:X  a  g[        UU 4S jT R                   5       5      (       + $ )Nr   Tc              3  6   >#    U  H  nT" TU5      v   M     g 7frF   rZ   )ru   r  rK   rI   s     rJ   rw   9solve_min_cut.<locals>.is_materialized.<locals>.<genexpr>M  s     E*$z$--*s   )r   r  r  )rI   rK   s   `rJ   is_materialized&solve_min_cut.<locals>.is_materializedI  s*    77m#E$**EEEErM   c           
       > [         R                  (       a  X;   a  g[        U 5      n[         R                  (       a(  TR	                  U 5      (       a  [
        R                  S4$ [        U R                  S   [        5      (       a4  [        U R                  S   [        R                  5      (       d  [        S4$ [        US[        [        U R                   S5      S5      -  -  5      nT" U 5      (       a  US4$ US	-  S4$ )
zReturns (weight, cannot_save_reason).

cannot_save_reason is None for finite weights, or a string explaining
why the node cannot be saved for infinite weights.
r  zview op (recompute_views=True)r   z$SymFloat (non-SymInt symbolic value)g?rz  r&   N   )r    treat_parameters_as_free_to_saveri  r$  rU   r  r  r   r   r   r   r   INT_INFr   rS  rT  r'  )rI   rq   mem_szr1  r  s      rJ   get_node_weight&solve_min_cut.<locals>.get_node_weightO  s     333$!!h&6&6t&<&< 88===dii&55dii.== FFF cST%6%6!<a@@A
 4  4<A:t##rM   r  c                F  > TR                  U 5      (       a  gU T;   ak  [        U R                  [        R                  R
                  5      =(       a    U R                  R                  S:H  n[        R                  (       d  U(       d  g[        U 5      (       a  gSU R                  ;   a-  [        U R                  S   [        R                  5      (       a  gTR                  U 5        TR                  SU R                  S-   [        R                   U(       a  SU 3OSS9  g	)
NFr   r   r   _inzcannot recompute: zcannot recomputecapacityreasonT)rU   r   r   r   r  r  r   r   r9  r   r   r   r  add_edger   r  r  )rI   r>  is_collectivebanned_nodesdont_bannx_graphr  s      rJ   ban_recomputation_if_allowed3solve_min_cut.<locals>.ban_recomputation_if_allowedz  s    D!!8 4;;

(=(=> @KK))-??  >>m $DII*TYYu-=u~~"N"N
 	IIXX4:'x0@R	 	 	
 rM   r   _outsinkz;must be available for backward: input required for gradientr<  r;  z3must be computed in backward: required for gradientz+must recompute: marked by checkpoint policyzprimal inputzforward RNG seedr   rD          znon-tensor outputzcannot save: )r=  zdata dependencyc                  > / nU  H,  n[         R                  " UT
R                  U5      US45        M.     [        U5      S:  a  [         R                  " U5      u  pEnU(       d  T
R                  U5      $ UR
                   Hi  nT
R                  U5      (       d  M  T
R                  U5      U:  a  M2  T
R                  U5      UT	" XW5      4nX;  d  MS  [         R                  " X(5        Mk     [        U5      S:  a  M  U$ )zl
Finds the first unfusible node in the chain of nodes starting from
`start_nodes` and returns its position.
Tr   )heapqheappushr   r   heappopr  r   )start_nodes	max_rangesorted_nodesrv   rF  rI   node_is_fusibler  r   rK   rR  s            rJ   find_first_unfusible+solve_min_cut.<locals>.find_first_unfusible	  s    
 9;ANN<)*@*@*CQ)MN  ,!#',}}\'B$A_" --d33

++D11 --d3i? !..t4"4.6C
 .|9 #	 ,!# rM   z1used above/below fusible %s:(%s) -> %s -> %s:(%s)rz  ztoo long %s %s %s %sr   FTr  r  c                     SSS.$ )Nmin_cut_failed_fx_graphr  r  rZ   rZ   rM   rJ   rz   solve_min_cut.<locals>.<lambda>	  s    5 (%rM   c                    > T $ rF   rZ   )fx_graph_strs   rJ   rz   rU  	  s    <rM   r  min_cut_failed_graphz.txtwz(failed to write: )
c                     SSS.$ )Nmin_cut_failed_edge_listr  r  rZ   rZ   rM   rJ   rz   rU  	  s    2$!rM   c                    > T $ rF   rZ   )edge_list_strs   rJ   rz   rU  	  s    }rM   c                f    S H*  nU R                  U5      (       d  M  U S [        U5      *  s  $    U $ )N)r;  rF  )endswithr   )	node_namesuffixs     rJ   get_base_name$solve_min_cut.<locals>.get_base_name	  s8    -F ))&11(CK<88 . ! rM   zdepends on z  :z    - z -> c                     SSS.$ )Nmin_cut_failed_svgr  r  rZ   rZ   rM   rJ   rz   rU  	  s     4$,)rM   c                    > T $ rF   rZ   )svg_contents   rJ   rz   rU  	  s    {rM   zFX graph dump: zMin-cut graph visualization: z[Production debugging: Use tlparse to extract debug artifacts (min_cut_failed_fx_graph, min_cut_failed_edge_list, min_cut_failed_svg)]
a  AOT Autograd failed to partition the joint forward-backward graph.

The partitioner determines which intermediate values to save from the forward pass vs recompute in the backward pass. This error means a value is required for backward, but cannot be saved AND cannot be recomputed.

This is a bug in PyTorch. Please file an issue at https://github.com/pytorch/pytorch/issues

Nodes involved in the conflict:
z

[For PyTorch developers: one of the above constraints is wrong. Either the node should be recomputable, saveable, or not required for backward.]

[Debug: min-cut path] z-Failed to compute min-cut on following graph:rk  c                 l   > SR                  T R                  R                  R                  T5      5      $ Nr[  join	readwriteedgelistgenerate_edgelistnxrC  s   rJ   rz   rU  	  #    		",,"7"7"I"I("STrM   c                 l   > SR                  T R                  R                  R                  T5      5      $ rl  rm  rr  s   rJ   rz   rU  	
  rt  rM   c              3  0   >#    U  H  oTU   4v   M     g 7frF   rZ   )ru   rv   rC  s     rJ   rw   r  
  s     8i$is   c              3  :   >#    U  H  oT;   d  M
  TU4v   M     g 7frF   rZ   )ru   r-  non_reachableus     rJ   rw   r  
  s     Ad=.@fq!fds   	znode_in[:-3]=z != node_out[:-4]=c              3  .   >#    U  H
  nTU   v   M     g 7frF   rZ   ru   rI   name_to_nodes     rJ   rw   r  !
  s     2	d		s   c                   > TU    $ rF   rZ   )r   node_idxs    rJ   rz   rU  !
  s	    (1+rM   r|   )r  r\   r  r\   r]   r:   r[   )rI   r\   r]   
str | None)rI   r\   rq   rj   r]   ztuple[float, str | None])r  )rI   r\   r>  r   r]   r:   )rM  rh   rN  r   r]   r   )rb  r   r]   r   )Jr$   get_default_op_listr;   r   rD   r<   r  networkxImportErrorr   DiGraphr   rl   rm   r?  r   r  r  r   r4   r3   r   r   r   r   rQ  r   floatr   r   r   r   rq   r6  r  r   r   r   r   rS  r   r   rJ  rL  r  rK  minimum_cutNetworkXUnboundedr:   r   handlersowning_moduler  r   r   _get_unique_pathopenwrite	Exceptionrn  ro  rp  rq  _find_infinite_capacity_pathr   
setdefaultrh  visualize_min_cut_graphr   r  r   get_name_to_noder  r~   )Mr   rR  r+  rB  joint_module_opsops_ignoreder,  r8  rD  rI   
ban_reasonis_non_tensor_nodeweightcannot_save_reasonr  rQ  	used_nodeordersfw_usersfirst_unfusible_usevisited
start_nodefusiblestart_orderrF  r  	cut_value	partitionunbounded_excstructured_tracing_enabledfx_graph_filer0  finf_pathnode_constraintsraw_path_nodesrd  	from_nodeto_noder>  base	from_baseto_baseconstraint_linesrb  constraintscconstraints_strraw_path_strsvg_pathlocal_files_msgtlparse_msg	reachablecutsetnbrs	cut_nodesnode_innode_outr@  r9  rA  r  r  r_  rW  rK   r1  r  r~  r  rx  rs  rC  r  rj  ry  sM    ```                                                         @@@@@@@@@@@@@@@@rJ   solve_min_cutr    sY    <"$H% &
#))&
 

 ' 4
$554
 *
 
 	9;G(A A& 9 9vF&$&$4G&$	!&$ &$P zz|H(2L @ !!77h9...9555!!II&!XXX	 "  !!II%!XXP	 "  $
 		E!D	   d(~> &&(/AB
 .d3
##D))j(: "E}DII'EUtyy SDIIe4Dell)S%S 	 t=./F!% $))--.@P0QRR%)"%8")8i;;*&F
 6TXX#579J		E!		F"&'9&:;	   dii%/V1CfUJJD		F"		E!(	   a "R 4 ,,,"44I &OO+D++D1 -	&&t,+   "+!0I4L4LT4R   6{Q&:8S[&Q#!)//2D!0066%2248;NN&y$77</$O%%229=/ %2248 5T:! 3 5P 111'1|%++J++J77''
3Z@2G $00<Kg,"w/3'>C  **3/+2CCG)HH."!..s3!..z: 15IID!0066&sD11 4w1G1G1Mt0TU &) g,"" ,Fb!~~h&I	9F  )I}*4,F8i84AdAA 9 ",I#3B<8CR=( ~-?"O  CRL	i  $ $K0L+4[5F5F+GH+Gic4c	+GHH2	28ML %%Q  O
	H	
R  V%))*<*<%=" %)#'"00	6
   ++!&tD ,  %   0 --CVLMmS)Q% *)) 	6015M	6 		",,"7"7"I"I("ST -	
 09 68&ZN! /7*	7F%%g. ((1D$//b9@@H&(3D$//b9@@H"9-w1GG(3D$//b9@@H !.i 8I+G4G$//<CC%i[1% /7. +-*:*@*@*B&	; ''"YKq(9:$A$++fQCL9 % +C
 #ii(89O!;;~6L %<H$E!Hk !  3 8E/-3"  %B8*B#OO K)a 
 4 ## $) *6b"#-! !!" 	@AT	
 	 ) 	@AT	
 	 )	6 Is   _= 9``<` ` `% n7=
```%n46)m! Ac+c=cm!
c	cm!c
c1!c,'m!,c11I0m!!An4c                   [        S/5      n[        S/ 4/5      nU(       a  UR                  5       u  p4U R                  U5       H  nXQ;   a  M
  X   U   nUR	                  SS5      nU[
        R                  :X  d  U[        :X  d  MC  UR	                  SS5      nX5U4n	XI/-   n
US:X  a  U
s  $ UR                  U5        UR                  XZ45        M     U(       a  M  g)zBFS from source to sink following only infinite-capacity edges.

Returns a list of (from_node, to_node, reason) tuples representing the path,
or None if no such path exists.
r   r=  r   r>  unknownrG  N)
r$   r   popleft
successorsr   r  r  r6  r  r   )rC  r  queuerI   	edge_pathneighbor	edge_datar=  r>  new_edgenew_paths              rJ   r  r  &
  s     ($G <A8R.AQ;RE
--/ ++D1H" x0I }}Z3H488#x7':"x; F3$z1v%#OH%h12 2 %  rM   c                *   U  U 3n[         R                  R                  U5      (       d  U$ Sn[         R                  R                  U  SU U 35      (       a2  US-  n[         R                  R                  U  SU U 35      (       a  M2  U  SU U 3$ )zGet a unique file path, appending a counter if the file already exists.

For example, if "min_cut_failed.svg" exists, returns "min_cut_failed_1.svg".
r&   rF  )ospathexists)	base_name	extensionr  counters       rJ   r  r  G
  s    
 [$D77>>$G
''..I;ay<
=
=1 ''..I;ay<
=
=['9+..rM   c                   SSK n SSKnUR
                  R                  U 5      R                  5       nUR                  U5      S   nUR                  5        He  nXR                  5          UR                  5          S   nUR                  [        U5      5        U[        S5      :X  d  MT  UR                  S	5        Mg     UR!                  5       R#                  S
5      n[%        SS5      n['        US5       n	U	R)                  U5        SSS5        X4$ ! [         a    [        R	                  SSS9   gf = f! , (       d  f       X4$ = f)z~Visualize the min-cut graph to an SVG file.

Returns (path_to_svg, svg_content) tuple. Both are None if pydot is unavailable.
r   NzMInstall pydot to visualize the min-cut graph for debugging: pip install pydotT)exc_info)NNr=  r  redutf-8min_cut_failed.svgrY  )r  pydotr  r<   r  nx_pydotto_pydot	to_stringgraph_from_dot_data	get_edges
get_sourceget_destination	set_labelr   r  	set_color
create_svgdecoder  r  r  )
rC  rs  r  
dot_format	dot_graphedger  rj  r  r  s
             rJ   r  r  V
  s3     %%h/99;J))*5a8I##%//+,T-A-A-CDZPs6{#U5\!NN5! & &&(//8K   0&9H	h		 
   3  [ 	 	
 , 
	   s   D 7D8D54D58
Ec                 |   / [         R                  P[         R                  P[         R                  P[         R                  P[         R
                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                   P[         R"                  P[         R$                  P[         R&                  P[         R(                  P[         R*                  P[         R,                  P[         R.                  P[         R0                  P[         R2                  P[         R4                  P[         R6                  P[         R8                  P[         R:                  P[         R<                  P[         R>                  P[         R@                  P[         RB                  P[         RD                  P[         RF                  P[         RH                  P[         RJ                  P[         RL                  P[         RN                  P[         RP                  P[         RR                  P[         RT                  P[         RV                  P[         RX                  P[         RZ                  P[         R\                  P[         R^                  P[         R`                  P[         Rb                  P[         Rd                  P[         Rf                  P[         Rh                  P[         Rj                  P[         Rl                  P[         Rn                  P[         Rp                  P[         Rr                  P[         Rt                  P[         Rv                  P[         Rx                  P[         Rz                  P[         R|                  P[         R~                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[        R                  P[         R                  P[         R                  P[         R                  P[         R                  Pn [         R                  [         R                  [         R                  /nU[         R                  [         R                  [         R                  [        R                  [         R                  [         R                  [         R                  [         R                  [         R                  /	-  nUnU / [        R                  P[        R                  P[         R                  P[         R                  P[         R                  P[        R                  P[        R                  P[         R                  P[         R                  P[        R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[         R                  P[        R                  P[        R                  P-  n U [         R                  [         R                  /-  n X-  n U [        5       -  n U [         R                  /-  n U [         Vs/ s H  n[        U5      PM     sn-  n [        U 5      n[        [        S[        4      " [         R                  [         R                  [         R                  /5      n[         R                  [         R                  [         R                  [         GR                   [         GR                  [         GR                  [         GR                  [         GR                  [         GR
                  [         GR                  [         GR                  /nXE-  nG[        U[        U5      U[        U5      U5      $ s  snf )N.)r   r  r  r  atan2rP  rS  rT  pow	remainderfmod__and____or____xor__
__lshift__
__rshift__eqnegegtleltrI  bitwise_notceilfloorfracnegreluroundsilutruncr<   log10log1plog2lgammaexpexpm1erferfccosacoscoshsinasinsinhtanatantanhatanhsqrtrsqrtrO  sigmoidsoftplus	thresholdthreshold_backwardclampwherelerpaddcmulgelugelu_backwardrg  mean_grad_sum_to_sizesum_to_sizerJ  totype_asr   r   squeeze	unsqueezersub_to_copyaliasr   slicetrK  broadcast_in_dimexpand
as_stridedpermuteselectru  rL  clone	full_likevarstd_unsafe_viewr   broadcast_tensorsscalar_tensorones	new_zerosr%  arangetriuvar_meanisinfr   fullzerosempty
empty_likeargmaxmaximumiota'_low_memory_max_pool_offsets_to_indicesr  gatherr{  
zeros_liker   r   r$   r   r	   native_dropout	rand_like
randn_likemmconvolutionconvolution_backwardbmmaddmm#_scaled_dot_product_flash_attention'_scaled_dot_product_efficient_attention_flash_attention_forward_efficient_attention_forwardupsample_bilinear2d
_scaled_mmr>   )default_recomputable_opsrecomputable_view_opsrC   mrD   rB   rA   r@   s           rJ   r  r  }
  s   L:L:L: 	L: 	

	L:
 	L: 	L: 	L: 	L: 	L: 			L: 	L: 	L: 	L: 	L: 	L:  	!L:" 	#L:$ 	%L:& 	'L:( 	)L:* 	+L:, 	-L:. 	/L:0 			1L:2 	

3L:4 			5L:6 	7L:8 			9L:: 	

;L:< 			=L:> 	

?L:@ 	AL:B 	

CL:D 	

EL:F 			GL:H 	IL:J 	KL:L 	

ML:N 	OL:P 			QL:R 	SL:T 			UL:V 			WL:X 	YL:Z 			[L:\ 			]L:^ 	_L:` 			aL:b 			cL:d 	

eL:f 			gL:h 	

iL:j 	kL:l 	mL:n 	oL:p 	qL:r 	sL:t 	

uL:v 	

wL:x 			yL:z 	{L:| 			}L:~ 	L:@ 	AL:B 			CL:D 	EL:F 	GL:H 			IL:J 	KL:L 	ML:N 	OL:P 	QL:R 	SL:T 			UL:V 	WL:Z "\\4>>4::F		




 
 %H $!		$!""$! 	

$! 		$!
 	$! 			$! 			$! 	$! 	$! 	$! 	$! 	$! 			$! 	$! 	

$!  	!$!" 	#$!$ 	%$!& 			'$!( 	)$!* 	+$!, 	-$!. 			/$!0 	1$!2 	

3$!4 	5$!6 			7$!8 	9$!: 	

;$!< 	

=$!> 	?$!@ 	A$!B 	C$!D 	

E$!F 	55G$! $L T[[ 99(/!   N1!3A!6 NN!":;HS#X./			dnndoo>J 	!!

0044%%))   #/K()8 + !Os   6d9c                L    0 nU R                    H  nX!UR                  '   M     U$ rF   )r   r   )r   r~  rI   s      rJ   r  r  %  s'    ')L"&TYY rM   c           	        [         R                  nUS:X  a  [        XU5      $ US:X  a  [        XU5      $ US:X  a  [	        XU5      $ US:X  a  [        XU5      $ US:X  aR  [        R                  S5        [        R                  " U UUUS9n[	        UU[        US9R                  [        US	95      $ [        U[        5      (       a  U" XX4U5      u  pS
X4$ [        SU 35      e)Ngreedyilpdpr)   dynamic_memory_budget_dpzdynamic_memory_budget_dp is an experimental solver. It does not guarantee performance improvements. Additionally, it is not guaranteed to be stable.)r   all_recomputable_banned_nodes recorded_knapsack_input_memories recorded_knapsack_input_runtimes)graph_info_provider)knapsack_algomax_mem_budgetrH  z,Not aware of memory budget knapsack solver: )r   activation_memory_budget_solverr*   r+   r(   r)   r<   warningr'   inialize_from_graphr,   get_knee_point_memory_budgetr   r   r   )
r   memoryruntimes
max_memoryrR  r[  SOLVERr^  saved_node_idxrecomp_node_idxs
             rJ   #_optimize_runtime_with_given_memoryrk  ,  s    33Fv<<	5Fj99	46Z88	3	3-f
KK	-	-?	

 0CC#*G-3-5	
 $7**)) + 	
 		
 
F0	1	1*08U+
' ^55I&RSSrM   no_dispatchc                   ^ [        U R                  5      nSU4S jjnU Vs/ s H
  oC" U5      PM     nnU R                  5        Vs/ s H
  oC" U5      PM     nnU R                  X%S9$ s  snf s  snf )Nc                   > [        U TS9$ )Nr]  )r    )dr^  s    rJ   realize_symbol8_remove_symbols_without_guarding.<locals>.realize_symbolc  s    X..rM   )stride)rp  ztorch.SymInt | intr]   r   )r  shapers  new_empty_strided)r   r^  rt  rq  r  rs  s    `    rJ    _remove_symbols_without_guardingrv  `  sk    ME/ )..1^AE.)*4AnQF4u44 /4s   A*A/c                  ^ ^^	 [         R                  nSS jnUS:X  a  gUS:X  ac  [        5          SSKJn  [
        R                  " UT R                  T R                  45      u  mm	UR                  UU	U 4S j5      nUsS S S 5        $ US:X  as  SS	K
Jn  [
        R                  " UT R                  T R                  45      u  mm	U" S
S9 nT R                  " T0 T	D6  S S S 5        WR                  5       n[        US5      $ [        U[         5      (       a  U" T 5      $ [#        SU 35      e! , (       d  f       g = f! , (       d  f       Nf= f)Nc                   [        U [        R                  5      (       aC  [        U R                  S   [        R
                  5      (       a  [        U R                  S   SS9$ [        U [        R                  5      (       aC  [        U R                  S   [        R                  5      (       a  [        U R                  S   SS9$ [        U [        R                  5      (       a-  [        U R                  S   [        R                  5      (       a  g[        U [        R                  5      (       a-  [        U R                  S   [        R                  5      (       a  gU $ )Nr   r\  r]        ?T)r   r   r   r   r   rQ  rv  r   r    r   r   r_  s    rJ   materialize_arg)estimate_runtime.<locals>.materialize_argn  s    a!!j&M&M3AFF5MDQQ277##
166%=%,,(O(OQVVE]T::277##
166%=%..(Q(Q277##
166%=%--(P(PHrM   testingr&   profiler   )benchmarkerc                 (   > TR                   " T 0 TD6$ rF   )r   )r   r   rI   s   rJ   rz   "estimate_runtime.<locals>.<lambda>  s    4;;3O3OrM   flops)FlopCounterModeF)displayz Not aware of runtime estimator: )r   r	   r]   r	   )r   *activation_memory_budget_runtime_estimatorrm  $torch._inductor.runtime.benchmarkingr~  r   tree_mapr   r   benchmark_gputorch.utils.flop_counterr  r   get_total_flopsrS  r   r   r   )
rI   RUNTIME_MODErz  r~  msr  modecounted_flopsr   r   s
   `       @@rJ   estimate_runtimer  k  s   DDL
 y 		"]H!???TYY<TULD&**+OPB ] 
	 <DKK8PQfU+tKK(( , ,,.=!$$	L"8	9	9D!! =l^LMM/ ] ,+s   AD-D>-
D;>
Ec           	       ^ ^^^ ^!^"^#^$^%^&^'^(^)^* US:  d  US:  a  [        SU 35      e[        [        R                  [        R                  [        R
                  [        R                  [        R                  S9n[        R                  (       a  [        USSSSS9nUS:X  a  TR                  $ [        T TU5      u  pEUS:X  a  U$ S-S jm!T!" TR                  5      m(T!" U5      m&T&T(::  a  U$ S.U&U(4S jjnS/U!U&U(4S	 jjm"[        USSSS
9n[        T TU5      u  pT"" U5      U:  a  U$ [        USS9m[        T TT5      u  pT"" U	5      U:  a  U	$ SSKJm#  [        U#4S jTR                   5       5      m%    S0U#U%4S jjnU" U
5      nU Vs/ s H5  nUR                  R!                  SS5      ["        R$                  :X  d  M3  UPM7     nnU Vs/ s H  oU;  d  M
  UPM     nn['        U[(        SS9m [+        T 5      S:X  a  TR                  U-   $ T  Vs/ s H  o" [)        U5      5      PM     snm'T  Vs/ s H  n[-        U5      PM     snm*SSKJm)          S1UU U'U)U*4S jjm$[        R2                  (       Ga  S2U"U$U UU*4S jjnU" S5      U" S5      /nUS   SS  US   SS  :w  a  US   US   4/nU(       a  UR5                  5       u  nnUS   US   -
  S:  a$  UR7                  U5        UR7                  U5        MM  U" US   US   -   S-  5      nUSS  USS  :w  a  UR7                  UU45        USS  USS  :w  a  UR7                  UU45        U(       a  M  UR9                  5         SS KJn  U Vs/ s H  nUS   PM
     nnU Vs/ s H  nUS   PM
     nnUR?                  SS9  URA                  UUSS9  [C        U5       H   u  nnURE                  US UUU   4SSS S!9  M"     URG                  S"5        URI                  S#5        URK                  S$5        URM                  S5        URO                  5       nURQ                  5         [R        RT                  " 5       n[        RV                  b%  [        RV                  n[R        RX                  " USS%9  S&n[Z        R\                  R_                  5       (       aD  [Z        R\                  Ra                  5       (       a!  S'[Z        R\                  Rc                  5        3n[R        Rd                  Rg                  US(U S)[i        5        S*35      nURk                  U5        [l        Ro                  S+U5        T$" UTT S,9S   $ s  snf s  snf s  snf s  snf s  snf s  snf )3Nr&   r   zJThe valid ranges for memory budget are 0 <= m <= 1. The provided value is )r   r   r   r   r   F)r   r   r   r   c                :    [        [        [        U 5      5      S-  $ N    eA)rg  mapri  )r9  s    rJ   estimate_activations_size:choose_saved_values_set.<locals>.estimate_activations_size  s    3x./#55rM   c                   > U S-  TT-
  -  $ r  rZ   )szmax_act_sizemin_act_sizes    rJ   get_normalized_size4choose_saved_values_set.<locals>.get_normalized_size  s    S\L899rM   c                &   > T" U 5      T-
  TT-
  -  $ rF   rZ   )activationsr  r  r  s    rJ   get_mem_ratio.choose_saved_values_set.<locals>.get_mem_ratio  s"    )+6E<'
 	
rM   )r   r   r   )r   )get_node_storagec              3  4   >#    U  H  nT" U5      v   M     g 7frF   rZ   )ru   rI   r  s     rJ   rw   *choose_saved_values_set.<locals>.<genexpr>  s     TCS4 0 6 6CSrd  c                   > U  Vs/ s H>  nUR                   [        S5      :  d  M  T" U5      T;  d  [        U5      (       d  M<  UPM@     sn$ s  snf r  )r'  r   r  )rA  rA  r  input_storagess     rJ   get_recomputable_banned_nodes>choose_saved_values_set.<locals>.get_recomputable_banned_nodes  sX    
 "
! S)	  %Q'~=03 !
 	
 
s   AAAr   Trl  rl  c                  > T" 5          [        UTT[        U S5      UT5      u  nnnS S S 5        [        5       nW H  n UR                  TU   5        M     UR                  T5      (       d  [        S5      e[        UUTU5      u  p[        (       a+  [        UTWUWT V
s/ s H  n
[        U
5      PM     sn
TTUS9	  UW4$ ! , (       d  f       N= f! [         a     M  f = fs  sn
f )Nr   z:dont_ban must be a subset of all_recomputable_banned_nodes)	r   r[  saved_node_idxsrecomputable_node_idxsexpected_runtimememories_banned_nodes normalized_memories_banned_nodesruntimes_banned_nodesmin_cut_saved_values)rk  rS  r$   r  BaseExceptionissubsetr   r  r;   r   ri  )memory_budgetrR  r   r  r  r  rB  r@  r9  rF  rA  aggressive_optionsr[  r  rm  r  s              rJ   get_saved_values_knapsack:choose_saved_values_set.<locals>.get_saved_values_knapsack  s    ]
 4%%M1%-	 &	  )3)C:3?@ *   !>?? L  (	
 ! 4'.K /'=!1)F')FAHQK)F' 2G&;%1 ---] ]$ ! *'s#   C C"C%
C
C"!C"c                F   > T" U TTS9u  pU [        T5      U-
  T" U5      4$ )N)rR  r   )rg  )r  r9  r  r  r  r   rR  r  s      rJ   estimate_for_budget4choose_saved_values_set.<locals>.estimate_for_budgetI  s=    -FYK.*L )*-==l+ rM   rH  ry  gMbP?r4  )
      )figsizeo)markerz.4fzoffset points)r   r  center)
textcoordsxytexthazMemory Budgetz Runtime of Recomputed Componentsz:Pareto Frontier of Memory Budget vs. Recomputation Runtime)exist_okr  _rank_memory_budget_paretorF  r  z%Generated Pareto frontier curve at %s)r  rR  r   )r9  rh   r]   r  )r  r  r]   r  )r  rh   r]   r  )rA  rj   r]   rh   )r  r  rR  rf   r   fx.Graphr]   ztuple[list[fx.Node], float])r  r  r]   ztuple[float, float, float])8r   r   r   ban_recompute_used_far_apart!ban_recompute_long_fusible_chains#ban_recompute_materialized_backwardban_recompute_not_in_allowlistban_recompute_reductionsaggressive_recomputationr   ri   r  torch._inductor.fx_utilsr  r$   r   r   r%   rE  r~   ri  r   r  torch.utils._mode_utilsrm  visualize_memory_budget_paretor  r   sortmatplotlib.pyplotpyplotfigureplotr  annotatexlabelylabeltitlegridgcfshowr  getcwdmemory_budget_pareto_dirmakedirsr   r  r  is_initializedget_rankr  rn  r1   savefigr<   rb  )+r   rR  r  r+  runtime_optimized_saved_valuesrF  r  more_aggressive_optionsmore_aggressive_saved_values%aggressive_recomputation_saved_valuesrA  r  recomputable_banned_nodesrA  must_save_nodesrI   r  optionsbisectslhsrhsmidpltitemx_valuesy_valuestxtfigfig_dirrank_suffixfig_namer  r[  r  r  r  r  r  r  r  r  rm  r  s+   ``                             @@@@@@@@@@@@rJ   choose_saved_values_setr    s   
 qMA-XYfXgh
 	
 $$AA#)#K#K%+%O%O & E E88O &&!"'',).$)
 (5)%" --6 -Y-=-=>L,-KLL|#--: :
 

 &##(%*	 '4Y 7'#  12]B++  % ;HY 2;7) :;mK449T9CSCSTTN
)
	
 
  !>l K +*A66::k5)-=-G-GG 	
*   -!,a0H,  ! %+!x%! ()Q./112O2OQHQK(2O ,I+H4+H 41.1.)11.@H1.	$1. 1.f ,,,	 	 's+-@-EF1:ab>WQZ^+
GAJ/0G";;=Sq6CF?T)NN3'NN3')3q6CF?a*?@qr7c!"g%NNC:.qr7c!"g%NNC:. ' 	'(/0DG0(/0DG0 	

7
#8C0  )FAsLLs)hqk"*   * 	

?#

56		NOggi
))+**655GKK$/))++0A0A0P0P0R0R"5#4#4#=#=#?"@AK77<<+K=:L:N9OtT
 	H;XF %#yk	 	m
!n 10s0   2U)U)	U.U.U38U8;U=Vc                  ^^ SSK Jm  SS jnSU4S jjn[        R                  R	                  5       (       Gaz  [        R                  R                  5       (       GaV  [        R                  R                  5       S:  Ga3  U" U 5      (       Ga%  U" U 5      (       Ga  [        5          T" 5          U Vs/ s H  oDR                  PM     sn/n[        [        R                  R                  5       5       Vs/ s H  n/ PM     nn[        R                  R                  XuS   5        [        U 5      n/ n	0 n
[        U5       H|  u  pU Vs/ s H  oU   PM	     nnSnU HF  n[        U5      nUU-  nU[        R                  R                  5       :X  d  M7  UU
UR                  '   MH     XS'   U	R                  U5        M~     [        R                   " U	[        R                  R"                  R%                  5       S9n[        R                  R'                  U[        R                  R"                  R(                  R*                  S9  [-        [        R.                  " U5      R1                  5       5      nS	U S
U
 3m[3        SS U4S jS9  UU    Vs/ s H  nUU   PM
     nnS S S 5        S S S 5        U$ U$ s  snf s  snf s  snf s  snf ! , (       d  f       N.= f! , (       d  f       U$ = f)Nr   )unset_fake_temporarilyc                    U R                    HT  n[        UR                  [        R                  R
                  5      (       d  M8  UR                  R                  S;   d  MT    g   g)N>   c10d_functionalr   TF)r   r   r   r   r  r  r   )r   rI   s     rJ   has_collectives3_sync_decision_cross_ranks.<locals>.has_collectives  sM    %%DUZZ22 ++''+RR	 &
 rM   c                  >^ SR                  S U R                   5       5      n[        R                  " UR	                  S5      5      R                  5       n[        [        R                  R                  5       5       Vs/ s H  nS PM     snm[        5          T" 5          [        R                  R                  TU5        S S S 5        S S S 5        [        U4S jT 5       5      $ s  snf ! , (       d  f       N0= f! , (       d  f       N9= f)N/c              3  8   #    U  H  oR                   v   M     g 7frF   r  )ru   r   s     rJ   rw   E_sync_decision_cross_ranks.<locals>.has_same_nodes.<locals>.<genexpr>  s     >,=qFF,=r+  r  c              3  4   >#    U  H  nTS    U:H  v   M     g7fr  rZ   )ru   r   
all_inputss     rJ   rw   r    s     :z!:a=A%zrd  )rn  r   hashlibsha256encode	hexdigestr>  r   r  get_world_sizerm  all_gather_objectr  )r   node_strri   rF  r   r  s       @rJ   has_same_nodes2_sync_decision_cross_ranks.<locals>.has_same_nodes  s    
 88>K,=,=>> 89CCE$)%*;*;*J*J*L$MN$Mqd$MN
]24//
FC 5] :z:::	 O44]]s*   C(C>"!C-C>-
C;	7C>>
Dr&   z
total size)r  r,  zpicked_rank_idx=z, saved_nodes of current rank=r  c                     SSS.$ )N)aot_joint_graph_sync_decision_cross_ranksr  r  rZ   rZ   rM   rJ   rz   ,_sync_decision_cross_ranks.<locals>.<lambda>  s    G (%rM   c                    > T $ rF   rZ   )sync_decision_cross_ranks_strs   rJ   rz   r    s    #@rM   r  )r   torch.fx.Graphr]   r:   )torch._subclasses.fake_tensorr  r   r  r  r  r  rm  r   r>  r  r  r  ri  r  r   rk  distributed_c10d_get_object_coll_device
all_reduceReduceOpMAXr   argminr  r   )r   r9  r  r  r   objectsrF  saved_ops_names_all_ranksr~  saved_sizessaved_ops_with_sizesr@  saved_ops_namesop_namesaved_nodes
saved_sizerI   size_of_nodesaved_sizes_tensorpicked_rank_idxrv   r  r  s                        @@rJ   rG  rG    s    E; 	&&((,,..,,.2K((;'']24(45156G!%"3"3"B"B"DE:EqE & : //0IST:V+K8L%'K35 (12K(L$DSTOG4OT
'D#+D>L,.Je//88:::F,TYY7	 (
 6@\2"":. )M "'((99QQS" (("u'8'8'I'I'R'R'V'V )  "%,,/A"B"G"G"IJO.>>OOm  oC  nD  -E) A *C?)S)SAQ)S  Q 5]X <W 6: U:Q 54]]X sb   'K/K
4J6	-K
6J;AK
	K 
9K
C=K
K K
"K6K


K	K
K*c                2   SnU(       a  SOSn[        [        U R                  R                  SS95      5      nU R                  R                  S[        R
                  R                  R                  S9 GH  n[        XR                  S   R                  5      n[        U[        R                  5      (       d  MG  / nUR                  R                  SS9 H  nX8R                  ;   d  M  U R                  R                  U5         U R                  R!                  U SU 35      n	US	-  nUR"                  S
   U	R"                  S
'   U	nUR%                  U	5        SSS5        M     U(       d  M  U R                  R                  U5         U R                  R'                  S[        R
                  R                  R                  / UR                  QUQ70 5      n
UR)                  U
SS9  SSS5        UR"                  R+                  S5      nU(       a9  Uu  p/ UQU Vs/ s H  oR"                  S
   PM     snQ7nUU4W
R"                  S'   U R                  R-                  U5        GM     U $ ! , (       d  f       GM  = f! , (       d  f       N= fs  snf )u  
Graph-safe RNG lets torch.compile use CUDA Graphs for graphs with RNG ops.
For graphs without HOPs, the partitioner adds placeholder nodes
fwd_rng_state_* and bw_rng_state_* to the forward and backward graphs. At
runtime, the AOTDispatcher retrieves these RNG states and passes them to the
compiled graphs.

This works well for no-HOP graphs. With HOPs, the partitioner runs
recursively: it first partitions the HOP (producing forward/backward HOP
subgraphs) and then stitches them back into the outer joint graph. For HOPs
that contain RNG ops, the outer joint graph now includes HOP subgraph
modules with extra RNG placeholders. We must thread these placeholders
through the outer module partitioned forward and backward graphs—this
function does exactly that. It collects the RNG placeholder nodes from the
HOPs and creates corresponding placeholders in the outer forward and
backward graphs.

There is a catch: for a short period, the joint graph is in a “bad” state.
The HOP subgraphs expect additional inputs (because of the new
placeholders), but the outer graph call sites don't yet provide them. We
can't fix this in the joint graph because the joint graph's input signature
is fixed (primals, tangents). As a compromise, we keep the joint graph in
somewhat of a bad state for some time and, once the outer forward and
backward graphs are partitioned, insert the corresponding RNG placeholders
and wire up the calls.
r   r  r  r   r,  r   )r   r   rF  r&   r   NT)propagate_metaeager_input_vals)r.  r  r   r-  r   r   r  invoke_subgraphr   r   r   r   r   r  r   rH  r   r   r   r  r  r   r  )moduler  r  
rng_string
last_inputhop_noder   new_rng_inputsplaceholder_noder  new_hop_node_with_fixed_args
eager_vals
eager_argseager_kwargsinpnew_eager_argss                   rJ   rK  rK    sO   < I$/_Jhv||66-6HIJJLL++599#9#9#I#I ,  6==#3#:#:;h//,.N$,NN$=$=$=$O !6!66  55jA$*LL$<$<)l!I;7%	 "Q	0@0E0Ee0L	u-%.
&--i8 BA	 %P ~\\11(;39<<3K3K'		..>>9(--9.9	40 224T 3  < &]]../AB
/9,J&#&5CD^c((5/^D&N
 '$M0556HI ''1Y\ MI BA <;" Es    AI0A J J0
J 
J	c           	       ^^^^ [        U R                  5      m[        5       mU R                  R                   Hy  nUR                  S:X  a"  SUR
                  ;   a  TR                  U5        O![        U5      (       a  TR                  U5        UT;   d  M^  TR                  UR                  5        M{     [        [        [        U R                  R                  5      5      n[        [        [        U R                  R                  5      5      nXE-   n[        XS9u  pxpTR                  5       nTR                  S U 5       5        [!        U R                  XgU	S5      n[        U4S jUR                   5       5      m[        UU4S jU R                  R                   5       5      n[        U4S j[#        U5       5       5      nS	n0 nU R                  R                   H  nUT;   d  M  UUU'   US
-  nM     [%        UTTUUUU5      $ )Nr   tangentsr  c              3  R   #    U  H  oc  M  UR                   S:w  d  M  Uv   M     g 7f)Nr   r,  )ru   r  s     rJ   rw   !classify_nodes.<locals>.<genexpr>U  s"      aADDH4D;s   ''	'r   c              3  f   >#    U  H&  nUR                   S :w  d  M  TUR                     v   M(     g7fr  r  r}  s     rJ   rw   r5  [  s/      8,D77h 	 TYY,s   11c              3  H   >#    U  H  nUT;  d  M  UT;  d  M  Uv   M     g 7frF   rZ   )ru   rI   rl   r   s     rJ   rw   r5  `  s1      6,D(( 	-19J-J 	,s   
""	"c              3  <   >#    U  H  u  pUT;   d  M  Uv   M     g 7frF   rZ   )ru   rA  pr  s      rJ   rw   r5  e  s!      -.da!7T2T.s   	r   r&   )r  r   r$   r   r   r   r  r   r  r  r  r  r4   r3   r6  r  r	  r  rf   )r0  r  r1  rI   r   r  ri   r2  r3  r4  r5  rm   forward_only_graphrn   rq   fw_cntrp   r~  rl   r   s    `               @@@rJ   r=  r=  8  s   
 $L$6$67L-7\""((77m#
dkk(A!!$'!$''!!$'$$$$TZZ0 ) 
L,>,>,D,DEFM!&)<l>P>P>V>V"WX3F O CK/ )--/   <F1BI .8 8&,,8 .
 ,6 6 &&,,6 ,O
 #- -.- # FH""(($$#HTNaKF ) # rM   )r  c          	     	   U R                   R                  5         U R                  5         U R                   n[        R                  (       a  [        U5      nX`l         U R                   n[        U 5      n[        U 5      n	U(       a
  [        U SS9n [        R                  (       d  [        U 5        [        U 5        [        U 5        Uc  / n[        XU5      n
[        U
R                  5      S:X  a  [!        U UUUU
R"                  S9$ [%        U R                   R&                  5       H  nUR(                  S:X  a  [+        S5      Ul        M%  U
R/                  U5      (       d	  SUl        MD  [+        S5      Ul        UR0                   H+  n[3        UR,                  UR,                  S-   5      Ul        M-     M     [        R4                  nUR&                   HC  n[7        UR8                  R;                  S	S5      [<        5      (       d  M4  UR8                  S	   n  O   [?        UU
US
9n[        R@                  (       a  [A        X~5      n[C        [E        [F        U5      5      n[C        [E        S U5      5      n[I        U UUUU
R"                  S9u  nnU(       a!  U	(       a  [K        U UU[        U5      5      u  nn[M        U5      n[        RN                  (       a  SSK(J'n  U" UUUU
R"                  5        [S        U5      n[S        U5      n[U        USS9n[U        USS9n[V        (       Ga  [Y        U Vs/ s H  n[[        U5      []        U5      4PM     sn5      n[_        S U 5       5      S-  n[`        Rc                  SU5        [`        Rc                  SU5        [e        S UR                   R&                   5       5      n[e        S UR                   R&                   5       5      nUU-  n[g        [*        5      nUR                   R&                   H\  nURh                  U;   d  M  [k        URl                  S5      (       d  M2  U[]        URl                  Rn                  5      ==   S-  ss'   M^     [`        Rc                  S[        U5      [        U5      [        U5      5        [Y        URq                  5       [r        Rt                  " S5      SS9n[`        Rc                  SU5        UU4$ s  snf )a(  
Partitions the joint graph such that the backward recomputes the forward.
Recomputing helps in trading off memory bandwidth with computation.

To create the fwd and bwd graph, we copy the joint graph, manually set the
outputs to just original forward or backward outputs. And then we run the
resulting graphs through dead code elimination.

.. warning::
    This API is experimental and likely to change.

Args:
    joint_module(fx.GraphModule): The joint forward and backward graph. This
        is the result of AOT Autograd tracing.
    _joint_inputs: The inputs to the joint graph. This is unused.
    compiler: This option determines the default set of recomputable ops.
        Currently, there are two options: ``nvfuser`` and ``inductor``.
    recomputable_ops: This is an optional set of recomputable ops. If this
        is not None, then this set of ops will be used instead of the
        default set of ops.
    num_fwd_outputs: The number of outputs from the forward graph.

Returns:
    Returns the generated forward and backward Fx graph modules.
Fr  Nr   )r1  r  rq   r   r  r&   r  )r  c                "    [        U 5      (       + $ rF   r/  )rv   s    rJ   rz   5min_cut_rematerialization_partition.<locals>.<lambda>  s    [^);rM   r0  r2  r4  Tc              3  8   #    U  H  n[        U5      v   M     g 7frF   )ri  r  s     rJ   rw   6min_cut_rematerialization_partition.<locals>.<genexpr>  s     'J\\r+  z'Theoretical Activations Stored: %.2f GBz,Theoretical Per Activation Storage Sizes: %sc              3  \   #    U  H"  oR                   S :X  d  M  UR                  v   M$     g7fr   Nr  r)  s     rJ   rw   r@    #      %
"7$77o;UIDII"7r  c              3  \   #    U  H"  oR                   S :X  d  M  UR                  v   M$     g7frB  r  r)  s     rJ   rw   r@    rC  r  r  z# remat/fw/bw: %d/%d/%drl  zCount of Ops Rematerialized: %s);r   r   r  r   cser7   r   r   r8  r9  r:  r;  r<  r=  r   rl   rV  rq   r  r   r   r   r'  r   r  rT  activation_memory_budgetr   r   r   r  r  rG  r  r  r   r  rH  rI  r3  rJ  r9   rK  r;   r~   ri  r   rg  r<   r  r$   r   r   r   r   r  rh  r   ro  )r0  rL  compilerr1  r  r   	cse_graphr   rP  rQ  rR  rI   r  r  r9  r  rT  rU  r3  rA  sorted_sizestotal_activations_size_gbfw_module_nodesbw_module_nodesremat_nodescountsrematerialized_opss                              rJ   r7  r7  y  s;   D **,D zz &	&$$K!5l!C%=l%K"!-lQVW::|,\*|,$,(*%_I 9&&'1, +*G(1(M(M
 	
 ++11277h #CD))$// !D #CD

$'(9(94;L;Lq;P$Q! # 3 33M!!diimmOT:EBB IIo6M " +#L ((1+L6+|<=O;\JKL 4''$-$I$IIy ")#8iC4H$ Iy 4I>I **	
 	%11		
 y)Iy)I.yeLI.ydKIlKlSV4lKL %('J\'J$JS$P!:<UV 	?N$ %
"+//"7"7%
 
 % %
"+//"7"7%
 
 &7!,S!1OO))DyyK'GDKKAR,S,Ss4;;6678A=8 * 	%  		
 $LLN 3 3A 6
 	24FGi= Ls   2 S*c                "   U(       aZ  [         R                  " U R                  5      n[        R                  " X5      n U R                  R
                   H
  n0 Ul        M     [        R                  R                  U5      u  pU
(       d  S[        R                  -   n
[        R                  SX5        [        R                  " U UUUS9nUR!                  5       n[#        USU
R%                  S5      -   5      nU	 U
 3nUc	  U" U5        g U" XS9  g )Nrr  zWriting FX graph to file: %s%s)parse_stack_tracedot_graph_shapewrite_)prog)r  deepcopyr   r   r  r   r   r  r  splitextr   torch_compile_graph_formatr<   r  r#   FxGraphDrawerget_main_dot_graphr   lstrip)tracedfnamefigname
clear_metarT  rQ  rR  r  rI   r  extgr   write_methods                 rJ   
draw_graphrb  %  s     MM&,,/	2LL&&DDI '  'IDF555HH-t9""+'		A 	
A1hC89LfSENE|UU&rM   r[   )r   r  r]   r:   )rI   r\   r]   r   )r   r\   r]   fx.Node | None)rI   r\   r]   rc  )rI   r\   r   zdict[fx.Node, Any]r]   rc  )NF)r   r  ri   rh   r   rh   r   zlist[AOTOutput]r   r  r  r:   r]   r  )r0  r  r1  r   r]   zEtuple[list[fx.Node], list[fx.Node], list[AOTOutput], list[AOTOutput]])r9  rh   r   r   r]   r  )r?  z#list[fx.Node] | tuple[fx.Node, ...]r]   r   )g      @r  r   )r   r  rI   torch.fx.NoderS  r  rT  r  rU  r   r]   rd  )r   r  rI   rd  r\  rd  ra  torch.dtyperN  r  r`  r  rU  r   r]   rd  )rk  r  r]   r  )r]   zlist[torch.dtype])rI   rd  r]   r:   )r]   re  )rv  re  r]   ztuple[float, float])r   r  r]   r  )r  r  r  r  r  r  r]   r  rF   )
r9  rh   r  r  r  r  rq   OrderedSet[fx.Node] | Noner]   r  )r0  r  r9  rh   r  rh   r1  r   rq   rf  r]   %tuple[fx.GraphModule, fx.GraphModule])r0  r  rL  r	   r1  r   r  list[int] | Nonerq   rf  r]   rg  )ri  r   rv  re  r]   r   )r   r  r]   r  )r]   z!list[torch._ops.OpOverloadPacket])r   ztuple[Any, ...]r}  ro   r]   zlist[tuple[fx.Node, int]])r  r  r]   r  )rT  torch.fx.GraphModulerU  ri  r  rd  r  rd  r  ztorch.devicer  r   r  rd  r  rd  r]   z#tuple[torch.fx.Node, torch.fx.Node])
r0  r  rT  r  rU  r  r  r   r]   rg  )r0  r  r]   r  )r0  r  r  r:   r]   r  )
r   r  rR  rf   r+  r   rB  rf  r]   z)tuple[list[fx.Node], OrderedSet[fx.Node]])rC  nx.DiGraph[str, dict[str, Any]]r]   z!list[tuple[str, str, str]] | None)r  r   r  r   r]   r   )rC  rj  r]   ztuple[str | None, str | None])r]   r>   )r   r  r]   r  )r   r  re  list[float]rf  rk  rg  r  rR  rf   r[  rh   r]   z"tuple[float, list[int], list[int]])r   r  r^  r   r]   r  )rI   r\   r]   r  )r&   )r   r  rR  rf   r  r  r]   rh   )r   r  r9  list[torch.fx.Node]r]   rl  )r&  r  r  r:   r]   r  )r0  r  r  z	list[int]r1  r   r]   rf   )r  )r0  r  rL  r	   rG  r   r1  r   r  rh  r]   rg  )fx_graphTNFN)r[  ri  r\  r   r]  r   r^  r:   rT  zstr | list[str] | NonerQ  r:   rR  r  r]   r  )
__future__r   r  r   r  rJ  r  loggingr  r   r  os.pathr  r5  rn  r   r   collections.abcr   dataclassesr   r   typingr	   r
   r   torch._inductor.inductor_primstorch.distributedtorch.fxr   torch.utils._pytreeutils_pytreer   torch._dynamo.utilsr   r   ;torch._functorch._activation_checkpointing.ac_logging_utilsr   $torch._functorch._aot_autograd.utilsr   torch._inductorr   r  !torch._inductor.custom_graph_passr   r   "torch._library.fake_class_registryr   torch._library.utilsr   torch._loggingr   r   torch._logging._internalr   r  r   %torch.fx.experimental._backward_stater   "torch.fx.experimental.proxy_tensorr   r   torch.fx.experimental.sym_noder   r   %torch.fx.experimental.symbolic_shapesr   r   r   r    r!   r"   torch.fx.passesr#   torch.utils._ordered_setr$   torch.utils.checkpointr%   r  -_activation_checkpointing.graph_info_providerr'   "_activation_checkpointing.knapsackr(   r)   r*   r+   ,_activation_checkpointing.knapsack_evaluatorr,   _aot_autograd.descriptorsr-   r.   r/   _aot_autograd.functional_utilsr0   _aot_autograd.logging_utilsr1   _aot_autograd.utilsr2   r3   r4   r5   r6   compile_utilsr7   r8   r9   r  rs  sympydebug_partitionerr;   rc   	getLoggerr^   r<   r   r   rK  r>   rf   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r  r  r  r  r   r   r6  r;  rB  r]  rg  rm  rw  r~  r  r  r  r  r  r  r  rV  r   r6  rY  ri  rq  cacher{  r  rI  r  rH  r:  r;  r<  r  r8  r  r  r  r  r  r  rk  r  rm  rv  r  r  rG  rK  r=  r7  rb  rZ   rM   rJ   <module>r     s   "         	  	  * $ * %  %   $ $ < A 5 @ + 7 . A ? H L  ) / 3  L  L 
 A ;  I H  %66 t 6''1^ 1yy~~		 > > >2      B    I 2-
	 H  $)lll l #	l
 l "l l^XCBJK5J J69JJJ$; KK
K 
K 
	K
 K K\C!C!
C! C! 	C!
 C! C! C! C!L9"G45	>GBMG`WWW *W 
	W| ?C	,W,W,W ,W "<	,W
 
,Wj ?C`" `"`" #`"
 `" "<`" +`"P 7;>BV  V V  	V 
 $4V  "<V  +V r c(":R  "P
P&8PPK\[*#[*#[* [* 	[*
 [* [* "[* "[* )[*|a  a a  a  	a 
 +a H@'<.K5 5;?55x ,0	s	&s	&s	& #s	& )	s	&
 /s	&l-&B/$!-$!"$!NeP-T-T-T -T 	-T
 -T $1-T (-T` 05*N` z	z	z	 z	 	z	zNN/BNNbOO)-OOd> >#,> > 	>H i  7;i  i i  i 
 i  $4i  +i ^ #'#"&' '' ' 	'
 !' '  ' 
'rM   