
    Vh\'                    *   d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlZddlmZmZmZ dd	lmZmZmZ dd
lmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> 	 ddl?m@Z@ erddlBmCZC ddlDmEZEmFZF  ede      ZGdQdRdZHdRdZIdeJeKe<f   fdZLd ZMh dZNd ZO G d de<      ZP G d d eP      ZQ G d! d"eP      ZR G d# d$e<      ZS G d% d&eS      ZT G d' d(eP      ZU G d) d*eU      ZV G d+ d,eQ      ZW G d- d.eW      ZX G d/ d0eQ      ZYdRd1ZZ G d2 d3eP      Z[ G d4 d5e<      Z\ G d6 d7e<      Z]d8 Z^dRd9Z_ G d: d;eQ      Z` G d< d=eQ      Za G d> d?eQ      Zb G d@ dAe<      Zc G dB dCe<      Zd G dD dEe<      Ze G dF dGe<      ZfddHlDmgZgmhZh  G dI dJeh      Zi ei       Zj G dK dLe<      Zk G dM dNe<      Zl G dO dPe<      Zmy# eA$ r dZ@Y ew xY w)Sa  
Function-related variable tracking classes for Dynamo's symbolic execution.

This module contains classes that track different types of functions during graph
compilation, including:
- User-defined functions and methods
- Built-in functions and methods
- Wrapped functions (e.g. from decorators)
- Special function types (e.g. functools.partial)
- Triton kernels and related function types

These classes are responsible for:
- Tracking function calls and their arguments
- Managing function closures and cell variables
- Handling function attributes and special methods
- Maintaining guards for function identity and closure contents
- Supporting function inlining and specialization
- Enabling proper symbolic execution of different function types

The variable trackers here work together with the rest of Dynamo to enable
accurate graph capture while handling Python's various function-related behaviors.
    N)Sequence)AnyCallableOptionalTYPE_CHECKINGTypeVar)Never)patch   )graph_break_hints	polyfills	variables)create_call_functioncreate_rot_nis_generator)
get_dynamo_observed_exceptionhandle_observed_exceptionInfiniteGeneratorErrorObservedExceptionObservedGeneratorExitObservedUserStopIterationraise_observed_exception	SkipFrameunimplemented_v2Unsupported)GuardBuilderinstall_guard)
AttrSourceConstantSourceDefaultsSourceGetItemSource)	check_constant_argscheck_unspec_or_constant_argscmp_name_to_op_mappingcountersidentityis_functionis_wrapper_or_member_descriptoristype	make_cell   )typestrValueMutationNewVariableTrackerConstantVariable)_fsdp_param_group)InstructionTranslator)TritonGridTypeTritonKernelType_F)boundc                     t        |t              r|S |st        j                  | |      S t        j                  j                  ||      S N)
isinstancer.   buildr   LazyVariableTrackercreate)txvalsources      Q/home/dcms/DCMS/lib/python3.12/site-packages/torch/_dynamo/variables/functions.pywrap_bound_argrA   W   sB    #'
$$R-- ,,33C@@    c                     t        |j                               D ]+  \  }}t        |t        t        f      st        | |      ||<   - y r8   )listitemsr9   tupledictrA   )r=   resultkvs       r@   wrap_args_kwargsrK   c   s>    V\\^$ .1a%'&r1-F1I.rB   rH   c                     | j                   j                  }|j                  D ]<  }|j                         }||v r!|j	                  ||j                  |             |||<   > y)z
    Update `result` to add mapping from local name to new cells created
    directly by `code`, or update SideEffects in `parent` if the a local cell is
    already in `result` (cell argument).
    N)outputside_effectsco_cellvarstrack_cell_new
store_cellpop)parentrH   coderN   namenew_cells         r@   init_cellvarsrW   j   sa     ==--L    ..06> ##Hfjj.>?t rB   c                     ddl m}  || ||||      }||_        t        |t              rddlm}	 t         |	|            }|t        |t              sJ ||_        |S )Nr   )FunctionTypepairwise)	typesrY   __kwdefaults__r9   rF   	itertoolsr[   rG   __annotations__)
rT   	f_globalsrU   defaultsclosure
kwdefaultsannotationsrY   funcr[   s
             r@   _create_nested_fnrf   {   sa     #ixAD$D+u%&8K01 *[$"???&DKrB   >   __doc____code____closure____globals____defaults__r]   r_   c                 &   |xr t        ||      }	 t        j                  ||      }|t
        v rt        ||      }|r t        j                  j                  |      S t        j                  |       S # t        $ r t	        t        |        Y gw xY wr8   )r   inspectgetattr_staticAttributeErrorr   fn_known_dunder_attrsgetattrr   r;   r<   r.   r:   )r=   fnr?   rU   subobjs        r@   fn_var_getattrrt      s    0
640F5''D1 $$T",,33FFCC  V,,  5 	!45s   A4 4BBc                   P    e Zd Zd Zd Z	 	 	 	 	 	 	 	 ddZdddedefdZd	 Z	d
 Z
y)BaseUserFunctionVariablec                 6    | j                         j                  S r8   get_codeco_filenameselfs    r@   get_filenamez%BaseUserFunctionVariable.get_filename       }}***rB   c                 6    | j                         j                  S r8   ry   co_namer{   s    r@   get_namez!BaseUserFunctionVariable.get_name       }}&&&rB   r=   r2   returnc                 L    |j                  | g | j                         ||      S r8   )inline_user_function_return	self_argsr|   r=   argskwargss       r@   call_functionz&BaseUserFunctionVariable.call_function   s,     --d4Ndnn6F4N4NPVWWrB   rU   c                     d}	 t        | j                         |      }t
        j                  j                  |      S # t        $ r |dk(  rt        | t              rd}Y Aw xY w)NF__name__T)hasattrget_functionNotImplementedErrorr9   NestedUserFunctionVariabler   r0   r<   r|   r=   rU   rH   s       r@   call_obj_hasattrz)BaseUserFunctionVariable.call_obj_hasattr   se     	T..0$7F ))0088 # 	z!j7Q&R	s   =  A A c                 n    t        t        j                  | j                               j                        S r8   )rD   rm   	signaturer   
parametersr{   s    r@   inspect_parameter_namesz0BaseUserFunctionVariable.inspect_parameter_names   s'    G%%d&7&7&9:EEFFrB   c                     i S r8    r|   r=   s     r@   closure_varsz%BaseUserFunctionVariable.closure_vars       	rB   Nr=   r2   r   list[VariableTracker]r   dict[str, VariableTracker]r   r.   )r   
__module____qualname__r}   r   r   strr.   r   r   r   r   rB   r@   rv   rv      sd    +'X#X &X -	X
 
X
9)
914
9	
9GrB   rv   c                        e Zd ZdZddhej
                  Zed        Zdd fdZ fdZ	d Z
d	 Zd
 Zd Zd Zd Zdeeef   fdZdddefdZdddedefdZ	 	 	 	 	 	 	 	 d fdZ xZS )UserFunctionVariablez-Some unsupported user-defined global functionrr   is_constantc                 f    t        |j                  t        j                                | ||      S Nr?   )r   
make_guardr   CLOSURE_MATCHclsvaluer?   s      r@   create_with_sourcez'UserFunctionVariable.create_with_source   s(    f''(B(BCD5((rB   r   c                 ,   t        |   di | t        |dd      rd| _        nd| _        t	        |t
        j                  t        j                  j                  f      sJ dt        |       d|        t        j                  |d|      }|| _        y )N_dynamo_marked_constantFTzexpected FunctionType found  _torchdynamo_inliner   )super__init__rq   r   r9   r\   rY   torchjitScriptFunctionr,   rm   rn   rr   r|   rr   r   r   	__class__s       r@   r   zUserFunctionVariable.__init__   s    "6"20%8#D$D"u115993K3KLM 	
*72;-q=	
M ##B(=rB&(rB   c                 X    t        | t              r| j                  S t        |          S r8   )r)   r   rr   r   as_python_constantr|   r   s    r@   r   z'UserFunctionVariable.as_python_constant   s%    $,-77Nw)++rB   c                     g S r8   r   r{   s    r@   r   zUserFunctionVariable.self_args   r   rB   c                     | j                   S r8   rr   r{   s    r@   r   z!UserFunctionVariable.get_function       wwrB   c                 .    | j                   j                  S r8   )rr   rh   r{   s    r@   ry   zUserFunctionVariable.get_code   s    wwrB   c                 "    t         j                  S r8   r\   rY   r{   s    r@   python_typez UserFunctionVariable.python_type       !!!rB   c                 4    t        | j                  dd       d uS N__self__)rq   rr   r{   s    r@   has_selfzUserFunctionVariable.has_self   s    tww
D1==rB   c                 .    | j                   j                  S r8   )rr   rj   r{   s    r@   get_globalsz UserFunctionVariable.get_globals  s    ww"""rB   c                    | j                   rJ |j                  j                  }t        j                  t
        |      }| j                  }|j                  xs g }t        |      D 	cg c])  \  }}	| j                  dnt        | j                  |      + }
}}	t        j                  |j                  |j                  |j                  t!        t#        ||
      D cg c]  \  }} |||       c}}      |j$                        }|j&                  r||j&                  D ci c])  }|| j                  dnt        | j                  |d      + }}|j&                  j)                         D ci c]  \  }}| ||||          c}}|_         t+        j,                  |      j.                  |i |}|j1                          t3        |j4                  j)                               }t7        ||       t9        |||j                         | j                  j$                  xs d}t;        |      t;        | j                  j                  j<                        k(  sJ t#        t?        j@                         | j                  j                  j<                  |      D ]  \  }}}|j                  jB                  }||v r||   }n| j                  rbtE        tG        | j                  d      |      }tG        |d      }	 tI        jJ                  ||jL                  |      }|jU                  |||      }n4	 tI        jJ                  ||jL                        }|jU                  d||      }|||<    |S c c}	}w c c}}w c c}w c c}}w # tN        $ r tQ        jR                         }Y w xY w# tN        $ r tQ        jR                         }Y uw xY w)	z
        Assume `args` and `kwargs` are VariableTracker arguments for a call to
        this function, create new bindings for initial locals.
        )r=   N)r>   r?   T)is_kwr   ri   cell_contents)+r   rM   root_tx	functoolspartialrA   rr   rk   	enumerater?   r    r\   rY   rh   rj   r   rF   zipri   r]   rE   rm   r   bindapply_defaultsrG   	argumentsrK   rW   lenco_freevarsr^   countrN   r!   r   r.   r:   r   
ValueErrorr   DeletedVariabletrack_cell_existing)r|   rS   r   r   r   wraprr   ra   idx_defaults_sourcesargr?   	fake_funcrI   kwdefaults_sourcesrJ   r6   rH   rb   rU   cellrN   cell_varclosure_cellclosure_cell_contentscontents_vars                              r@   	bind_argszUserFunctionVariable.bind_args  s   
 ####--''  G<!%??(b $H-
Q KK'D^DKK-MM
 
 &&KKNNKK (+85E'F#V S0 NN
	  **"  {{* 'QdCD" " --335(Aq 4A&8&;<<(I$
 2!!),114B6Beoo++-.&)ffbkk2''%%+7|s477#3#3#?#?@@@@"OOtww//;;W 
 "	$OCt "==55L|#'-,t{{M:C  )3<(Q%?#2#8#8 2 24I$L (;; $?#2#8#8ASAS#TL (;;D$U#F4LE"	$H U
"(< " ?#,#<#<#>L? " ?#,#<#<#>L?s<   *.M-M3$.M91M>;!N1 N'N$#N$'OOr=   r2   rU   c                     |t         v rt        j                  | |      S t        || j                  | j
                  |      S r8   )r$   r   GetAttrVariablert   rr   r?   r|   r=   rU   s      r@   var_getattrz UserFunctionVariable.var_getattr[  s7    )),,T488b$''4;;==rB   c                 l    t        | j                  |      }t        j                  j	                  |      S r8   )r   rr   r   r0   r<   r   s       r@   r   z%UserFunctionVariable.call_obj_hasattr`  s+     $'))0088rB   c           
      v   | j                   t        j                  j                  u r  t	        j
                  | j                         j                  |i |}|j                  d   }t        |t              sS|j                         }d|j                   d}t        dd| j                   d| d| d|g t        j                         t        |t               s,|j#                         }d	| d
}t        d|  |d| ddg       |j                   }	t%        j&                  |	d      S | j(                  r't+        || j                   | j#                         ||      S |j,                  j.                  j0                  r|j,                  j.                  j2                  sq	 ddlm}
 |
h| j                   |
j:                  |
j<                  fv rDt        j                  j>                  j3                  |      5  t@        |   |||      cd d d        S t@        |   |||      S # t8        $ r d }
Y w xY w# 1 sw Y   +xY w)Nr   z=`nonstrict_trace` expects a callable, but got value of type <>zTypeError from user codezcall_function(, )gb_typecontextexplanationhintsz(Applying `nonstrict_trace` to function <zk>; however, `nonstrict_trace` currently requires the function to be defined outside `torch.compile` region.zLimitation of `nonstrict_tracezmake sure definition of z is outside z`torch.compile` regionTnonstrict_traceable)	FSDPState)"rr   r   _dynamononstrict_tracerm   r   r   r   r9   rv   r   r   r   r   r   
USER_ERRORr   r   r   TorchInGraphFunctionVariabler   invoke_and_store_as_constantrM   current_tracerunder_activation_checkpoint#allow_side_effects_under_checkpoint/torch.distributed.fsdp._fully_shard._fsdp_stater   	Exception_pre_forward_post_forwardrN   r   r   )r|   r=   r   r   r6   fn_vartypmsgfn_namerr   r   r   s              r@   r   z"UserFunctionVariable.call_functionf  s*    77emm3333G%%dgg.33TDVDEZZ]Ff&>?((*UVYVbVbUccde 6,TZZL4&6(!L #*55	 f&:; //+@	  Ju  v <#f #27)<H0	 B99"RVWW/DGGT]]_dF  II$$@@II,,PP!U $&&''5 * ]]//SSTVW C 70T6BC Cw$Rv66  ! 	!C Cs   H 2H/H,+H,/H8Fr   Nr   )r   r   r   rg   rv   _nonvar_fieldsclassmethodr   r   r   r   r   ry   r   r   r   rG   r   r.   r   r   r   r   __classcell__r   s   @r@   r   r      s    7 	 
"	0	0N ) ))", ">#Uc?6J1K Un>5 >S >
9)9149	987#87 &87 -	87
 
87 87rB   r   c                   J     e Zd Zdd fdZed        Z	 	 	 	 	 	 	 	 ddZ xZS )BuiltinMethodVariablec                 j    t        |   di | t        |t        j                        sJ || _        y Nr   )r   r   r9   r\   BuiltinMethodTyperr   r   s       r@   r   zBuiltinMethodVariable.__init__  s0    "6""e55666rB   c                     | j                   }| j                  }|t        u xr |dk(  xs t        |      t        u xr |dk(  S )N__new____contains__)r   r   rF   type	frozenset)objmethod_selfmethod_names      r@   is_supported_builtin_methodz1BuiltinMethodVariable.is_supported_builtin_method  sI    llll u$A	)A 
*L{n/L	
rB   c                     | j                   j                  }| j                   j                  }| j                  xr t	        | j                  d      }t        j                  |||      }|j                  ||||      S r   )rr   r   r   r?   r   r.   r:   call_method)r|   r=   r   r   r  rU   
obj_sourceobj_vts           r@   r   z#BuiltinMethodVariable.call_function  sf     gg&&ww[[HZZ%H
 &&r;
C!!"dD&99rB   r  r  r   )r   r   r   r   staticmethodr  r   r  r  s   @r@   r  r    sG    
 
 

:#
: &
: -	
:
 

:rB   r  c            
            e Zd Zdej                  ded   f fdZd Zd Zd Z	d Z
d	 Zd
 Z d ZeZd Zd Zd Zd Zd Zd Zd Zdej,                  fdZdee   fdZd Zd Zd Zdddeddddddf
 fd Z xZ S )!LocalGeneratorObjectVariablerT   inline_tracerr2   c                 N    t        |   di | || _        || _        || _        y r  )r   r   rT   r`   r&  )r|   rT   r`   r&  r   r   s        r@   r   z%LocalGeneratorObjectVariable.__init__  s+     	"6"	"*rB   c                     | j                   S r8   )rT   r{   s    r@   ry   z%LocalGeneratorObjectVariable.get_code  s    yyrB   c                 6    | j                         j                  S r8   rx   r{   s    r@   r}   z)LocalGeneratorObjectVariable.get_filename  r~   rB   c                 6    | j                         j                  S r8   r   r{   s    r@   r   z%LocalGeneratorObjectVariable.get_name  r   rB   c                     t         r8   )r   r{   s    r@   r   z)LocalGeneratorObjectVariable.get_function  s    !!rB   c                      yNFr   r{   s    r@   r   z%LocalGeneratorObjectVariable.has_self      rB   c                 "    | j                         S r8   )r   r{   s    r@   r   z%LocalGeneratorObjectVariable.__name__  s    }}rB   c                 V    | j                   j                   d| j                          dS )N(r   )r   r   r   r{   s    r@   __str__z$LocalGeneratorObjectVariable.__str__  s'    ..))*!DMMO+<A>>rB   c                    ddl m} ddlm}m}m}  |j                         } ||      } ||      } ||      }	|5  |5  |	5  | j                  |      }
|
j                  s| j                  |      | _
        t        j                  | j                        j                  |       d d d        d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)Nr   )"disallow_side_effects_in_generator)r2    save_and_restart_speculation_log(temporarely_allow_writes_to_output_graph)torch._dynamo.side_effectsr4  torch._dynamo.symbolic_convertr2   r5  r6  
current_tx_get_inline_tracergenerator_exhaustedforce_unpack_var_sequenceremaining_itemsr   ListIteratorVariablereconstruct)r|   codegenr4  r2   r5  r6  r=   savedisallowtemptracers              r@   r?  z(LocalGeneratorObjectVariable.reconstruct  s    Q	
 	
 ."--//35b97; 	V8 	VT 	V,,R0F--'+'E'Eb'I$**4+?+?@LLWU		V 	V 	V 	V 	V 	V 	V 	V 	Vs;   CC	A"B=$C	,C=CC		C	CCc                 <    | j                   j                  |||      S r8   )rr   r   r   s       r@   r   z&LocalGeneratorObjectVariable.bind_args  s    ww  T622rB   c                     | j                   S r8   r`   r{   s    r@   r   z(LocalGeneratorObjectVariable.get_globals      ~~rB   c                 "    t         j                  S r8   )r\   GeneratorTyper{   s    r@   r   z(LocalGeneratorObjectVariable.python_type  s    """rB   c                 p    ddl m} | j                  |j                  || g i       | _        | j                  S Nr   )InliningInstructionTranslator)r8  rM  r&  build_inline_tracer)r|   r=   rM  s      r@   r:  z/LocalGeneratorObjectVariable._get_inline_tracer  s;    P%!>!R!RD"b"D !!!rB   c                 d   | j                  |      }| j                         rt        t        |       	 t	        j
                  t        dt        d   i      5  |j                         cd d d        t        dxx   t        d   z  cc<   S # 1 sw Y   nxY wnf# t        $ r}|d }~wt        $ r  t        $ rC}t        j                  j                  j                  | j                                t         |d }~ww xY w	 t        dxx   t        d   z  cc<   y # t        dxx   t        d   z  cc<   w xY w)Nunimplementedinline_call)r:  _is_generator_exhaustedr   StopIterationr
   rG   r%   inline_call_r   r   r   r   r   
eval_frame	skip_codery   r   )r|   r=   rD  es       r@   next_variablez*LocalGeneratorObjectVariable.next_variable  s   ((,'')$]B7	A H8O&PQ -**,- - _%-)@@%- - -  	G% 	 	#MM$$..t}}?"	#- _%-)@@%H_%-)@@%sM   #B B&	B BB D 	C8B  C85>C33C88D D/c                      yr-  r   r   s     r@   has_unpack_var_sequencez4LocalGeneratorObjectVariable.has_unpack_var_sequence  r.  rB   r   c                      yNTr   r   s     r@   has_force_unpack_var_sequencez:LocalGeneratorObjectVariable.has_force_unpack_var_sequence"  s    rB   c                     g }	 	 |j                  | j                  |             "# t        $ r t        |       Y |S w xY wr8   )appendrX  r   r   )r|   r=   rH   s      r@   r<  z6LocalGeneratorObjectVariable.force_unpack_var_sequence%  sL    d0045  - )"-s    & >>c                     | j                  |      }	 |j                  |       y # t        $ r}|j                  |       Y d }~y d }~ww xY wr8   )r:  _raise_exception_variabler   exception_handler)r|   r=   excrD  rW  s        r@   _setup_exceptionz-LocalGeneratorObjectVariable._setup_exception/  sH    ((,	(,,S1  	( $$Q''	(s   % 	A	AA	c                 T    | j                   d u xs | j                   j                  dk(  S )Nr   )r&  instruction_pointerr{   s    r@   _is_generator_just_startedz7LocalGeneratorObjectVariable._is_generator_just_started8  s*    !!T)XT-?-?-S-SWX-XXrB   c                 0    t        | j                  dd      S )Nr;  F)rq   r&  r{   s    r@   rR  z4LocalGeneratorObjectVariable._is_generator_exhausted;  s    t))+@%HHrB   r=   rU   r   r   r   r   r.   c                    |dk(  r| j                  |      S |dk(  r| S |dk(  rp| j                         r-t        |      r"t        d |D              st	        t
        |       | j                  |      }|j                  |       | j                  |      S |dk(  r| j                  |      }| j                         s| j                         rd|_	        t        j                  d       S 	 | j                  |t        j                  t        d             t        j                   dk\  r5|j"                  j$                  d	k(  rd|_	        t        j                  d       S 	 | j                  |      rt	        t(        |       n|d
k(  r| j                  |      }	 | j                  |t        |      dk(  r|d   n|d          | j                  |      }t1        dt2        fi       }	 | j                  |t        j                  |d             | j                  |       t	        t(        |       |S t6        | q  ||||       y # t&        $ r d|_	        t        j                  d       cY S w xY w# t&        $ r d|_	        t        j                  d       cY S t*        $ r |j,                  J |j,                  cY S w xY w# t.        $ r  w xY w# t5        |      $ r Y |S w xY w)N__next____iter__sendc              3   \   K   | ]$  }t        |t              xr |j                  d u  & y wr8   )r9   r0   r   ).0r   s     r@   	<genexpr>z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>Q  s1       s$45K#))t:KKs   *,closeTr   )      CALL_INTRINSIC_1throwrq  r+   r   __InternalThrowException)rX  rg  r   allr   	TypeErrorr:  	push_manyrR  r;  r   r0   rd  ExceptionVariableGeneratorExitsysversion_infonext_instructionopnamer   RuntimeErrorr   symbolic_resultr   r  r  r   r   r   )	r|   r=   rU   r   r   rD  retvalexc_typer   s	           r@   r   z(LocalGeneratorObjectVariable.call_method>  s    :%%b))ZKV^ ..0SY  #  -Y;,,R0FT"%%b))W_ ,,R0F..0D4P4P4R-1* 11$778%%	33M2F( $$///66:LL15F.$55d;;.%%b),\2> W_ ,,R0F
 %%bSY!^$q'aQ
 ''+F| 6bIH?%%b)*E*EhPR*ST""2&
 )v>MBdF3a ) 8-1* 11$778 ) 8-1* 11$77, .
 --999---., % N 1:  MsI   'A1H; !I& (J5 7K ;%I#"I#&%J2"J21J25K KK)!r   r   r   r\   CodeTyper   r   ry   r}   r   r   r   r2  __repr__r?  r   r   r   r:  rX  rZ  builtinsboolr]  rD   r.   r<  rd  rg  rR  r   r   r  r  s   @r@   r%  r%    s    
+nn
+   78	
++'"? HV&3#"A.8== tO/D (YIz4#z4 z4 &	z4
 -z4 
z4 z4rB   r%  c                       e Zd ZdZy)4ContextlibContextManagerLocalGeneratorObjectVariablez
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager

        It is a special case of a generator function as we do not allow return a context manager
        from a torch.compile function.
    N)r   r   r   rg   r   rB   r@   r  r    s    rB   r  c                   R     e Zd ZdZeddef fdZd Zd Z	 	 	 	 	 	 	 	 ddZ	 xZ
S )	LocalGeneratorFunctionVariablezxfunctions that behaves like iterators

    .. note::

        This is a wrapper around (Nested)UserFunctionVariable
    )generator_clsvtc                @    t        |   di | || _        || _        y r  )r   r   r  r  )r|   r  r  r   r   s       r@   r   z'LocalGeneratorFunctionVariable.__init__  s$     	"6"*rB   c                     || j                   j                  j                         v rt        | |      S t        | j                  |      S r8   )r   __dict__keysrq   r  )r|   rU   s     r@   __getattr__z*LocalGeneratorFunctionVariable.__getattr__  s;    4>>**//114&&tww%%rB   c                 6    ddl m} |j                  || ||      S rL  )r8  rM  rN  )r|   r=   r   r   rM  s        r@   _build_inline_tracerz3LocalGeneratorFunctionVariable._build_inline_tracer   s$    P,@@	
 	
rB   c                    t        | j                  j                               sJ | j                  |||      }| j                  j                         }| j                  j	                         }| j                  |||| j                        S r   )r   r  ry   r  r   r  r?   )r|   r=   r   r   r&  rT   r`   s          r@   r   z,LocalGeneratorFunctionVariable.call_function*  s     DGG,,.///11"dFCww!GG'')	 !!;;	 " 
 	
rB   r   )r   r   r   rg   r%  r.   r   r  r  r   r  r  s   @r@   r  r    sO     3		+	+&


#
 &
 -	

 

rB   r  c                   ,     e Zd ZdZ fdZ fdZ xZS )3FunctionDecoratedByContextlibContextManagerVariablezm
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager
    c                 2    t        |   |fdt        i| y )Nr  )r   r   r  )r|   r  r   r   s      r@   r   z<FunctionDecoratedByContextlibContextManagerVariable.__init__H  s%    	
N	
 	
rB   c                     t         |   |||      }t        |t        j                  j
                  j                        sJ d|_        |S r\  )r   r  r9   r   r   symbolic_convert&InliningGeneratorInstructionTranslatoris_generator_from_ctx_manager)r|   r=   r   r   rD  r   s        r@   r  zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracerO  sO    
 -b$?MM**QQ
 	
 
 04,rB   )r   r   r   rg   r   r  r  r  s   @r@   r  r  ?  s    
 rB   r  c                   v     e Zd ZdZd fdZdefdZd Zd Z	 	 	 	 	 	 	 	 d fd	Z	 fd
Z
dddef fdZ xZS )UserMethodVariablez$Some unsupported user-defined methodr   c                 6    t        |   dd|i| || _        y )Nrr   r   )r   r   r  )r|   rr   r  r   r   s       r@   r   zUserMethodVariable.__init__`  s    )B)&)rB   c                 h    | j                   j                   d| j                   d| j                   dS )Nr1  r   r   )r   r   rr   r  r{   s    r@   r  zUserMethodVariable.__repr__d  s.    ..))*!DGG9BtxxjBBrB   c                     | j                   gS r8   )r  r{   s    r@   r   zUserMethodVariable.self_argsg  s    zrB   c                 "    t         j                  S r8   )r\   
MethodTyper{   s    r@   r   zUserMethodVariable.python_typej  s    rB   r=   r2   c                    ddl m}  || j                        rHg | j                         |}t	        j
                  | j                  d      }|j                  |||      S |j                  j                         rt        | j                  t        j                        ryt        | j                  dd      }||j                  d      r|dk7  s| j                  r| j                  j                  || j                  j                   ||| j                  	      S t"        d| j                  t"        j$                  j&                  u r>t	        j(                  | j                        j                  || j                  g||      S | j                  rQt        | j                  j*                  | j                  j                         }t-        ||| j/                         ||      S t0        	|   |||      S )
Nr   )is_nonstrict_trace_callableTr   r    z	torch.nn.ztorch.nn.utils.parametrize)constant)trace_rulesr  rr   r   r   r   r   rM   is_root_tracerr9   r  NNModuleVariablerq   
startswithr   r   r   r1   FSDPParamGroupuse_training_stateTorchCtxManagerClassVariabler   r   r   r   )
r|   r=   r   r   r  	call_argsvarmodule_attrrr   r   s
            r@   r   z UserMethodVariable.call_functionm  s    	>&tww/2$..*2T2I88TC $$RF;; 99##%*HHi00+
 "$''<<K '**;7#??##xx++(($AQAQ ,   ),;;NNN99$''BPPTXX%%v  )9)9:B/BvVVw$Rv66rB   c                 &    t         |          dd  S Nr+   )r   r   r   s    r@   r   z*UserMethodVariable.inspect_parameter_names  s    w.044rB   rU   c                     | j                   xr t        | j                   |      }|dk(  r| j                  S |dk(  r!t        j                  || j
                  |      S t        |   ||      S )Nr   __func__)r?   r   r  r.   r:   rr   r   r   )r|   r=   rU   r?   r   s       r@   r   zUserMethodVariable.var_getattr  s`    >DKK!>:88O:"((TWWf==w"2t,,rB   r  r   )r   r   r   rg   r   r   r  r   r   r   r   r   r  r  s   @r@   r  r  ]  sm    .C# C ;7#;7 &;7 -	;7
 
;7z5-5 -S - -rB   r  c                   <     e Zd Zd fdZ	 	 	 	 	 	 	 	 d fdZ xZS )WrappedUserMethodVariablec                     |j                  dd        |j                  dd        t        |   |j                  |j                  fi | || _        || _        y Nrr   r  )rR   r   r   rr   r  wrappedr   r|   r  r   r   r   s       r@   r   z"WrappedUserMethodVariable.__init__  sI    

4

5$W[[;F;rB   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r8   r   enterr   r   exitr|   r=   r   r   rH   r   s        r@   r   z'WrappedUserMethodVariable.call_function  A     	2&r48"rB   r  r   r   r   r   r   r   r  r  s   @r@   r  r    8    	#	 &	 -		
 
	 	rB   r  c                   <     e Zd Zd fdZ	 	 	 	 	 	 	 	 d fdZ xZS )WrappedUserFunctionVariablec                     |j                  dd        |j                  dd        t        |   |j                  fi | || _        || _        y r  )rR   r   r   rr   r  r   r  s       r@   r   z$WrappedUserFunctionVariable.__init__  sC    

4

5$.v.rB   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r8   r  r  s        r@   r   z)WrappedUserFunctionVariable.call_function  r  rB   r  r   r  r  s   @r@   r  r    r  rB   r  c                     d }|D cg c]
  } ||       }}|j                         D ci c]  \  }}| ||       }}} ||i |}	| j                  j                  |	|t        |            S c c}w c c}}w )Nc                 v    t        | t        j                        r| j                         S | j	                         S r8   )r9   r   TensorVariableget_real_valuer   )xs    r@   convertz-invoke_and_store_as_constant.<locals>.convert  s0    a112##%%##%%rB   r   )rE   rM   register_attr_or_moduler   )
r=   rr   rU   r   r   r  r  rI   rJ   ress
             r@   r   r     s    &
 !%%1GAJ%D%(.71am7F7
d
f
C99,,d# -   &7s
   A1A6c                   z     e Zd Zdhej                  Z	 d	 d fdZd Zd Zd Zd Z	d Z
d Zd	 Zd
 Zd Z xZS )r   r`   c	                 L   t        
|   di |	 t        |j                         t              sJ t        |j                         t
        j                        sJ t        |t              sJ || _        || _	        || _
        || _        || _        || _        || _        || _        y r  )r   r   r9   r   r   r\   r  rG   r
  rT   r`   ra   rc   rd   rb   
wrapped_fn)r|   r
  rT   r`   ra   rc   rd   rb   r  r   r   s             r@   r   z#NestedUserFunctionVariable.__init__  s     	"6"'446<<<$113U^^DDD)T***	" $&5?rB   c                     g S r8   r   r{   s    r@   r   z$NestedUserFunctionVariable.self_args  r   rB   c                 6    | j                   j                         S r8   )rT   r   r{   s    r@   ry   z#NestedUserFunctionVariable.get_code  s    yy++--rB   c                 "    t         j                  S r8   r   r{   s    r@   r   z&NestedUserFunctionVariable.python_type  r   rB   c                 D   | j                   rt        t        j                  | j                  j                         | j                  | j                  j                               }| j                  r| j                  j                         |_	        | j                  r| j                  j                         |_        | j                  rZ| j                  j                         }t        |t              rddlm} t#         ||            }t        |t"              sJ ||_        |S )Nr   rZ   )rb   r   r\   rY   rT   r   r`   r
  ra   rk   rc   r]   rd   r9   rF   r^   r[   rG   r_   )r|   re   rd   r[   s       r@   r   z'NestedUserFunctionVariable.get_function  s    <<%%!!II((*NNLL++-

 == $ @ @ BD??"&//"D"D"FD**==?K+u-."8K#89 k4000#.D rB   c                     | j                   d uS r8   )rb   r{   s    r@   has_closurez&NestedUserFunctionVariable.has_closure0  s    ||4''rB   c                      yr-  r   r{   s    r@   r   z#NestedUserFunctionVariable.has_self3  r.  rB   c                     | j                   S r8   rG  r{   s    r@   r   z&NestedUserFunctionVariable.get_globals6  rH  rB   c                 H   | j                         }t        j                  || j                  | j                  j                         | j                  rt        | j                  j                        nd t        d t        t        | j                         j                              D                    }| j                  r| j                  j                         |_         t        j                   |      j"                  |i |}|j%                          t'        |j(                  j                               }t+        |j,                  j.                  |       t1        |||       t3        |j                        D ])  \  }}	|	|vsJ | j4                  j                  |   }
|
||	<   + |S )Nc              3   2   K   | ]  }t        d         y wr8   )r*   )rn  r   s     r@   ro  z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>@  s     Sa)D/Ss   )ry   r\   rY   r`   r
  r   ra   rF   rE   ranger   r   rc   keys_as_python_constantr]   rm   r   r   r   rG   r   rK   rM   r   rW   r   rb   )r|   rS   r   r   rT   re   r6   rH   r   rU   r   s              r@   r   z$NestedUserFunctionVariable.bind_args9  sH   }}!!NNLL++-*.--E$--%%&TS5T]]_5P5P1Q+RSS
 ??"&//"I"I"KD,!!$',,d=f=eoo++-...7ffd+"4#3#34 	 ICv%%%<<%%c*DF4L	 
 rB   c                    j                  fd        | j                         j                  j                  | j                        g        t        j                  | j                  j                  j                               | j                  r | j                         n!j                  j                  d       g       | j                  r | j                         n!j                  j                  d       g       | j                  r | j                         n!j                  j                  d       g       | j                  r=	 | j                  j                         }j                  j                  |      g       n!j                  j                  d       g       j                  t!        dd             | j"                  rwj                  fd        | j"                         j                  t!        dd             j                  t%        d             j                  t!        dd             y y # t        $ r  | j                         Y w xY w)Nc                  0     j                  t        d      S )Nrf   )load_import_fromr   r@  s   r@   <lambda>z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>S  s    G,,X7JK rB      Fc                  (     j                  dd      S )Nr   wrapsr  r  s   r@   r  z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>w  s    00gF rB   r+   r   T)add_push_nullrT   extend_outputcreate_load_const_uncheckedr`   r0   r<   r   r   ra   create_load_constrb   rc   rd   r   r   r   r  r   )r|   r@  rd   s    ` r@   r?  z&NestedUserFunctionVariable.reconstructQ  s   K	
 			wBB4>>RST ''		(?(?@A==DMM"!!7#<#<T#B"CD<<DLL!!!7#<#<T#B"CD??DOO$!!7#<#<T#B"CD*"..AAC%%88EF !!7#<#<T#B"CD21e<=??!!F DOO$!!"6q%"@A!!,q/2!!"6q$"?@  ' *(()*s   ;I I32I3r8   r  )r   r   r   rv   r  r   r   ry   r   r   r  r   r   r   r?  r  r  s   @r@   r   r     s_    	!	0	0N  @ 
@6."0(0+ArB   r   c                        e Zd Zddhej                  Zdd fdZd Zed        Z	 	 	 	 	 	 	 	 ddZ	dd	Z
ddd
efdZ xZS )SkipFunctionVariabler   reasonc                 @    t        |   di | || _        || _        y r  )r   r   r   r  )r|   r   r  r   r   s       r@   r   zSkipFunctionVariable.__init__  s!    "6"
rB   c                     | j                   S r8   r   r{   s    r@   r   z'SkipFunctionVariable.as_python_constant  s    zzrB   c                 |    t        |      s(t        |j                  t        j                                | ||      S r   )r(   r   r   r   FUNCTION_MATCHr   s      r@   r   z'SkipFunctionVariable.create_with_source  s2    .u5 &++L,G,GHI5((rB   r=   r2   c           	         t        j                  | j                  dd      r2t        dt	        | j                        d| j                   ddg       y | j                  t
        j                  j                  u r?|j                  dd       }|r|j                         }t        d	d
| d| dd| dg       y t        | j                  dd      }t        | j                  dd       }|dn
t	        |      }	 t        j                  | j                        }d| d| d}	d| dg}
d|vr|
d| d| ddgz  }
|d+k(  rd,}	g }
| j"                  r| j"                  nd-}t        d.d/| d0| d1| |	|
       y # t        $ r ddh}||v rd| d | d}	d!d"g}
n|\|j                  d#      rKd$| d | d }	d%g}
t
        j                  j                  j                  |	d&z   d&j!                  |
      z          nKd'| d | d(}	d)d*g}
t
        j                  j                  j                  |	d&z   d&j!                  |
      z          Y w xY w)2N_torchdynamo_disableFz1Skip calling `torch.compiler.disable()`d functionzSkip calling function `z4` since it was wrapped with `torch.compiler.disable`z(Remove the `torch.compiler.disable` callr   r	  z%Call to `torch._dynamo.graph_break()`z0Called `torch._dynamo.graph_break()` with args `z`, kwargs ``z$User-inserted graph break. Message: z.Remove the `torch._dynamo.graph_break()` call.r   z<unknown qualname>r   z<unknown module>z?Dynamo developers have intentionally marked that the function `z` in file `z` should not be traced.zAvoid calling the function `z`.r   zRemove the function `z` or the file `zv` from torch/_dynamo/trace_rules.py. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch._abc	_warningsz6Dynamo does not know how to trace the Python builtin `.zIf you are attempting to call a logging function (e.g. `_warnings.warn`), you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.zKPlease file an issue on GitHub so the PyTorch team can add support for it. optreez*Dynamo cannot trace optree C/C++ function zi Consider using torch.utils._pytree - https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.py
z/Dynamo does not know how to trace the builtin `z.` This function is either a Python builtin (e.g. _warnings.warn) or a third-party C/C++ Python extension (perhaps created with pybind).zIf it is a Python builtin, please file an issue on GitHub so the PyTorch team can add support for it and see the next case for a workaround.a  If it is a third-party C/C++ Python extension, please either wrap it into a PyTorch-understood custom operator (see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html for more details) or, if it is traceable, use `torch.compiler.allow_in_graph`.allow_in_graphzFound an allow_in_graph decorator to a function which is created inside the parent function that is getting compiled. This is not supported for now.z<missing reason>z,Attempted to call function marked as skippedzmodule: z, qualname: z, skip reason: )rm   rn   r   r   r   r   r   graph_breakgetr   rq   getfilerw  r  utils	warn_oncejoinr  )r|   r=   r   r   graph_break_msgqualname	module_ormodule_namepathr   r   known_python_builtin_modulesr  s                r@   r   z"SkipFunctionVariable.call_function  s    !!$**.DeLKDJJ5djj\Auv>	 ZZ5==444$jj5O"1"D"D"F?J4&P[\b[ccdeB?BSTD	 tzz>;OPH

L$?I090A,s9~K9Ytzz2UV^U_ `  $v%<> 
 38*B? D(/z OA A ;	 EZ ++? 
 $(KKT[[5GFF";-|H:_U[T\]'	]  %Y06/D, <<'=(27  
iGE *y/C/CH/M$N{m[\]e\ffg"hK^E
 MM''11+2DtyyQVGW2WX J+VWX`Wa ba b  m;E MM''11+2DtyyQVGW2WXK%Ys   7AE4 4CI ?I c                 h    t         j                  j                  t        | j                  |            S r8   )r   r0   r<   r   r   r   s      r@   r   z%SkipFunctionVariable.call_obj_hasattr  s$    ))00T1JKKrB   rU   c                     |t         v rt        j                  | |      S t        || j                  | j
                  |      S r8   )r$   r   r   rt   r   r?   r   s      r@   r   z SkipFunctionVariable.var_getattr  s7    )),,T488b$**dkk4@@rB   r8   r  r   r=   r2   )r   r   r   r.   r  r   r   r  r   r   r   r   r   r  r  s   @r@   r  r    s     
	'	'N
 ) )f#f &f -	f
 
fPLA5 AS ArB   r  c                   H     e Zd ZdZd fdZd fdZ	 	 	 	 	 	 	 	 ddZ xZS )WrapperUserFunctionVariablea3  
    Used to represent a wrapper object that contains the actual callable as an
    attribute. For example, torch.jit.script/trace have the original function at
    their _torchdynamo_inline attribute. Similarly, functions with
    __script_if_tracing_wrapper have the original attr at "__original_fn".
    c                 @    t        |   di | || _        || _        y r  )r   r   wrapper_objattr_to_trace)r|   r  r  r   r   s       r@   r   z$WrapperUserFunctionVariable.__init__  s#    "6"&*rB   c                     || j                   k(  r[t        | j                  | j                         }| j                  xr t	        | j                  |      }t        j                  |||      S t        | !  ||      S r8   )	r  rq   r  r?   r   r.   r:   r   r   )r|   r=   rU   r>   r?   r   s        r@   r   z'WrapperUserFunctionVariable.var_getattr  si    4%%%$**D,>,>?C[[BZT%BF"((S&99w"2t,,rB   c                     t        j                  t        j                        j	                  || t        j
                  | j                        g||      S r8   )r   r   r   getattr_and_tracer   r0   r  r   s       r@   r   z)WrapperUserFunctionVariable.call_function  sL     --''

-y11$2D2DEMMv
	
rB   r  r
  r   )r   r   r   rg   r   r   r   r  r  s   @r@   r  r  	  s=    +
-

#

 &

 -	


 


rB   r  c                  R    t         j                  j                         rddlm}  | S i S )Nr   traceable_collective_remaps)r   distributedis_available)torch.distributed._functional_collectivesr  r  s    r@   _traceable_collective_remapsr  +  s&    %%'	
 +*IrB   c                     t         j                  j                         sJ d       |t               j	                         v sJ |j
                  }| j                  d      }t        ||      S )NzIllegal invocation.z)torch.distributed._functional_collectives)r   r  r  r  valuesr   import_sourcer   )r=   rr   
inner_namepath_sources       r@   _traceable_collectives_sourcer  6  sb    ))+B-BB+-/668888J""#NOKk:..rB   c                   p     e Zd ZdZd fdZedd       Zed        Zedd       Z	 	 	 	 	 	 	 	 d	dZ	 xZ
S )
!CollectiveFunctionRewriteVariablea  
    Some of the torch.distributed.* collective APIs are possible to rewrite to 'traceable' collectives.

    This class provides both a way to check if a function is remappable, and perform the remapping.

    In the case that a function is 'remappable' but only for some combinations of call-time arguments,
    we check the args at `call_function` time and fall back to graph-breaking if needed.  This is no worse
    than status-quo as we currently graph-break on all distributed.* collectives.
    c                X    t        |   |fi | t        |t              sJ || _        y r8   )r   r   r9   r   replacement_var)r|   rr   r#  r   r   s       r@   r   z*CollectiveFunctionRewriteVariable.__init__J  s.    &v&/+?@@@.rB   c                 j    t         j                  | |      \  }}t        |ft        |fd|i||d|S )Nr?   )r#  r?   )r!  rewriter   )r=   old_fnr?   optionsnew_fn
new_sources         r@   r<   z(CollectiveFunctionRewriteVariable.createO  sM    >FFr6R
0
0V
VgV
 	
 	
rB   c                 H    t        j                  |       xr | t               v S r8   )rm   
isfunctionr  )variables    r@   can_rewritez-CollectiveFunctionRewriteVariable.can_rewriteY  s%     x(WX9U9W-W	
rB   c                 8    t               |   }|t        | |      fS r8   )r  r  )r=   rr   r(  s      r@   r%  z)CollectiveFunctionRewriteVariable.rewrite_  s"    -/34R@@@rB   c                    dd l m} ddlm} t	        j
                  | j                        }t         |j                  |i |j                        }d}d|v rQ|d   j                         r>t        d| j                   d|d|d| j                   g t        j                  	       | j                  |j                  |j                  |j                   fv ro|j#                  d
      }||j$                  n|j&                  d
   j(                  }||vrt+        d|       t,        j.                  j1                  ||         |d
<   | j2                  j5                  |||      S )Nr   )REDUCE_OP_TO_STRr   async_opz)async_op=True for distributed collectivesz, args=	, kwargs=z3`torch.compile` doesn't support `async_op=True for r   opzUnsupported all_reduce op: )torch.distributedr  r  r0  rm   r   rr   rG   r   r   r   r   r   SUPPORTABLE
all_reducereduce_scatter_tensor_reduce_scatter_baser  r   r   defaultr   r   r0   r<   r#  r   )	r|   r=   r   r   distr0  r   reduce_op_var	reduce_ops	            r@   r   z/CollectiveFunctionRewriteVariable.call_functiond  sj    	)N %%dgg.	ninnd5f5??@F:$6$I$I$KC77)8dWJvi8QRVRYRYQZ[&22	 77OO&&%%
 

 #JJt,M !, ##))$/77 
  00 #>yk!JKK$55<< +F4L ##11"dFCCrB   r  r
  r   )r   r   r   rg   r   r#  r<   r-  r%  r   r  r  s   @r@   r!  r!  ?  s{    /
 
 
 
 

 A A,D#,D &,D -	,D
 
,DrB   r!  c                   0     e Zd Z	 	 	 	 	 	 	 	 d fdZ xZS )FunctoolsWrapsVariablec                 |    |s(t              dk(  rfd}t        j                  |      S t        |   ||      S )Nr+   c                     t        | t        j                        r| j                  d         S t	        d|  dg t
        j                         y )Nr   )r  zfunctools.wrapsz]`torch.compile` can't trace `functools.wraps` on functions defined outside the compile regionr   )r9   r   r   cloner   r   r5  )rr   r   s    r@   r  z3FunctoolsWrapsVariable.call_function.<locals>.wraps  sN    b)"F"FG88tAw877 -!d *66	rB   )r   r   LambdaVariabler   r   )r|   r=   r   r   r  r   s     `  r@   r   z$FunctoolsWrapsVariable.call_function  s>     #d)q.
 ++E22w$Rv66rB   r   )r   r   r   r   r  r  s   @r@   r>  r>    s3    7#7 &7 -	7
 
7 7rB   r>  c                   *    e Zd Zd Z	 	 	 	 	 	 	 	 ddZy)CollectionsNamedTupleFunctionc                     | j                   S r8   r   r{   s    r@   r   z0CollectionsNamedTupleFunction.as_python_constant  r   rB   c                 z   t        ||      }|r} | j                  |D cg c]  }|j                          c}i |j                         D ci c]  \  }}||j                          c}}}t	        j
                  |t                     S t        dd|d|dg t        j                         y c c}w c c}}w )N)mutation_typeznamedtuple constructionzargs=r2  z?`torch.compile` only support certain input types for namedtupler   )
r"   rr   r   rE   r   UserDefinedClassVariabler-   r   r   r5  )	r|   r=   r   r   constant_argsr  rI   rJ   r   s	            r@   r   z+CollectionsNamedTupleFunction.call_function  s     ,D&9DGG267Q!&&(79?HA1a**,,HE 55%5%7  	-tgZy)Y"..		
 8Hs   B2B7Nr   )r   r   r   r   r   r   rB   r@   rD  rD    s2    
#
 &
 -	

 

rB   rD  c                        e Zd Zdeddf fdZd Zd Zd Z	 	 	 	 	 	 	 	 dd
Zdd	de	defdZ
dd	de	fdZd Zd Z xZS )FunctoolsPartialVariablere   r   Nc                     t        |   di | || _        t        |t              sJ || _        t        |t              sJ || _        t        j                  t              | _        y r  )r   r   re   r9   rD   r   rG   keywordsr   r   r&   
fake_value)r|   re   r   rM  r   r   s        r@   r   z!FunctoolsPartialVariable.__init__  s\    "6"	$%%%	(D)))  $++H5rB   c                 "    t         j                  S r8   )r   r   r{   s    r@   r   z$FunctoolsPartialVariable.python_type  s       rB   c                 <   j                  fd        | j                         | j                  rj                  | j                         | j                  s2j                  t        t        | j                        dz   d             y j                  | j                  j                                t        | j                  j                               }j                  j                  t        |      t        | j                        z   dz   |d             y )Nc                  (     j                  dd      S )Nr   r   r  r  s   r@   r  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>  s    g&>&>{I&V rB   r+   F)r  re   r   foreachrM  r  r   r   r  rF   r  create_call_function_kw)r|   r@  r  s    ` r@   r?  z$FunctoolsPartialVariable.reconstruct  s    VW		99OODII&}}!!"6s499~7I5"QR,,./T]]'')*++CIDII,F,JDRWX	
rB   c                 "    | j                         S r8   r   r{   s    r@   r   z%FunctoolsPartialVariable.get_function      &&((rB   r=   r2   c                 z    | j                   |z   }i | j                  |}| j                  j                  |||      S r8   )r   rM  re   r   )r|   r=   r   r   merged_argsmerged_kwargss         r@   r   z&FunctoolsPartialVariable.call_function  s>     ii$&34==3F3yy&&r;FFrB   rU   c                     t         j                  j                  t        t	        j
                  t              |            S r8   )r   r0   r<   r   r   r   r&   r   s      r@   r   z)FunctoolsPartialVariable.call_obj_hasattr  s2     ))00I%%h/6
 	
rB   c                    | j                   xr t        | j                   |      }|dk(  r| j                  S |dk(  r!t        j                  | j
                  |      S |dk(  rW| j                  j                         D ci c]  \  }}t        j                  |      | }}}t        j                  ||      S t        t        |       y c c}}w )Nre   r   r   rM  )r?   r   re   r   ListVariabler   rM  rE   r0   r<   ConstDictVariabler   ro   )r|   r=   rU   r?   rI   rJ   rE   s          r@   r   z$FunctoolsPartialVariable.var_getattr  s    >DKK!>6>996>))$))FCC:?C}}?R?R?TUtq!%,,Q/2UEU..uVDD 4 Vs   > C	c                 :   t        j                  | j                  j                         g| j                  D cg c]  }|j                          c}i | j
                  j                         D ci c]  \  }}||j                          c}}S c c}w c c}}w r8   )r   r   re   r   r   rM  rE   )r|   r   rI   rJ   s       r@   r   z+FunctoolsPartialVariable.as_python_constant	  s      II((*
26))<3c$$&<
 6:]]5H5H5JKTQq!&&((K
 	
<K   B
1Bc                 :   t        j                  | j                  j                         g| j                  D cg c]  }|j                          c}i | j
                  j                         D ci c]  \  }}||j                          c}}S c c}w c c}}w )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants)r   r   re   guard_as_python_constantr   rM  rE   )r|   rJ   rI   s      r@   ra  z1FunctoolsPartialVariable.guard_as_python_constant  s      II..0
48II>qa((*>
 <@==;N;N;PQ41aq!,,..Q
 	
>Qr_  r   )r   r   r   r.   r   r   r?  r   r   r   r   r   r   ra  r  r  s   @r@   rK  rK    s    	6_ 	64 	6!
)G#G &G -	G
 
G
)
14
	

55 
5S 
5

rB   rK  c                       e Zd Zdddhej                  Ze ej                  d      dee	de
f   ej                  f   fd              Zed        Zdeddf fd	Zedefd
       Zd Zd Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZd Z xZS )PolyfilledFunctionVariablerr   r  traceable_fnNr   .c                     i S r8   r   )r   s    r@   _get_polyfill_handlersz1PolyfilledFunctionVariable._get_polyfill_handlers!  s	     	rB   c                 f    t        |j                  t        j                                | ||      S r   )r   r   r   r  r   s      r@   r   z-PolyfilledFunctionVariable.create_with_source&  s(    f''(C(CDE5((rB   c                 *   t        |   di | || _        | j                         j	                  ||      }t        |      sJ d| d|        dD ]"  }t        ||d       }|st        |      sJ |} n t        d| d      || _        || _	        y )NzPolyfill handler z is not callable for )__torch_dynamo_polyfill____python_implementation__z# does not have a traceable functionr   )
r   r   rr   rf  r  callablerq   r  r  rd  )r|   rr   r   handlercandidate_attr	candidaterd  r   s          r@   r   z#PolyfilledFunctionVariable.__init__,  s    "6"--/33B; X$5gY>STVSW"XX 
 	N  >I	***(	 #G9,OP  & ,rB   c                     | j                   S r8   )rd  r{   s    r@   polyfill_fnz&PolyfilledFunctionVariable.polyfill_fnC  s       rB   c                 0    t        | j                  dd      S )N*__torch_dynamo_can_constant_fold_through__F)rq   r  r{   s    r@   can_constant_fold_throughz4PolyfilledFunctionVariable.can_constant_fold_throughG  s    OOI5
 	
rB   c                 "    | j                         S r8   rU  r{   s    r@   r   z'PolyfilledFunctionVariable.get_functionL  rV  rB   c                 .   | j                         rt        ||      rt | j                  |D cg c]  }|j                          c}i |j	                         D ci c]  \  }}||j                          c}}}t        j                  ||      S | j                  t        j                  u r&t        |      dk(  r|st        |d   t        j                  t        j                  f      rt        d |d   j                  D              rt        j                  j!                  ||j"                  j%                  dt&        j(                  t+        d |d   j                  D              fi       t'        j(                  |d   j                  D cg c]4  }t        |t        j,                        r|j.                  n|j0                  6 c}            S t        j                  || j2                        }|j5                  |||      S c c}w c c}}w c c}w )Nr+   r   c              3      K   | ]n  }t        |t        j                        xr t        |j                  t              xs2 t        |t        j
                        xr |j                         t        u  p y wr8   )r9   r   r0   r   intSymNodeVariabler   )rn  r  s     r@   ro  z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>f  se        Ay99:Wz!''SV?W Yq)";";<WTWAWYs   A4A6r   c              3   <   K   | ]  }|j                           y wr8   )as_proxy)rn  as     r@   ro  z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>q  s     ?A1::<?s   )sym_num)rs  r#   rr   r   rE   r.   r:   r  sumr   r9   r   r\  TupleVariablerv  rx  r<   rM   create_proxyr   sym_sumrF   r0   r   r|  rd  r   )	r|   r=   r   r   r  rI   rJ   rH   traceable_function_variables	            r@   r   z(PolyfilledFunctionVariable.call_functionO  s    ))+0M&1
 6:;a**,;=C\\^LTQq!..00L  #((V44 GGx||#D	Q47Y%;%;Y=T=T$UV  a  ,,33		&&#MM?a??A	  "&a   *!Y-G-GH GG!"+	 4  ( '6&;&;B@Q@Q&R#*88T6JJO <L4s   HH9Hc                 b   |dk(  r| j                  |||      S t        | j                  |d       }|J d| d| j                          t        |      sJ d| d| j                          i }| j                  rt        | j                  |      |d<   t        |fi |}|j                  |||      S )N__call__zMember z not found in z is not callable in r?   )r   rq   rr   r'   r?   r   rc  )r|   r=   rU   r   r   methodr'  polyfilled_method_variables           r@   r   z&PolyfilledFunctionVariable.call_method  s     :%%b$77$-!JWTF.	#JJ!6"QgdV3Gy$QQ";; *4;; =GH%?%R'%R")77D&IIrB   c                     | j                   S r8   r   r{   s    r@   r   z-PolyfilledFunctionVariable.as_python_constant  r   rB   r   r   r   r   r   r   r.   )r   r   r   r.   r  r  r   	lru_cacherG   r   r   r\   rY   rf  r   r5   r   propertyrp  rs  r   r   r   r   r  r  s   @r@   rc  rc    s    
	'	'	N YtHS#X,>@R@R,R'S    ) )
-2 -D -. !R ! !

)2K#2K &2K -	2K
 
2KhJ &	J
 -J 
J&rB   rc  c                       e Zd Zd Zy)TracebackVariablec                      y r8   r   r   s       r@   r   zTracebackVariable.call_function  s    rB   N)r   r   r   r   r   rB   r@   r  r    s    2rB   r  c                   0     e Zd Z fdZd Zd Zd Z xZS )SysFunctionVariablec                 2    t        |   di | || _        y r  )r   r   r   )r|   r   r   r   s      r@   r   zSysFunctionVariable.__init__  s    "6"
rB   c                 h   t        |j                        rK|j                  d   }|j                  }d }t        j                  ||      |t        j                  ||      g}n>t        j                  d       t        j                  d       t        j                  d       g}t        j                  |      S )N)r   exn_vt_stackr  r.   r:   r   r0   r~  )r|   r=   exnr  tbrE   s         r@   exc_infozSysFunctionVariable.exc_info  s    r//"%C,,CB%%b#.%%b"-E **40**40**40E
 &&u--rB   c                 >    | j                  |      j                  d   S r  )r  rE   r   s     r@   	exceptionzSysFunctionVariable.exception  s    }}R &&q))rB   c                     | j                   t        j                  u r| j                  |      S | j                   t        j                  u sJ | j                  |      S r8   )r   r{  r  r  r   s       r@   r   z!SysFunctionVariable.call_function  sF    ::%==$$zzS]]***~~b!!rB   )r   r   r   r   r  r  r   r  r  s   @r@   r  r    s    .$*"rB   r  )TMADescriptorMetadataTritonHOPifierc                       e Zd ZdedefdZdedefdZdedefdZ	de
ej                  j                  j                  df   fd	Zd
 Zd Zd Zd ZdedefdZdddee   ddfdZdefdZy)DynamoTritonHOPifierr	  r   c                     t        |      r8   )r   )r|   r	  s     r@   raise_unsupportedz&DynamoTritonHOPifier.raise_unsupported  s    #rB   maybe_callablec                 .    t        |t        t        f      S r8   )r9   r   r   )r|   r  s     r@   is_callablez DynamoTritonHOPifier.is_callable  s    79MN
 	
rB   r>   c                     |j                   S r8   r  )r|   r>   s     r@   	get_valuezDynamoTritonHOPifier.get_value  s    yyrB   .c                     ddl m} t        ||      r|j                         S t	        ddt        |       dg t        j                         y )Nr+   )BaseListVariablez/unsupported grid type for triton hop check_gridzgrid type = z;`torch.compile` only supports list-like grid for check_gridr   )listsr  r9   rz  r   r  r   r5  )r|   gridr  s      r@   
check_gridzDynamoTritonHOPifier.check_grid  sK    +d,-==?"I&tDzl3Y&22	rB   c                     |j                         D ci c]%  \  }}t        j                  j                  |      |' }}}|j	                  ||gi       }|S c c}}w r8   )rE   r   r0   r<   r   )r|   r  metar=   rI   rJ   s         r@   	call_gridzDynamoTritonHOPifier.call_grid  sV    DHJJLQDAq	**11!4a7QQ!!"tfb1 Rs   *Ac                 \    ddl m} |j                  ||      }|j                  |||      }|S )Nr+   )SourcelessBuilder)builderr  r<   r   )	r|   user_fnr   r   r=   r,  r  wrapped_user_functionrH   s	            r@   call_user_defined_fnz)DynamoTritonHOPifier.call_user_defined_fn  s1    . 1 8 8W E&44RvFrB   c                 l    ddl m}  ||t        |j                  |             j	                  |      }|S )Nr+   )VariableBuilder)r  r  r   kernel_source_wrap)r|   user_objr=   r,  rU   r  wrapped_user_objs          r@   wrap_user_defined_objz*DynamoTritonHOPifier.wrap_user_defined_obj  s7    ,*
811dV=

%/ 	  rB   c                 l    |j                  |      }|D cg c]  }|j                          }}|S c c}w r8   )unpack_var_sequencera  )r|   configsr=   configs       r@   maybe_unpack_configsz)DynamoTritonHOPifier.maybe_unpack_configs  s=    --b1 DKK6224KK Ls   1rH   c                 d    |j                         s| j                  d       |j                         S )Nz`@triton.heuristics must return constant values because configs can only contain constant values.)is_python_constantr  ra  )r|   rH   s     r@   maybe_unpack_heuristic_resultz2DynamoTritonHOPifier.maybe_unpack_heuristic_result  s0    ((*""r ..00rB   r,  TritonKernelVariabler   c                     |j                   t        |      dk7  r| j                  d        t        |      |j                  |j
                  |d   |j                        S )Nr+   z7Triton kernels should be called with only a single gridr   )kernel
kernel_idxr  r  )r  r   r  r  r  r  r?   )r|   r,  r   s      r@   call_getitemz!DynamoTritonHOPifier.call_getitem	  s\     ==$D	Q""I tH~??**a"//	
 	
rB   c                 $   ddl m} ddlm} i }t	        |j                               D ]D  }||   }	t        |	t              s|	j                         ||<   |	j                  j                  ||<   F |j                         D 	ci c]%  \  }}	t        j                  j                  |      |	' }
}}	ddlm}m} |j                         D 	ci c]"  \  }}	t        |	|      r||	j#                         $ }}}	|
j                         D 	ci c]  \  }}	t        |	|      s||	 }}}	|j%                         D ][  }	|	j'                         }	t        |	t        j(                  t        j*                  f      r>| j-                  dt/        |	       d       ] |j1                  |      } ||t2              }|j4                  j7                  d|d	|j8                  ||||j;                         d
       t        j                  d       S c c}	}w c c}	}w c c}	}w )Nr+   r/   )r]  r   )kernel_side_tabletriton_kernel_wrapper_mutationz.Unexpected argument type for a Triton kernel: r  r   r   )r  constant_args_idxr  tma_descriptor_metadatar   )r  r0   dictsr]  rD   r  r9   TMADescriptorVariableto_metadatadata_ptrfrom_tensorrE   r   r<   *torch._higher_order_ops.triton_kernel_wrapr  r  r   r  realizer  rx  r  repradd_constant_argsrG   rM   r  r  rz  )r|   r,  gridscombined_args_rawr=   r0   r]  r  rI   rJ   combined_argsr  r  rI  non_constant_argsr  r  s                    r@   call_HOPzDynamoTritonHOPifier.call_HOP  s   ., :<',,./ 	>A!!$A!23-.]]_'*'(zz'='=!!$		> *//1
1 &&--a0!3
 

	
 *//1
1!-. q##%%
 
 &++-
1a!12 qD
 
 #))+ 	A		Aa)":":I<U<U!VW&&DT!WIQO	 .??N !2D9
		*&11%6+B--/		
 ))
 	
]



s   *H 
'HHN)r   r   r   r   r	   r  r   r  r  r  rF   r   fxproxyProxyr  r  r  r  r  r  r   r  r0   r  r   rB   r@   r  r    s    S U 
# 
$ 

S S %(<(<c(A"B  1C 1C 1
(
 sm
 
 	
$@
BR @
rB   r  c                        e Zd ZU ded<   ded<   ee   ed<   ded<   d fd	Z	 	 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 d fdZde	de	fdZ
 xZS )r  r3   r  r4   r  r  r   r  r   c                     |j                  dd       | _        t        |   di | t        j                  | |||       y )Nr  r   )rR   r  r   r    dynamo_triton_hopifier_singletoninit_variable)r|   r  r  r  r   r   s        r@   r   zTritonKernelVariable.__init__g  s;    #ZZ>"6"(66tVZQUVrB   c                 2    t         j                  | |||      S r8   )r  call_triton_kernelr   s       r@   r   z"TritonKernelVariable.call_functionl  s      0BB$
 	
rB   c                     |dk(  rt         j                  | |      S |dk(  rt         j                  | |||      S t        |   ||||      S )N__getitem__run)r  r  call_runr   r   )r|   r=   rU   r   r   r   s        r@   r   z TritonKernelVariable.call_methodv  sW     = 3@@tLLU]3<<T4QSTT w"2tT6::rB   r   c                 v    ddl m} ddlm} t	        ||      r  |j
                  |j                               S |S )Nr+   r/   )rx  )r  r0   tensorrx  r9   r<   evaluate_expr)r|   r   r0   rx  s       r@   specialize_symbolicz(TritonKernelVariable.specialize_symbolic  s6    .+ c?+*#**3+<+<+>??
rB   r  r   r  )r   r   r   r_   r   rw  r   r   r   r   r  r  r  s   @r@   r  r  a  s    
W

#
 &
 -	

 

; &	;
 -; 
;s s rB   r  c                   <     e Zd Z	 	 	 	 	 	 	 	 d fdZd Zd Z xZS )r  c                     t        |t        j                        sJ t        |   di | || _        || _        || _        || _        y r  )	r9   r   DataPtrVariabler   r   r  dims
block_dimselement_size)r|   r  r  r  r  r   r   s         r@   r   zTMADescriptorVariable.__init__  sH     (I$=$=>>>"6" 	$(rB   c                     | j                   D cg c]  }|j                          c}| j                  D cg c]  }|j                          c}| j                  j                         fS c c}w c c}w r8   )r  rz  r  r  )r|   dims     r@   r  z!TMADescriptorVariable.to_metadata  sT    '+yy1S\\^1'+7S\\^7&&(
 	
17s
   A*A/c                     j                   fd        j                  j                         g  j                   j                   j
                  }j                  |       j                  t        |      dz   d       y )Nc                  V     j                  ddt        j                         d      S )Nz$triton.tools.experimental_descriptorcreate_d_tma_descriptor)r  r   r  )r@  r|   s   r@   r  z3TMADescriptorVariable.reconstruct.<locals>.<lambda>  s+    G,,6#dii.))9: rB   r+   F)	r  r  r?  r  r  r  rR  r   r   )r|   r@  r   s   `` r@   r?  z!TMADescriptorVariable.reconstruct  sp    	
 	!!'*@@T__@d.?.?@c$i!mU3rB   )r  zvariables.DataPtrVariabler  list[ConstantVariable]r  r  r  r0   )r   r   r   r   r  r?  r  r  s   @r@   r  r    s8    )-) ') -	)
 ))

4rB   r  c                   @     e Zd Zdeddf fdZ	 	 	 	 	 	 	 	 ddZ xZS )CreateTMADescriptorVariablerankr   Nc                 >    |dv sJ t        |   di | || _        y )N)r+   r   r   )r   r   r  )r|   r  r   r   s      r@   r   z$CreateTMADescriptorVariable.__init__  s(    
 v~~"6"	rB   c                    d|v r|d   n|d   }t        |t        j                        st        d| j                   d      | j                  dk(  r;t        |      t        |      z   dk(  sJ d|v r|d   n|d   g}d|v r|d   n|d	   g}nTt        |      t        |      z   d
k(  sJ d|v r|d   n|d   d|v r|d   n|d	   g}d|v r|d   n|d   d|v r|d   n|d   g}d|v r|d   n|d   }t        ||||      S )Nptrr   z8Please ensure there were no graph breaks between create_z3d_tma_descriptor and the upstream .data_ptr() call.r+      r  	block_dimr      dim1dim0
block_dim1rq  
block_dim0r  r  )r  r  r  r  )r9   r   r  r   r  r   r  )r|   r=   r   r   r  r  r  r  s           r@   r   z)CreateTMADescriptorVariable.call_function  sa     %fUmDG#y889)) %$$  99>t9s6{*a///!&&ud1gD (3f'<{#$q'J t9s6{*a///"(F"2vQ"(F"2vQD
 )5(>|$DG(4(>|$DGJ 2@61Ivn-tTVx$!%	
 	
rB   r   )r   r   r   rw  r   r   r  r  s   @r@   r  r    sE     
	(
#(
 &(
 -	(

 
(
rB   r  r8   r
  )nrg   r  r   rm   r^   r{  r\   collections.abcr   typingr   r   r   r   r   typing_extensionsr	   unittest.mockr
   r   r  r   r   r   bytecode_transformationr   r   r   rc  r   r   r   r   r   r   r   r   r   r   guardsr   r   r?   r   r   r    r!   r  r"   r#   r$   r%   r&   r'   r(   r)   r*   baser,   r-   r.   r  r0   #torch.distributed.fsdp._fully_shardr1   ModuleNotFoundErrorr8  r2   r  r3   r4   r5   rA   rK   rG   r   rW   rf   rp   rt   rv   r   r  r%  r  r  r  r  r  r  r   r   r  r  r  r  r!  r>  rD  rK  rc  r  r  r  r  r  r  r  r  r  r   rB   r@   <module>r     sP  .     
  $ B B #   6 6 V V   1 N N
 
 
 = < &E
 D T"	A. $sO';"<  "( -" DQ73 Q7h:4 :<y4? y4x	
 
4
%= 4
n"<V-- V-r 2 ("6 ( NA!9 NAbGA? GAT
/ 
D/QD(< QDh71 74
$8 
:L
 L
^~ ~B3 3
"/ "BU
> U
p $8#9  +? +\!4O !4H2
/ 2
W;  s   &H HH