
    ȅi                       % 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  S SKJr  S SKJrJr  S SKJrJr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,  S SK-J.r.  S SK/J0r0  S SK1J2r2J3r3  S SK4J5r5J6r6  S SK7J8r8J9r9J:r:J;r;J<r<J=r=  S SK>J?r?  S SK@JArA  S SKBJCrC  SSKDJ'r'  SSKEJFrF  SSKGJHrHJIrIJJrJJKrK  SSKLJMrM  SSKNJOrOJPrPJQrQ  SSKRJSrS  SSKTJUrU  SSKVJWrWJXrX  SSKYJZrZJ[r[J\r\  \(       a  S SK]r]\'R                  r_\`\aS'   \R                  " \c5      rd\R                  \aS'   \R                  R                  rg\R                  R                  rh\ " S S5      5       ri\ " S  S!5      5       rj\ " S" S#5      5       rkS$\R                  S%\`4S& jrmS'\R                  S%\`4S( jroS'\R                  S%\`4S) jrpS$\R                  S%\q4S* jrr " S+ S,5      rsS- rt\s" 5       ru  SS.\R                  S/\w\R                     S0\w\R                     S1\w\O   S2\\x   S3\`S%\R                  4S4 jjryS$\R                  S%\`4S5 jrzS$\R                  S%\`4S6 jr{S$\R                  S%\`4S7 jr|S$\R                  S%\`4S8 jr}S$\R                  S%\`4S9 jr~S$\R                  S%\`4S: jrS$\R                  S%\`4S; jrS$\R                  S%\`4S< jrS$\R                  S%\`4S= jrS$\R                  S%\`4S> jrS$\R                  S%\`4S? jrS$\R                  S%\`4S@ jrSA\R                  S%\\w\R                     \w\R                     \w\O   \w\O   4   4SB jrSC\w\R                     SD\x4SE jrSF\\w\R                     \\R                  SG4   4   S%\q4SH jr   SSI\R8                  R                  S$\R8                  R                  SJ\SK\SL\q4
SM jjrSI\R8                  R                  S$\R8                  R                  SN\R8                  R                  SO\GR                  SP\SQ\SL\qS%\R8                  R                  4SR jrSS\GR                  S%\4ST jrS%\w\GR                     4SU jrS$\R8                  R                  S%\`4SV jrS%\GR                  4SW jrSX\GR                  S%\4SY jrSI\R8                  R                  S%S4SZ jrSI\R8                  R                  S%S4S[ jrS\\R                  S]\R                  S^\\x\R                  4   S%S4S_ jr SSC\w\R                     S\\R                  S]\R                  S`\\A\R                        S%S4
Sa jjrSSb.SA\R                  SC\w\R                     Sc\w\R                     Sd\qS`\\A\R                        S%\\R                  \R                  4   4Se jjrSSSf.SA\R                  Sg\\w\q      S`\\A\R                        S%\\R                  \R                  4   4Sh jjr\q" Si5      rSj\qS%\q4Sk jrS$\R                  S%\q4Sl jrSI\R                  4Sm jr\GR>                  Sn 5       rSo\\R                  \q4   S%\w\\R                  \q4      4Sp jrSq\R                  S%\R                  4Sr jrSs\R8                  R                  St\R8                  R                  Su\R8                  R                  Sv\R8                  R                  Sw\GRF                  Sx\qSy\R8                  R                  Sz\R8                  R                  4S{ jrSA\R                  Ss\R                  St\R                  S|\qS%\\R                  \R                  4   4
S} jrSA\R                  S%S4S~ jrSA\R                  S%S4S jrS rSA\R                  S\`S%\R                  4S jr SS.\R                  S\jS\kS\\A\R                        4S jjrS rS%\i4S jrSI\R                  4S jrS.\R                  S\w\   S\w\   S\S\jS\w\R                     S%\\\w\q   \w\q   4   4S jrS SKJr  S\GR                  S\qS%\GR                  4S jrS r SS.\R                  S\jS%\w\R                     4S jjrS.\R8                  R                  SC\w\R8                  R                     4S jrS rS r SSS.SA\R                  Sg\\w\q      S%\\R                  \R                  4   4S jjjr     SS\R8                  R                  S\xS\xS\`S\\\x\w\x   4      S\`S\\x   S%S4S jjrg)    Ndefaultdict)Callable)	dataclassreplace)AnyOptionalTYPE_CHECKINGUnion)countersis_node_meta_valid)(create_structured_trace_for_min_cut_info)config)
is_builtin)trace_structured)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)get_cuda_generator_meta_valis_with_effects)fx_graph_cseget_aten_targetraise_getitemsAOT_PARTITIONER_DEBUGlogc                      \ rS rSr% Sr\\   \S'   \\   \S'   \\   \S'   \\   \S'   \\   \S'   S\R                  4S	 jr
S\R                  4S
 jrS\R                  4S jrS\R                  4S jrS\R                  4S jrSrg)OpTypesN   z8Class for keeping track of different operator categoriesfusible_opscompute_intensive_ops
random_opsview_opsrecomputable_opsnodec                 2    [        U5      U R                  ;   $ N)r0   r7   selfr<   s     W/home/james-whalen/.local/lib/python3.13/site-packages/torch/_functorch/partitioners.py
is_fusibleOpTypes.is_fusibleX   s    t$(8(888    c                 2    [        U5      U R                  ;   $ r>   )r0   r8   r?   s     rA   is_compute_intensiveOpTypes.is_compute_intensive[   s    t$(B(BBBrD   c                 2    [        U5      U R                  ;   $ r>   )r0   r9   r?   s     rA   	is_randomOpTypes.is_random^   s    t$77rD   c                 2    [        U5      U R                  ;   $ r>   )r0   r:   r?   s     rA   is_viewOpTypes.is_viewa   s    t$55rD   c                 2    [        U5      U R                  ;   $ r>   )r0   r;   r?   s     rA   is_recomputableOpTypes.is_recomputabled   s    t$(=(===rD    N)__name__
__module____qualname____firstlineno____doc__r   r   __annotations__fxNoderB   rF   rI   rL   rO   __static_attributes__rQ   rD   rA   r5   r5   N   s    BH%%%h//8$$"" **9rww 9C C8bgg 86BGG 6>BGG >rD   r5   c                      \ rS rSr% \\R                     \S'   \\R                     \S'   \\R                     \S'   \\R                     \S'   \	\R                  \
4   \S'   \\R                     \S'   \R                  S\\R                     4S	 j5       rS
\R                  S\4S jrS
\R                  S\4S jrS
\R                  S\4S jrS
\R                  S\
4S jrSrg)NodeInfoh   inputs_required_fw_nodesrequired_bw_nodesunclaimed_nodesfw_orderstatic_lifetime_input_nodesreturnc                 B   ^  [        S T R                   5       U 4S jS9$ )Nc              3   $   #    U  H  ov   M     g 7fr>   rQ   .0ns     rA   	<genexpr>-NodeInfo.required_fw_nodes.<locals>.<genexpr>w   s     0/1Q/s   c                 "   > TR                   U    $ r>   )rb   )ri   r@   s    rA   <lambda>,NodeInfo.required_fw_nodes.<locals>.<lambda>w   s    a@PrD   key)sortedr_   r@   s   `rA   required_fw_nodesNodeInfo.required_fw_nodest   s!    0//06P
 	
rD   ri   c                     XR                   ;   $ r>   )r_   r@   ri   s     rA   is_required_fwNodeInfo.is_required_fwz   s    ++++rD   c                     XR                   ;   $ r>   )r`   rv   s     rA   is_required_bwNodeInfo.is_required_bw}   s    ****rD   c                     XR                   ;   $ r>   )ra   rv   s     rA   is_unclaimedNodeInfo.is_unclaimed   s    ((((rD   c                 T    XR                   ;   d   SU S35       eU R                  U   $ )NNode z not in fw nodes!)r_   rb   rv   s     rA   get_fw_orderNodeInfo.get_fw_order   s2    +++IuQC7H-II+}}QrD   rQ   N)rR   rS   rT   rU   listrX   rY   rW   r   dictint	functoolscached_propertyrs   boolrw   rz   r}   r   rZ   rQ   rD   rA   r\   r\   h   s     M"277++!"''**((277C<  !+BGG!44
4= 
 

, ,D ,+ +D +)bgg )$ ) bgg  #  rD   r\   c                   H    \ rS rSr% \\S'   \\S'   \\S'   \\S'   \\S'   Srg)	MinCutOptions   ban_if_used_far_apartban_if_long_fusible_chainsban_if_materialized_backwardban_if_not_in_allowlistban_if_reductionrQ   N)rR   rS   rT   rU   r   rW   rZ   rQ   rD   rA   r   r      s      $$"&&!!rD   r   r<   rd   c                 |    U R                   R                  SS 5      [        R                  [        R                  4;   $ )N	recompute)metagetr    MUST_RECOMPUTEPREFER_RECOMPUTEr<   s    rA   must_recomputer      s5    99==d+''))0  rD   fx_gc                 b    U R                   R                   H  n[        U5      (       d  M    g   g)NTF)graphnodesr   r   r<   s     rA   has_recomputable_opsr      s)    

  $ ! rD   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     rA   has_recomputable_rng_opsr      sV    

  4  V,,		11T[[5E5EE ! rD   c                     [        U R                  S   [        R                  [        R                  45      (       a  g[        U R                  S   [        R
                  5      (       d   eg)Nvalr!      )
isinstancer   r   SymIntSymBoolSymFloatr   s    rA   sym_node_sizer      sK    $))E"U\\5==$ABBdii&7777rD   c                       \ rS rSrS rSrg)InvalidNodeBase   c                     g)NzInvalid NoderQ   rr   s    rA   __repr__InvalidNodeBase.__repr__   s    rD   rQ   N)rR   rS   rT   rU   r   rZ   rQ   rD   rA   r   r      s    rD   r   c                 6    [        U R                  SS 5      S:g  $ )N	namespace_c10d_functional)getattrr   r   s    rA   is_not_collectiver      s    4;;T26HHHrD   joint_graphr^   outputsoutputs_descssubgraphignore_must_be_in_fw_bwc                 V  ^ [         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U H  n
[        U
[         R                  5      (       aN  U
T;  a  ['        S	U
 S
35      e[        TU
   [         5      (       a   S	U
 S35       eUR)                  TU
   5        Mp  UR)                  U
5        M     UR+                  [-        U5      5      nX<R                  S'   UR/                  5         UR1                  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placeholdercall_functionc                    > TU    $ r>   rQ   xenvs    rA   rm   4_extract_graph_with_inputs_outputs.<locals>.<lambda>   	    CFrD   get_attrc                    > TU    $ r>   rQ   r   s    rA   rm   r     r   rD   outputr   z couldn't be found in envz was invalid, but is outputdesc)rX   Graphr   namer   r   _must_be_in_backwardInvalidNode_must_be_in_forwardoppytreearg_tree_leavesargskwargsr   rY   r   any	node_copyRuntimeErrorappendr   tupleeliminate_dead_codelint)r   r^   r   r   r   r   	new_graphr<   new_nodeall_argsr   output_valuesoutr   s                @rA   "_extract_graph_with_inputs_outputsr      sb   $ 
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a!!|"U1#-F#GHH!#a&/:: s56:   Q(  #  

5/
0C$HHV!!#NN?s   #J&>J&c                     U R                   S:H  =(       aF    S[        U R                  5      ;  =(       a'    [        U 5      (       + =(       a    [	        U 5      (       + $ Nr   tangents)r   strr   _is_bwd_seed_offset_is_fwd_seed_offsetr   s    rA   
_is_primalr     sK    =  	*c$++..	*#D))	* $D))	rD   c                 ^    U R                   S:H  =(       a    S[        U R                  5      ;   $ r   r   r   r   r   s    rA   _is_tangentr   !  s$    77m#F
c$++6F(FFrD   c                 >   [         R                  =(       a    [        U R                  [        R
                  R                  5      =(       a    [        U R                  5      (       + =(       d1    U R                  [        R                  R                  R                  :H  $ r>   )r   is_non_builtin_to_includer   r   r   _ops
OpOverloadr   opshigher_order triton_kernel_wrapper_functionalr   s    rA   r   r   %  s`    ++ 	DKK!6!6	7	W
4;;@W<W 	R;;%))00QQQrD   c                     U R                   S:H  =(       a7    S[        U R                  5      ;   =(       d    S[        U R                  5      ;   $ )Nr   bwd_seedbwd_base_offsetr   r   s    rA   r   r   ,  =    77m# c$++&&O*;s4;;?O*OrD   c                     U R                   S:H  =(       a7    S[        U R                  5      ;   =(       d    S[        U R                  5      ;   $ )Nr   fwd_seedfwd_base_offsetr   r   s    rA   r   r   2  r   rD   c                     U R                   S:H  =(       a)    [        U R                  R                  S5      [        5      $ )Nr   r   )r   r   r   r   r   r   s    rA   _is_backward_stater   8  s*    77m#W
499==3G(WWrD   c                 @    U R                   R                  SS 5      S:H  $ )Npartitioner_tagis_backwardr   r   r   s    rA   _has_tag_is_backwardr  <  s    99==*D1]BBrD   c                 @    U R                   R                  SS 5      S:H  $ )Nr   
is_forwardr  r   s    rA   _has_tag_is_forwardr  @  s    99==*D1\AArD   c                 @    U R                   R                  SS 5      S:H  $ )Nr   must_be_in_forwardr  r   s    rA   _has_tag_must_be_in_forwardr	  D  s    99==*D15IIIrD   c                 @    U R                   R                  SS 5      S:H  $ )Nr   must_be_in_backwardr  r   s    rA   _has_tag_must_be_in_backwardr  H  s    99==*D15JJJrD   c                 R   [        U 5      (       a  g[        U 5      =(       dU    [        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   r   _schema
is_mutabler  r  r<   r  s     rA   r   r   L  s|    "4(( & 4;;

 5 56 	+KK** 
 !&& 	,T22	rD   c                    [        U 5      (       a  g[        U 5      =(       dU    [        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  r  s     rA   r   r   Z  sd    #D)) & 4;;

 5 56 	+KK**   %4*4rD   joint_modulec          
      \   [         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r>   r   rh   r<   s     rA   rj   +_extract_fwd_bwd_outputs.<locals>.<genexpr>h  s     	K J)) J   r   r   r   )	r   r   r   
find_nodesnextiterr   r   len)r  num_fwd_outputsr   r   fwd_outputsbwd_outputsfwd_outputs_descsbwd_outputs_descss           rA   _extract_fwd_bwd_outputsr$  d  s     $$	K 2 2 = = = J	KG **T,$$//8/<=>CCGGTFS\)	
M
 *?+K*+K%&67%&67%6IIrD   saved_valuesr   c                 \    U  H&  nUR                   U:X  d  M  U R                  U5          g    g r>   )r   remove)r%  r   saved_values      rA   _remove_by_namer)  v  s+    #t#, $rD   fwd_module_outputs.c                     [        U 5      n[        [        U 5      S-
  SS5       H  n[        X   5      (       a  M  US-   n  U$    U$ )Nr!   )r  ranger   )r*  idxis      rA   find_first_sym_noder0  }  sT      
!C3)*Q.B7-011a%CJ	 8 JrD   r   maxminpositionc           	         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   atenabsdefaultr   r   amaxprimsconvert_element_typefloat64	clamp_min
reciprocalmulTensorfloat32r   )r   r<   r1  r2  r3  abs_node	amax_nodeamax_64_nodeclamp_min_nodereciprocal_nodemul_node
scale_nodes               rA   calculate_quantization_scalingrM    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rL  
quant_typerA  	clamp_maxc           	      	   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   r5  fp8_quant_pos_r7  r8  )r9  r   r   r   r>  r?  r<  rE  r   r   r:  rC  rD  rA  rO  r   )r   r<   rL  rN  rA  rO  r3  target_node_32scaled_target_nodeclamp_min_scaled_nodeclamp_max_scaled_nodequant_activation_nodes               rA   perform_quantizationrW    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tensorc                 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)rX  num_elementsr[  s      rA   calculate_tensor_sizer]    s+     <<>L&&(L'K88rD   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   )r`  dtypes     rA   get_allowed_dtypesrg  -  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   Fr_  
size_in_mbd   skip_dynamo_guardsquantize_dynamic_shape)rg  r   r   rf  r   rc  r   rd  r   r]  r   r   )r<   r`  size_thresholdri  s       rA   should_quantizern  7  s   ')Nd##tyy'7'='=^'S__++DD+	c,  'tyy'78J??!!::+	c
&' ++ ??!!::/

#&
./ ), J+J,HIIJ
 ))EFFrD   c                      [         R                  R                  R                  S   R	                  SS5      n [        [         U R                  S5      S   5      $ )Nr_  rN  ztorch.float8_e5m2rb  r,  )r   rc  r   rd  r   r   re  )rN  s    rA   get_quant_typerp  Q  sN    ''@@+	c,+,  5***3/344rD   rf  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   finfor2  r1  )rf  infos     rA   calculate_rangert  Y  s%     ;;uD88TXXrD   c           
         U R                  SS9S   nUR                  S   n[        5       n[        U5      u  pE[	        5       n/ / p[        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_quantizationFr_  use_scalingT-q=rQ  r7  r8  r   r5  inductor%activation_quantization_fwd_aten_passr!   )r  r   rp  rt  r   	enumerater   r   r   rc  r   rd  rM  rW  r   r   r9  r   r   r>  r?  r<  r   r   r0  
update_argr   r   )r   r   r   rN  rA  rO  position_to_quanttensor_scale_nodessym_scale_nodesr3  r<   rL  
quant_noder/  output_updated_argsr.  scale_nodess                    rA   quantize_activation_fwr  e  s[   *1-F++a.K!J*:6I*,b#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+8I<+
I9	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   rv  Fdequant_typer_  rw  
fp8_scale_
fp8_quant_ c              3   L   >#    U  H  nUR                   T:X  d  M  Uv   M     g 7fr>   r   )rh   	bwd_input
scale_names     rA   rj   )quantize_activation_bw.<locals>.<genexpr>  s&      &)2I$>>Z7 "	)2s   $	$r  r   r5  dequant_r8  ry  %activation_quantization_bwd_aten_passr!   )r   r   r   r   popr   rc  r   rd  r9  r   r   r  r   r   r>  r?  r<  r   r:  divrD  r   r   userskeysreplace_input_withr   )
r   r<   	bw_inputsactivation_noder  rL  divided_target_node_32dequant_nodeuserr  s
            @rA   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&	
fwd_module
bwd_modulebwd_module_inputsc                   ^ ^ [        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   encodingrQ   rQ   rD   rA   rm   5perform_fp8_activation_quantization.<locals>.<lambda>      B 
rD   c                  &   > T R                  SSSS9$ NFT)print_outputinclude_strideinclude_deviceprint_readabler  s   rA   rm   r         :44tD 5 
rD   metadata_fn
payload_fnc                      SSS.$ )N+after_activation_quantization_fwd_aten_passr  r  rQ   rQ   rD   rA   rm   r  	      A 
rD   c                  &   > T R                  SSSS9$ r  r  r  s   rA   rm   r    r  rD   c                      SSS.$ )N,before_activation_quantization_bwd_aten_passr  r  rQ   rQ   rD   rA   rm   r    r  rD   c                  &   > T R                  SSSS9$ r  r  r  s   rA   rm   r    r  rD   r   r  r   r  z^fp8_quant_pos_\d+_r  r  r  Trv  r_  rw  r   r,  r  c                      SSS.$ )N+after_activation_quantization_bwd_aten_passr  r  rQ   rQ   rD   rA   rm   r  E  r  rD   c                  &   > T R                  SSSS9$ r  r  r  s   rA   rm   r  I  r  rD   )r   r  r   r  r   r   resubr9  r   r   updatereplace_all_uses_with
erase_noder   rc  r   rd  r   r   reversedr   r  )r  r  r  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   ``           rA   #perform_fp8_activation_quantizationr    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	rc   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 )Nr_  exclude_primalsFprimalsr   r  r   r   z*Skipping quantization of static input %s: Trv  r   r  )inductor_configrd  r   r   r   rc  r   r   r  r   rn  r3   debugr   rf  r  )
r%  r  r  rc   r<   static_input_namessaved_values_namesr*  r  should_perform_fp8_quants
             rA   enable_activation_quantizationr  O  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)rc   saved_sym_nodesr  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   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[,        R.                  " UX5       Hc  nSUR0                  ;  a  M  [3        UR0                  S   5      U-
  n[5        US S9 H  nUU;  a  M  UR)                  UU   5        M!     UU-  nMe     UR7                  5         UR9                  UU-   5        / n/ nU HH  nUR0                  R;                  S	S
5      (       a  UR)                  U5        M7  UR)                  U5        MJ     UR7                  5         UR9                  UU-   5        [=        U5      n[?        U5       HH  u  nnUU:  d  M  UR0                  R;                  S	S
5      (       a  M1   SU SU S[=        U5       35       e   [        U R                  X-   XQ-   U-   U[A        [=        U5      [=        U5      -   5       Vs/ s H.  nUU:  a  U[=        U5      :  a  [C        U5      O
[E        U5      PM0     sn-   S5      n[        U R                  UU-   U-   U-   U-   UUS5      n[F        RH                  RK                  U U5      n[F        RH                  RK                  X5      n[M        UUUU5        UU4$ s  snf )Nr  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  rg   s     rA   rj   +_extract_fwd_bwd_modules.<locals>.<genexpr>  sR      )
   HH		22>>FFF "AGG!"s   A&A(r   c                     U R                   $ r>   r  )ss    rA   rm   *_extract_fwd_bwd_modules.<locals>.<lambda>  s    166rD   ro   saved_tensor_with_no_vc_checkFzi=z, no_vc_check_start_idx=z, len(saved_values)=r   )'r$  r   r  filterr   r   r   r   r   r   r   distributedis_availabler  r)  r   allr   r   addr   r   	itertoolschainr   r   rq   clearextendr   r  r{  r-  r*   r)   rX   _lazy_graph_module_make_graph_moduler  ) r  r%  r  r  rc   r   r!  r"  r#  placeholdersprimal_inputstangent_inputsfwd_seed_offset_inputsbwd_seed_offset_inputsbackward_state_inputs	bwd_graphdistributed_enabledr<   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no_vc_check_start_idxr/  	fwd_graphr  r  s                                    rA   _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((((' 72 /9lM    *40f%#**40#**40   3<3E3EFO 7V		!"499U#34}D)9:A '#**?1+=> ; 	$ W" 25LLM "$!99==8%@@$++D1&--d3	 
 25MMN :; \*4%%99==!@%HH QC/0E/FFZ[^_k[lZmnH + 3."_4
 3|,s?/CCD	
 E ))a#l2C.C 02+A./ E	
	
 	I 3
	
	 !	!  		 
 	
I &&99,	RJ&&99,RJ"j*.I z!!3
s   5Q9)static_lifetime_input_indicesrc   r  c                  ^ / nSnU R                   R                   H7  n[        U5      (       d"  [        U5      (       d  [	        U5      (       d  M5  UnM9     Uc   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c  / n['        XU5      n/ n/ n[(        R*                  R-                  5       mS nS	 nU4S
 jnU R                   R                   GH  nUR.                  U;  a  M  UR0                  S:X  a'  UR.                  S U R3                  5        5       ;   a  MM  UR4                  [(        R6                  R8                  R:                  R<                  [(        R6                  R>                  R@                  R<                  [(        R6                  R>                  RB                  R<                  [(        R6                  R>                  RD                  R<                  [(        R6                  R>                  RD                  RF                  4;   a  GMA  [I        U5      (       a  UR                  U5        GMe  U" U5      (       a  GMu  URJ                  RM                  S5      [N        RP                  :X  a  UR                  U5        GM  U" U5      (       a/  U	(       a   SUUR4                  45       eUR                  U5        GM  U" U5      (       d  UR0                  S:w  d   SU S35       eURR                   Vs/ s H  nUR.                  U;  d  M  UPM     nn[U        S U 5       5      (       a  URW                  U5        GMs  [Y        U5      (       a  GM  UR                  U5        GM     [[        [\        R_                  U5      Ra                  5       5      n[[        [\        R_                  U5      Ra                  5       5      n[        Rb                  (       a  [c        U R                   U5      nUc  URd                  n[g        U UUUUS9u  nnUR                   Ri                  [j        S9  UR                   Ri                  [j        S9  U	(       a,  U
(       a  [m        U UU[o        U5      5      u  nn[q        U5      n[s        U5      n[s        U5      n[u        USS9n[o        URv                  5      S:  a
  [u        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.
Nc              3   \   #    U  H"  oR                   S :w  d  M  UR                  v   M$     g7fr   Nr   r   r  s     rA   rj   $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.)r  r  Tis_default_partitionc                     SU R                   ;   =(       d=    [        U R                   R                  S5      [        R                  R
                  5      $ )Nr5  r   )r   r   r   r   _subclasses
FakeTensorr   s    rA   	is_tensor$default_partition.<locals>.is_tensorf  s=    		) 
ZIIMM% %"3"3">">.
 	
rD   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r>   )r   operatorgetitemrh   r  s     rA   rj   =default_partition.<locals>.is_multi_output.<locals>.<genexpr>m  s     GJDx///Js   )+r   )r  r  r  r   s    rA   is_multi_output*default_partition.<locals>.is_multi_outputk  s.    GDJJGG $DJJ!#	
rD   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<  )r<   r  s    rA   r  $default_partition.<locals>.is_impureq  sc     NNN/ 		 (' U;;eii&@&@&L&L&T&TT	
rD   r   c              3   *   #    U  H	  u  pUv   M     g 7fr>   rQ   )rh   kvs      rA   rj   r    s      3
6$!A6s   r   z,Trying to apply AC on a graph with impure opr   z	Expected z to be a tensorc              3   8   #    U  H  n[        U5      v   M     g 7fr>   r   rg   s     rA   rj   r    s     7!{1~~r  r  r  rc   )is_impure_nodeFr  )<r   r   r  r   r   r   r   r   r   r   r+   warningswarn#min_cut_rematerialization_partitioncleanup_recompute_tagsr   (unsafe_allow_optimization_of_collectivesforce_save_collectives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_ranksrc   r  r   r   functionalize_rng_opsr  #reordering_to_mimic_autograd_enginer1   thread_graphsafe_rng_from_hopsr`   )r  _joint_inputsr  r  rc   forward_nodes	last_noder<   forward_node_namesgraph_has_recomputable_opsgraph_has_recomputable_rng_ops	node_infor%  r  r  r  r  ri   backward_usages	fw_module	bw_moduler  s                        @rA   default_partitionr@    s   @ MI""((t$$
4(8(8<OPT<U<UI )    ""((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??1 >4 1
 %$''_"< 	
v_-	
< '+jjUjAFFBT4T1jU7777 ""?3d##%k )n 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g Vs   <VVg    .ArZ  c                     XR                   -  $ r>   )itemsize)rZ  rf  s     rA   _tensor_nbytesrC    s    >>!!rD   c                   ^ S[         4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)Nrd   c                     [        U [        R                  5      (       d  g[        [	        U R                  5       SS9U R                  5      $ )Nr      fallback)r   r   rD  rC  r   rZ  rf  r   s    rA   object_nbytes_size_of.<locals>.object_nbytes  s4    !U\\**i	DA177KKrD   r   r!   c              3   4   >#    U  H  nT" U5      v   M     g 7fr>   rQ   )rh   ri   rJ  s     rA   rj   _size_of.<locals>.<genexpr>  s     5A}Q''   c              3   8   >#    U  H  u  pT" U5      v   M     g 7fr>   rQ   )rh   r7  ri   rJ  s      rA   rj   rM    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   r   r   r   r   r   sumr   itemsr   rD  r   typer   r   r   r:  r*  r<  )r<   r   rJ  s     @rA   _size_ofrS    s   LC 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 rD   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!   z%sTrp   reverse)collectionsr   r   r   r   r   rR   r3   rs  rq   rQ  r  
itemgetter)r   r   cntr<   s       rA   
_count_opsrZ    sk    '%c*C77o%$$%*%  HHT6#))+8+>+>q+A4PQrD   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 $ r>   )dirr   r   r:  r   r   r   OpOverloadPacket	overloadsr   	pointwiser   r   )r   	attr_nameopoverloadpacketoverloadop_overloads        rA   pointwise_opsrd    s    
C(	"599>>9=*EJJ,G,GHH(224H!"2=Kyy""k&6&66

+, 5 ) JrD   	depth_mapc                     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!   TrU  )	r   r   rX   r<   rY   rq   rQ  r  rX  )r   re  arg
arg_depthss       rA   sort_depthsri  !  si    '+'+z#uxx}}?Q?Q/Rs^t   *""$(*=*=a*@$OOs   7A8 	A8gmc                   ^
^^ [         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U
UU4S 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    $ r>   rQ   r   s    rA   rm   5reordering_to_mimic_autograd_engine.<locals>.<lambda>D  s	    ArD   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    $ r>   rQ   )ri   orders    rA   rm   Sreordering_to_mimic_autograd_engine.<locals>.insert_node_in_graph.<locals>.<lambda>V  s	    %(rD   ro   c                    > TU    $ r>   rQ   r   s    rA   rm   rq  X  r   rD   )r   r  r  r  all_input_nodesrq   r   )r<   	cur_nodesinsertable_nodesr   r   rp  s      rA   insert_node_in_graphAreordering_to_mimic_autograd_engine.<locals>.insert_node_in_graphH  s    F	0:)nq ==?D'43;  & ---I )nq  ""28JK$D!++D2BCCI %rD   Nr   )rX   r   r   r  r   r{  r   r   r  r   mathinfr  r   r   r   r   r:  copy_r<  GraphModule)rj  r<   r.  rv  r  first_node_in_bwdminimum_ordertangentr  new_gmr   r   rp  s             @@@rA   r4  r4  (  s   . 
I"$C ##}#5''.>?D	 6 )2"((..(AB(A93TY(ABE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r>  r?  fw_nodebw_nodedevice	rng_countlast_fwd_inputlast_bwd_inputc                    UR                   nUc   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
Nfwd_rng_state_r   bwd_rng_state_	rng_stater   r   r   )indexr   r   _prims	rng_primsgraphsafe_run_with_rng_stater9  r   r-   r   r   r   create_noder   r   r  r  inserting_before)r>  r?  r  r  r  r  r  r  
device_idxfw_graphbw_graphr  fwd_rng_statebwd_rng_state	fw_kwargsfunctional_fw_node
bwd_kwargs
rng_outputs                     rA   %apply_graphsafe_rng_functionalizationr  v  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   )9H9H%;+H7;AI
H"%
H47
I
Inum_sym_nodesc                   ^' [         R                  " 5       nS nS[        [        R                     4S jm'S[        [        R                     4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  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R1                  [        R                  " S5      5        [3        U5      S:  n[        R4                  R6                  n[6        R8                  =(       a<    U(       + =(       a.    UR:                  (       + =(       d    UR<                  R>                  n[A        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RB                  S:X  a  [E        UUUUUUUU5      u  nnMb  URG                  U5         URI                  SUUR                  /URJ                  Q7URL                  S9nURI                  S[N        RP                  US40 S9nU" U5      URR                  S'   URI                  S[N        RP                  US40 S9n [T        RT                  " URR                  5      U l)        URW                  U 5        URY                  U5        UR[                  U5        S S S 5        URG                  U5         S[)        U5       3n!UR]                  U!5      n"U" U5      U"RR                  S'   S S S 5        URG                  U5         URI                  SUW"UR                  /URJ                  Q7URL                  S9n URW                  U 5        URY                  U5        S S S 5        GM#     U(       a  [)        [_        UR
                  R%                  SS	95      5      n#U#RJ                  S   n$[3        U$5      U-
  n%U$S U% [a        U5      -   U$U%S  -   n&UR
                  Rc                  U&5        UR
                  RY                  U#5        URe                  5         URe                  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_nodesr<   s      rA   get_rng_ops*functionalize_rng_ops.<locals>.get_rng_ops  sh    JJ$$D?*DKK00II559I9II*.TYY' % rD   rd   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   rD  r  rR  )r<   
candidates	candidates      rA   
get_device)functionalize_rng_ops.<locals>.get_device  s     		!YYu%
*e,,$J#I)U\\22##((F2$+++ $
 ||E""rD   r  c                 :   SSK Jn  U" 5       nUc   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_moder  )torch._guardsr  rR  from_tensorr   r  get_rng_state)r  r  	fake_modes      rA   get_sample_rng_state3functionalize_rng_ops.<locals>.get_sample_rng_state  sr    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  NrQ   )rh   	node_pairr  s     rA   rj   (functionalize_rng_ops.<locals>.<genexpr>7  s"      6W
9U#$$6Ws   r  r!   r  r  r  r   r  r   r   rng_state_output_r   )3r  countr	   r   r  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  rc  r   graphsafe_rng_functionalizationfallback_randomtest_configs*graphsafe_rng_func_ignores_fallback_randomr{  rR  r  r  r  r   r   r  r  r   copyr  r  r   r   r  r   r   	recompile)(r  r>  r?  r  uidr  r  joint_graph_rng_opsfw_graph_rng_opsbw_graph_rng_opsrecomputable_rng_ops_mapr<   	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(                                          @rA   r3  r3    sp   2 //
C	#HU\\2 #$@Xell%; @ &l3"9-"9-!""((4  V,,		11T[[5E5EE+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#$!..87<<8">>	 &: &" !,,#$$,a0	 -  %9$@

5!%11#$$*  2 
 #'))GLL"9
--j9##G,$++E2; 4@ **+@A0c<
$,$8$8$D!0DV0L!&&u- B
 **73%11#&+W^^KgllK">>	 2 
 --j9##G, 43} !MX d9??#=#=#=#JKL#((+
 _}<**+()*+,-. 	
 	w'"">2A 43@ BA
 43s&   C&W 5WAW$ 
W	
W!	$
W4	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    r0  r   )r  r<   s     rA   r&  r&    sg     ""((t{{EJJ$9$9::%%);;"4((%5%?%?DIIk" )rD   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:  rz  r<  r  r  r   r	  r    r0  r   )r  has_mutation_in_bwr<   is_copy_s       rA   r'  r'    s     5?L++11277h;;%)).."6"6">">>+D11"&&tyy|4*400TYYq\EW5W1A1K1K		!!!+. 6X0 ! 3rD   c                     U R                   [        R                  :w  a  gU R                  S   nSUR                  ;  =(       a    U R
                  S:H  $ )NFr   r5  r   )r   r  r  r   r   r   )r<   parents     rA   is_getitem_of_multi_outputr    sA    {{h&&&YYq\F+J?0JJrD   r  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r>   r   r  s     rA   rj   )cleanup_recompute_tags.<locals>.<genexpr>  s      E1;t$$r  c              3   8   #    U  H  n[        U5      v   M     g 7fr>   r  r  s     rA   rj   r    s     @ZTN4((Zr  r   )r   r   r   r  r   r    r0  r   r   r  r   )r  r  r<   r  s       rA   r$  r$    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 rD   r<  min_cut_optionsdont_banc                 F  ^^^^%^&^'^(^)^*^+^,^-^.^/^0 Tc
  [        5       m[        5       m/[        (       aQ  [        S U R                   5       5      nU[        S T/R                   5       5      -
  n[
        R                  SU5        S m&S m'U&U'U/4S jm( SS KnU(UU/4S	 jm*U*UU/4S
 jnU(4S jm)S[        4U)U/4S jjn	UR                  5       m.[        5       m%U%UU.U/4S jn
U R                   GH  nUR                  S:X  a  M  UTR                  ;   aj  UTR                  ;  a.  T.R                  UR                   S-   S["        R$                  S9  Md  T.R                  UR                   S-   S["        R$                  S9  ['        U5      (       a.  T.R                  UR                   S-   S["        R$                  S9  M  [)        U5      (       d  [+        U5      (       a  U
" U5        TR-                  U5      (       a  U" U5      (       a  U
" U5        SUR.                  ;  =(       a    SUR.                  ;  =(       dB    SUR.                  ;   =(       a,    [1        UR.                  S   [2        R4                  5      (       + n[7        U5      (       a  [        [9        U5      5      nO[U(       aA  [1        UR.                  R;                  S5      [<        5      (       a  SO["        R$                  nOU	" UTR>                  5      nT.R                  UR                   S-   UR                   S-   US9  UR@                   H<  nT.R                  UR                   S-   UR                   S-   ["        R$                  S9  M>     GM     S[B        [D        RF                     S[H        S[H        4U(U4S jjnTRJ                  (       GaR  TRL                   GHA  nUR@                   Vs/ s H,  nTR-                  U5      (       d  M  TRO                  U5      PM.     nnUR@                   Vs/ s H  nTR-                  U5      (       d  M  UPM     nn[Q        U5      S:  d  M  U" U[S        U5      5      n[U        UR@                  5       H  nTR-                  U5      (       d  M  TRO                  U5      U:  d  M2  T(" UU5      (       d  MB  UT%;   a  MJ  [
        R                  SUTRO                  U5      UUTRO                  U5      5        U
" U5        M     GMD     TRV                  (       Ga  [        5       nU R                   GHi  nTR-                  U5      (       d  M  TRO                  U5      U4/nTRO                  U5      n[Q        U5      S:  d  MR  [X        RZ                  " U5      u  nnUU;   a  M2  UR]                  U5        TRO                  U5      US-   :  aP  [Q        U5      S:X  aA  [
        R                  SUUTRO                  U5      TRO                  U5      5        U
" U5        M  UR@                   H[  nTR-                  U5      (       d  M  T(" UU5      (       d  M+  UT%;  d  M3  [X        R^                  " UTRO                  U5      U45        M]     [Q        U5      S:  a  GM  GMl      URa                  T.SS5      u  nnUu  nm-[        5       nU.4S  jU 5        H"  u  m0nURo                  U-U04S! jU 5       5        M$     [        5       nU H*  u  n n!U S S" U!S S# :X  d   eU S S" n"UR]                  U"5        M,     [q        U 5      m+[s        U R                  5       V#Vs0 s H  u  n#oU#_M
     snn#m,[u        U+4S$ jU 5       U,4S% jS&9n$U$T%4$ ! [         a  n[        S5      UeS nAff = fs  snf s  snf ! [b         ai    [
        R                  S5        [
        R                  SRe                  URf                  Rh                  Rk                  T.5      5      5        [m        T.5        e f = fs  snn#f )'Nc              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     rA   rj    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r>   )r   rh   r/  s     rA   rj   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_namesr7  r   rg  s          rA   !can_fuse_into_auto_functionalized8solve_min_cut.<locals>.can_fuse_into_auto_functionalized"  s    88uyy--AAAVVAY
 ##66GG
S	
%D((4.Cx#t$$8 & rD   c                     UR                   [        R                  R                  R                  :w  a  gUR
                  S   nU H  nUR
                  S   U   nXL d  M    g   g)NFtensors_to_cloner   T)r   r   r   r   r   r   )r  r  r  r   rg  s        rA   .can_fuse_into_triton_kernel_wrapper_functionalEsolve_min_cut.<locals>.can_fuse_into_triton_kernel_wrapper_functional3  s[    88uyy--NNNHH%78%D((8$T*Cx & rD   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)r0   r:  catr   r  r  r   r   r   r   r   rB   )r  r  r  r  op_typess     rA   rB   !solve_min_cut.<locals>.is_fusible=  s     1),Q229!??HH(((q	  yy%%FFG
 ""1%@(*=*=a*@@rD   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  )rL   r   r  r  r  rw   r  )r<   rt  curr  rB   r<  r  s       rA   is_materialized_backwards0solve_min_cut.<locals>.is_materialized_backwardsW  s    D!!v&	)nq --/C		 //55j>S>S##D))MM$'	 " )nq  rD   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      (       d&  TR%                  U 5      (       d  ['        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                  (       a/  [9        S U R:                   5       5      n[=        U 5      nUS-  U:  $ g)	Nr   Fr   Tzmaterialized backwards: %s %si  c              3   z   #    U  H1  n[        U[        R                  5      (       d  M$  [        U5      v   M3     g 7fr>   )r   rX   rY   rS  r  s     rA   rj   Bsolve_min_cut.<locals>.should_ban_recomputation.<locals>.<genexpr>  s(      %%.*Q2HYs   #;;r   )r   r   r  r  r   r   r    r0  r   recompute_viewsrL   r:  lift_fresh_copyr<  
lift_freshr   rO   rI   rF   r   r   r3   r  r   r  dist_from_bwmax_dist_from_bwr   rP  r   rS  )r<   input_tensors_sizeoutput_sizer  r  r  s      rA   should_ban_recomputation/solve_min_cut.<locals>.should_ban_recomputatione  s   77o%;;(***99==d+/?/I/II!!h&6&6t&<&<;;4//779P9PQQ22++D11 2 ""4((0066,T22 77<U=
 =
 II5tU4::=NO t#(9(9F<S<S(S ++!$ %%)YY% " #4.K?%777rD   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r>   rQ   )rh   r  rB   r<   s     rA   rj   9solve_min_cut.<locals>.is_materialized.<locals>.<genexpr>  s     E*$z$--*s   )r   r  r  )r<   rB   s   `rA   is_materialized&solve_min_cut.<locals>.is_materialized  s*    77m#E$**EEEErD   rd   c           
        > [         R                  (       a  X;   a  g[        U 5      n[         R                  (       a&  TR	                  U 5      (       a  [
        R                  $ [        U R                  S   [        5      (       a2  [        U R                  S   [        R                  5      (       d  [        $ [        US[        [        U R                   S5      S5      -  -  5      nT" U 5      (       a  U$ US-  $ )Nr   r   g?rj  r!      )r    treat_parameters_as_free_to_saverS  r  rL   rx  ry  r   r   r   r   r   INT_INFr   r1  r2  r	  )r<   rc   mem_szr  r  s      rA   get_node_weight&solve_min_cut.<locals>.get_node_weight  s    333$!!h&6&6t&<&< 88Odii&55dii.== Vsc#d.?.?*Eq&IIJK4  MA:rD   c                 ,  > 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                   S9  g)NFr   r   source_incapacityT)rL   r   r   r   r   r   r   r   r%  r   r   r   r  add_edger   rx  ry  )r<   is_collectivebanned_nodesr  nx_graphr  s     rA   ban_recomputation_if_allowed3solve_min_cut.<locals>.ban_recomputation_if_allowed  s    D!!8 4;;

(=(=> @KK))-??  >>m $DII*TYYu-=u~~"N"N
 	(DII$5IrD   r   r  sinkr  _outr   r5          start_nodes	max_rangec                   > / 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  rw   )r)  r*  sorted_nodesri   r7  r<   node_is_fusibler  r   rB   r<  s            rA   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 #	 ,!# rD   z1used above/below fusible %s:(%s) -> %s -> %s:(%s)rj  ztoo long %s %s %s %sr  z-Failed to compute min-cut on following graph:
c              3   0   >#    U  H  oTU   4v   M     g 7fr>   rQ   )rh   ri   r#  s     rA   rj   r    s     8i$is   c              3   :   >#    U  H  oT;   d  M
  TU4v   M     g 7fr>   rQ   )rh   r  non_reachableus     rA   rj   r    s     Ad=.@fq!fds   	c              3   .   >#    U  H
  nTU   v   M     g 7fr>   rQ   rh   r<   name_to_nodes     rA   rj   r    s     2	d		s   c                    > TU    $ r>   rQ   )r   node_idxs    rA   rm   solve_min_cut.<locals>.<lambda>  s	    (1+rD   ro   );r   get_default_op_listr2   r   r;   r3   rs  networkxImportErrorr   floatDiGraphr   r`   r^   r   r   rx  ry  r   r   r   rw   r   r   r   rD  r   r   r   r   rc   r  r   rX   rY   r   r   rs   r   r  r1  r   r   r,  r.  r  r-  minimum_cut	Exceptionjoin	readwriteedgelistgenerate_edgelistvisualize_min_cut_graphr  get_name_to_noder{  rq   )1r   r<  r  r  joint_module_opsops_ignorednxer  r  r$  r<   is_non_tensor_nodeweightr  r1  	used_nodeordersfw_usersfirst_unfusible_usevisited
start_nodefusiblestart_orderr7  r   	cut_value	partition	reachablecutsetnbrs	cut_nodesnode_innode_out	node_namer.  r%  r"  r  r  rB   r  r  r<  r>  r6  r#  r  r7  s1    ```                                 @@@@@@@@@@@@rA   solve_min_cutrd    s    <"$H% &
#))&
 

 ' 4
$554
 *
 
 	9;G"A&4lFe  < zz|H(2L 6 !!77h9...9+++!!$))e"3Vdhh!O dii&0&488L$
 dii%/$((Kd2488(.
 ##D)).Ft.L.L(. "E}DII'EUtyy SDIIe4Dell)S%S 	 t=./F!$))--"6FFDHH  %T9+P+PQF$))e+TYY-?&QJJDdii&0$))e2CdhhW e "L$rww- C C  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!~~h&I	9  )I}*4,F8i84AdAA 9 ",I#s|x},,,CRL	i  $
 $K0L+4[5F5F+GH+Gic4c	+GHH2	28ML %%e
  O
	Z
R  @A2<<00BB8LMN)	& IsC   ]? ^/^^"2^"^' `?
^	^^'A3`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     [        R                  S5        UR                  S5        g )Nr   r  ry  redz2Visualizing the failed graph to min_cut_failed.svgzmin_cut_failed.svg)rA  pydotnx_pydotto_pydot	to_stringgraph_from_dot_data	get_edges
get_sourceget_destination	set_labelr   rC  	set_colorr3   rs  	write_svg)r#  rO  rg  
dot_format	dot_graphedgerR  s          rA   rK  rK    s    %%h/99;J))*5a8I##%//+,T-A-A-CDZPs6{#U5\!NN5! & HHAB,-rD   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  atan2rC  r1  r2  pow	remainderfmod__and____or____xor__
__lshift__
__rshift__eqnegegtleltr;  bitwise_notceilfloorfracnegreluroundsilutruncr3   log10log1plog2lgammaexpexpm1erferfccosacoscoshsinasinsinhtanatantanhatanhsqrtrsqrtrB  sigmoidsoftplus	thresholdthreshold_backwardclampwherelerpaddcmulgelugelu_backwardrP  mean_grad_sum_to_sizesum_to_sizer=  totype_asr  r  squeeze	unsqueezersub_to_copyaliasviewslicetr>  broadcast_in_dimexpand
as_stridedpermuteselectre  r?  clone	full_likevarstd_unsafe_viewreshape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  gatherrd  
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_mmr5   )default_recomputable_opsrecomputable_view_opsr:   mr;   r9   r8   r7   s           rA   r@  r@    s   L0L0L0 	L0 	

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

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

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

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

CL0D 	

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

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

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

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

uL0v 	

wL0x 			yL0z 	{L0| 			}L0~ 	L0@ 	AL0B 			CL0D 	EL0F 	GL0H 			IL0J 	KL0L 	ML0N 	OL0P 	QL0R 	SL0T 			UL0V 	WL0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$ r>   )r   r   )r   r<  r<   s      rA   rL  rL  `	  s'    L"&TYY rD   memoryruntimes
max_memoryall_recomputable_banned_nodesc           	         [         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   r   recorded_knapsack_input_memories recorded_knapsack_input_runtimes)graph_info_provider)knapsack_algomax_mem_budgetr(  z,Not aware of memory budget knapsack solver: )r   activation_memory_budget_solverr%   r&   r#   r$   r3   warningr"   inialize_from_graphr'   get_knee_point_memory_budgetcallabler   )
r   r  r  r  r<  r  SOLVERr  saved_node_idxrecomp_node_idxs
             rA   #_optimize_runtime_with_given_memoryr  g	  s    33Fv<<	5Fj99	46Z88	3	3-f
KK	-	-?	

 0CC#*G-3-5	
 $7**)) + 	
 		
 
&		*08U+
' ^55I&RSSrD   no_dispatchr   rH  c                    ^ [        U R                  5      nU4S 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$ )NrG  )r   )drH  s    rA   realize_symbol8_remove_symbols_without_guarding.<locals>.realize_symbol	  s    X..rD   )stride)r   shaper  new_empty_strided)r   rH  r  r  r  r  s    `    rA    _remove_symbols_without_guardingr	  	  sk    ME/ )..1^AE.)*4AnQF4u44 /4s   A(A-c                   ^ ^^	 [         R                  nS 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       Na= 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   rF  rG        ?T)r   rX   rY   r   r   rD  r	  r   r   r   r   rI  s    rA   materialize_arg)estimate_runtime.<locals>.materialize_arg	  s    a!!j&M&M3AFF5MDQQ277##
166%=%,,(O(OQVVE]T::277##
166%=%..(Q(Q277##
166%=%--(P(PHrD   testingr!   profiler   )benchmarkerc                  (   > TR                   " T 0 TD6$ r>   )r   )r   r   r<   s   rA   rm   "estimate_runtime.<locals>.<lambda>	  s    4;;3O3OrD   flops)FlopCounterModeF)displayz Not aware of runtime estimator: )r   *activation_memory_budget_runtime_estimatorr   $torch._inductor.runtime.benchmarkingr  r   tree_mapr   r   benchmark_gputorch.utils.flop_counterr  r   get_total_flopsr1  r  r   )
r<   RUNTIME_MODEr  r  msr  modecounted_flopsr   r   s
   `       @@rA   estimate_runtimer!  	  s   DDL
 y 		"]H!???TYY<TULD&**+OPB ] 
	 <DKK8PQfU+tKK(( ,,,.=!$$	,		D!! =l^LMM+ ] ,+s   AD&	D7&
D47
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[        [        R                     S[        4S	 jm!T!" TR                  5      m(T!" U5      m&T&T(::  a  U$ U&U(4S
 jnS[        [        R                     4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%S[$        [        R                     S[        [        R                     4U#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[0        SS9m [3        T 5      S:X  a  TR                  U-   $ T  Vs/ s H  o" [1        U5      5      PM     snm'T  Vs/ s H  n[5        U5      PM     snm*SSKJm)  UU U'U)U*4S jm$[        R:                  (       Ga  U"U$U UU*4S 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R=                  5       u  nnUS   US   -
  S:  a$  UR?                  U5        UR?                  U5        MM  U" US   US   -   S-  5      nUSS  USS  :w  a  UR?                  UU45        USS  USS  :w  a  UR?                  UU45        U(       a  M  URA                  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RG                  SS9  URI                  UUSS 9  [K        U5       H   u  nnURM                  US! UUU   4S"S#S$S%9  M"     URO                  S&5        URQ                  S'5        URS                  S(5        URU                  S5        URW                  5       nURY                  5         [Z        R\                  " 5       n[        R^                  b%  [        R^                  n[Z        R`                  " USS)9  S*n[b        Rd                  Rg                  5       (       aD  [b        Rd                  Ri                  5       (       a!  S+[b        Rd                  Rk                  5        3n[Z        Rl                  Ro                  US,U S-[q        5        S.35      nURs                  U5        [t        Rw                  S/U5        T$" UTT S09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 )1Nr!   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   r%  rd   c                 :    [        [        [        U 5      5      S-  $ N    eA)rP  maprS  )r%  s    rA   estimate_activations_size:choose_saved_values_set.<locals>.estimate_activations_size	  s    3x./#55rD   c                    > U S-  TT-
  -  $ r$  rQ   )szmax_act_sizemin_act_sizes    rA   get_normalized_size4choose_saved_values_set.<locals>.get_normalized_size	  s    S\L899rD   activationsc                 &   > T" U 5      T-
  TT-
  -  $ r>   rQ   )r/  r'  r+  r,  s    rA   get_mem_ratio.choose_saved_values_set.<locals>.get_mem_ratio
  s"    )+6E<'
 	
rD   )r   r   r   )r   )get_node_storagec              3   4   >#    U  H  nT" U5      v   M     g 7fr>   rQ   )rh   r<   r3  s     rA   rj   *choose_saved_values_set.<locals>.<genexpr> 
  s     TCS4 0 6 6CSrN  r"  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   )r"  r/  r3  input_storagess     rA   get_recomputable_banned_nodes>choose_saved_values_set.<locals>.get_recomputable_banned_nodes"
  sX    
 "
! S)	  %Q'~=03 !
 	
 
s   AAAr   TrU  r  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   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   )	r   r  saved_node_idxsrecomputable_node_idxsexpected_runtimememories_banned_nodes normalized_memories_banned_nodesruntimes_banned_nodesmin_cut_saved_values)
r  r1  r   r  BaseExceptionissubsetrd  r2   r   rS  )memory_budgetr<  r   r=  r;  r<  r  r.  r%  r7  r/  aggressive_optionsr  r>  r   r@  s              rA   get_saved_values_knapsack:choose_saved_values_set.<locals>.get_saved_values_knapsackM
  s   ]
 4%%M1%-	 &	  )3)C:3?@ *   !>????'	
 ! 4'.K /'=!1)F')FAHQK)F' 2G&;%1 ---W ]$ ! $'s#   B: CC:
C
CCc                 F   > T" U TTS9u  pU [        T5      U-
  T" U5      4$ )N)r<  r   )rP  )r  r%  r=  r1  rF  r   r<  r@  s      rA   estimate_for_budget4choose_saved_values_set.<locals>.estimate_for_budget}
  s=    -FYK.*L )*-==l+ rD   r(  r  gMbP?r  )
      )figsizeo)markerz.4fzoffset points)r   rK  center)
textcoordsxytexthazMemory Budgetz Runtime of Recomputed Componentsz:Pareto Frontier of Memory Budget vs. Recomputation Runtime)exist_okr  _rank_memory_budget_paretor7  z.svgz%Generated Pareto frontier curve at %s)rD  r<  r   )<r   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   r^   rd  r   rX   rY   rC  torch._inductor.fx_utilsr3  r   r   r   r    r0  rq   rS  r  r!  torch.utils._mode_utilsr   visualize_memory_budget_paretor  r   sortmatplotlib.pyplotpyplotfigureplotr{  annotatexlabelylabeltitlegridgcfshowosgetcwdmemory_budget_pareto_dirmakedirsr   r  r  is_initializedget_rankpathrG  r,   savefigr3   r  )+r   r<  rD  r  runtime_optimized_saved_valuesr7  r-  more_aggressive_optionsmore_aggressive_saved_values%aggressive_recomputation_saved_valuesr"  r8  recomputable_banned_nodesr/  must_save_nodesr<   rI  optionsbisectslhsrhsmidpltitemx_valuesy_valuestxtfigfig_dirrank_suffixfig_namerE  r  r'  r1  r3  rF  r7  r+  r>  r,  r   r@  s+   ``                             @@@@@@@@@@@@rA   choose_saved_values_setr  	  s   
 qMA-XYfXgh
 	
 $$AA#)#K#K%+%O%O & E E88O &&!"'',).$)
 (5)%" --6RWW 6% 6 -Y-=-=>L,-KLL|#--:
4= 
 

 &##(%*	 '4Y 7'#  12]B++  % ;HY 2;7) :;mK449T9CSCSTTN
 )
	bgg
 
  !>l K +*A66::k5)-=-G-GG 	
*   -!,a0H,  ! %+!x%! ()Q./112O2OQHQK(2O ,I+H4+H 4,. ,.\ ,,,	 	 '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	 	c
!d 10s0   +2V9!V9-	V>:V>3WWW Wc                   ^^ SSK Jm  S nU4S 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   r<   s     rA   has_collectives3_sync_decision_cross_ranks.<locals>.has_collectives
  sM    %%DUZZ22 ++''+RR	 &
 rD   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r>   r  )rh   r   s     rA   rj   E_sync_decision_cross_ranks.<locals>.has_same_nodes.<locals>.<genexpr>
  s     >,=qFF,=r  zutf-8c              3   4   >#    U  H  nTS    U:H  v   M     g7fr  rQ   )rh   r   
all_inputss     rA   rj   r  
  s     :z!:a=A%zrN  )rG  r   hashlibsha256encode	hexdigestr-  r   r  get_world_sizer   all_gather_objectr  )r   node_strr^   r7  r  r  s       @rA   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  rQ   rQ   rD   rA   rm   ,_sync_decision_cross_ranks.<locals>.<lambda>  s    G (%rD   c                     > T $ r>   rQ   )sync_decision_cross_ranks_strs   rA   rm   r    s    #@rD   r  )torch._subclasses.fake_tensorr  r   r  r  rp  r  r   r   r-  r  rL  r{  rS  rq  r   rX  distributed_c10d_get_object_coll_device
all_reduceReduceOpMAXr   argminr  r   )r   r%  r  r  r   objectsr7  saved_ops_names_all_ranksr<  saved_sizessaved_ops_with_sizesr.  saved_ops_namesop_namesaved_nodes
saved_sizer<   size_of_nodesaved_sizes_tensorpicked_rank_idxri   r  r  s                        @@rA   r2  r2  
  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0J2-K2J7>AKJ<
9KC=KKKK2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   r7  r!   r   NT)propagate_metaeager_input_vals)r  r  r   r  r   r   r   invoke_subgraphr   r   r   r   rX   r{  r   r9  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                   rA   r5  r5    sO   8 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                  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  XU'   US
-  nM     [#        UTTUUU5      $ )Nr   r   r  c              3   R   #    U  H  oc  M  UR                   S:w  d  M  Uv   M     g 7f)Nr   r  )rh   rN  s     rA   rj   !classify_nodes.<locals>.<genexpr>|  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     rA   rj   r    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r>   rQ   )rh   r<   r`   rs   s     rA   rj   r    s1      6,D(( 	-19J-J 	,s   
""	"c              3   <   >#    U  H  u  pUT;   d  M  Uv   M     g 7fr>   rQ   )rh   r/  pr  s      rA   rj   r    s!      -.da!7T2T.s   	r   r!   )rL  r   r   r   r   r   r  r   r  r  r   r  r   r   r$  r   r{  r\   )r  r  r  r<   r  r  r^   r   r!  r"  r#  forward_only_graphra   rc   fw_cntrb   r<  r`   rs   s    `              @@@rA   r(  r(  j  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""(($$#TNaKF ) # rD   )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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R.                   H+  n[1        UR*                  UR*                  S-   5      Ul        M-     M     [        R2                  nUR$                   HC  n[5        UR6                  R9                  S	S5      [:        5      (       d  M4  UR6                  S	   n  O   [=        UU
US
9n[        R>                  (       a  [?        X~5      n[A        [C        [D        U5      5      n[A        [C        S U5      5      n[G        U UUUU
R                   S9u  nnU(       a!  U	(       a  [I        U UU[        U5      5      u  nn[K        U5      n[        RL                  (       a  SSK'J&n  U" UUUU
R                   5        [Q        U5      n[Q        U5      n[S        USS9n[S        USS9n[T        (       Ga  [W        U Vs/ s H  n[Y        U5      [[        U5      4PM     sn5      n[]        S U 5       5      S-  n[^        Ra                  SU5        [^        Ra                  SU5        [c        S UR                   R$                   5       5      n[c        S UR                   R$                   5       5      nUU-  n[e        [(        5      nUR                   R$                   H\  nURf                  U;   d  M  [i        URj                  S5      (       d  M2  U[[        URj                  Rl                  5      ==   S-  ss'   M^     [^        Ra                  S[        U5      [        U5      [        U5      5        [W        URo                  5       [p        Rr                  " S5      SS9n[^        Ra                  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   )r  r  rc   r   r%  r!   rD  )rD  c                 "    [        U 5      (       + $ r>   r  )ri   s    rA   rm   5min_cut_rematerialization_partition.<locals>.<lambda>  s    [^);rD   r  )enable_activation_offloadingr   Tc              3   8   #    U  H  n[        U5      v   M     g 7fr>   )rS  r  s     rA   rj   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     rA   rj   r  0  #      %
"7$77o;UIDII"7r  c              3   \   #    U  H"  oR                   S :X  d  M  UR                  v   M$     g7fr  r  r  s     rA   rj   r  3  r  r  r  z# remat/fw/bw: %d/%d/%drU  zCount of Ops Rematerialized: %s):r   r   r  r   cser/   r   r   r$  r%  r&  r'  r(  r  r`   r@  rc   r  r   r   r   r	  rw   r  r2  activation_memory_budgetr   r   r   rC  r  r2  r   r  r   r  r3  r4  r  ,_activation_offloading.activation_offloadingr1   r5  r2   rq   rS  r   rP  r3   rs  r   r   r   r   r   r  rQ  r  rX  )r  r6  compilerr  r  r   	cse_graphr   r:  r;  r<  r<   r  rD  r%  r  r>  r?  r  r/  sorted_sizestotal_activations_size_gbfw_module_nodesbw_module_nodesremat_nodescountsrematerialized_opss                              rA   r#  r#    s3   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   ' Stracedfnamefigname
clear_metaprogparse_stack_tracedot_graph_shapec                 "   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 )Nrb  zWriting FX graph to file: %s%s)r  r  write_)r  )r  deepcopyr   rX   r{  r   r   rl  rr  splitextr   torch_compile_graph_formatr3   rs  r   FxGraphDrawerget_main_dot_graphr   lstrip)r  r  r  r  r  r  r  r   r<   baseextgr   write_methods                 rA   
draw_graphr  I  s     MM&,,/	2LL&&DDI '  'IDF555HH-t9""+'		A 	
A1hC89LfSENE|UU&rD   )NF)g      @rx  r   r>   )r!   )ry  )fx_graphTNFN)r  r   r  r,  r  loggingrx  r  rl  os.pathr  r!  rW  r   collections.abcr   dataclassesr   r   typingr   r	   r
   r   r   torch._inductor.inductor_primstorch.distributedtorch.fxrX   torch.utils._pytreeutils_pytreer   torch._dynamo.utilsr   r   ;torch._functorch._activation_checkpointing.ac_logging_utilsr   torch._inductorr   r  torch._library.utilsr   torch._loggingr   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_utilsr+   _aot_autograd.logging_utilsr,   _aot_autograd.utilsr-   r.   compile_utilsr/   r0   r1   sympydebug_partitionerr2   r   rW   	getLoggerrR   r3   Loggerr   r:  r>  r5   r\   r   rY   r   r{  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r	  r  r   r   r   r$  r)  r0  rC  rM  rf  rW  rD  r]  rg  rn  rp  rt  r  r  r   r  r  r  r@  r  rC  rS  rZ  cacherd  ri  r4  r  r  r3  r&  r'  r  r$  rd  rK  r@  rL  r  r^  r   r	  r!  r  r2  r5  r(  r#  r  rQ   rD   rA   <module>r     sO           	  	  # $ * 6 6  %   $ $ < 6 + + A ? H L  ) / 3  L  L 
 A ; M H H  %66 t 6''1W^^ 1yy~~		 > > >2      >    T r~~ $ 2>> d  C  I  #$)WWMW "'']W 	?	W
 smW "W XXWtRWW  Gbgg G$ GBGG  bgg $ bgg $ XRWW X XCrww C4 CBbgg B$ BJbgg J$ JKrww K4 Kbgg $ 5rww 54 5J..J
4=$rww-i$y/IJJ$$rww- s d277mU277C<-@@A K88>>K
((--K 
K 
	K
 K\C!88>>C!
((--C! C! 	C!
 C! C! C! XX]]C!L9%,, 95 9"D- G%((-- GD G45 5	5;; 	5 	=G%((.. =GT =G@MG%((.. MGT MG`WWW CL)W 
	W| BF	,Wrww-,W,W ,W "**RWW*=!>	,W
 
,Wj BFT"..T"rww-T" "'']T"
 T" "**RWW*=!>T" 2>>2>>)*T"x :>AEI ..I 
 $,DI#6I  "**RWW*=!>I  2>>2>>)*I X c("# " "277 s :Rbhh R  "Pbggsl!3 PU277C<=P8Q PKBNN Kr~~ K\Z*xx##Z*xx##Z* XX]]Z* XX]]	Z*
 LLZ* Z* HHMMZ* HHMMZ*zR ..R ~~R  ~~R  	R 
 2>>2>>)*R j@ @D @R^^  .K5..5;?5^^5x /3	W&W&W& #W& z"''*+	W&t."eW ePBHH -T-TK-T 5k-T 	-T
 -T $(=-T 5$s)T#Y&'-T` 05 5 5 5(N\ u	u	u	 
"'']	u	pNN/3EHHMM/BNbM`2p g  :>g ..g  $,DI#6g  2>>2>>)*g Z ,0#%)'HH  '' ' 	'
 5d3i(
)' ' c]' 
'rD   